Completed
Push — try/jetpack-options-package-cl... ( 66c62f...07827f )
by
unknown
251:04 queued 244:15
created

class.jetpack.php (33 issues)

Upgrade to new PHP Analysis Engine

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

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

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

Loading history...
453
	 */
454
	static function update_active_modules( $modules ) {
455
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
456
		$active_modules       = Jetpack::get_active_modules();
457
		$new_active_modules   = array_diff( $modules, $current_modules );
458
		$new_inactive_modules = array_diff( $active_modules, $modules );
459
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
460
		$reindexed_modules    = array_values( $new_current_modules );
461
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
462
463
		foreach ( $new_active_modules as $module ) {
464
			/**
465
			 * Fires when a specific module is activated.
466
			 *
467
			 * @since 1.9.0
468
			 *
469
			 * @param string $module Module slug.
470
			 * @param boolean $success whether the module was activated. @since 4.2
471
			 */
472
			do_action( 'jetpack_activate_module', $module, $success );
473
			/**
474
			 * Fires when a module is activated.
475
			 * The dynamic part of the filter, $module, is the module slug.
476
			 *
477
			 * @since 1.9.0
478
			 *
479
			 * @param string $module Module slug.
480
			 */
481
			do_action( "jetpack_activate_module_$module", $module );
482
		}
483
484
		foreach ( $new_inactive_modules as $module ) {
485
			/**
486
			 * Fired after a module has been deactivated.
487
			 *
488
			 * @since 4.2.0
489
			 *
490
			 * @param string $module Module slug.
491
			 * @param boolean $success whether the module was deactivated.
492
			 */
493
			do_action( 'jetpack_deactivate_module', $module, $success );
494
			/**
495
			 * Fires when a module is deactivated.
496
			 * The dynamic part of the filter, $module, is the module slug.
497
			 *
498
			 * @since 1.9.0
499
			 *
500
			 * @param string $module Module slug.
501
			 */
502
			do_action( "jetpack_deactivate_module_$module", $module );
503
		}
504
505
		return $success;
506
	}
507
508
	static function delete_active_modules() {
509
		self::update_active_modules( array() );
510
	}
511
512
	/**
513
	 * Constructor.  Initializes WordPress hooks
514
	 */
515
	private function __construct() {
516
		/*
517
		 * Check for and alert any deprecated hooks
518
		 */
519
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
520
521
		/*
522
		 * Enable enhanced handling of previewing sites in Calypso
523
		 */
524
		if ( Jetpack::is_active() ) {
525
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
526
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
527
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
528
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
529
		}
530
531
		/*
532
		 * Load things that should only be in Network Admin.
533
		 *
534
		 * For now blow away everything else until a more full
535
		 * understanding of what is needed at the network level is
536
		 * available
537
		 */
538
		if ( is_multisite() ) {
539
			Jetpack_Network::init();
540
		}
541
542
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
543
			return function() {
544
				return wp_generate_password( 32, false );
545
			};
546
		} );
547
548
		$this->connection_manager = new Connection_Manager( );
549
550
		/**
551
		 * Prepare Gutenberg Editor functionality
552
		 */
553
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
554
		Jetpack_Gutenberg::init();
555
		Jetpack_Gutenberg::load_independent_blocks();
556
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
557
558
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
559
560
		// Unlink user before deleting the user from .com
561
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
562
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
563
564
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
565
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
566
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
567
				define( 'XMLRPC_REQUEST', true );
568
			}
569
570
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
571
572
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
573
		}
574
575
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
576
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
577
578
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
579
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
580
581
			$this->require_jetpack_authentication();
582
583
			if ( Jetpack::is_active() ) {
584
				// Hack to preserve $HTTP_RAW_POST_DATA
585
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
586
587
				$signed = $this->verify_xml_rpc_signature();
588 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
589
					// The actual API methods.
590
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
591
				} else {
592
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
593
					// active Jetpack connection, so that additional users can link their account.
594
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
595
				}
596 View Code Duplication
			} else {
597
				// The bootstrap API methods.
598
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
599
				$signed = $this->verify_xml_rpc_signature();
600
				if ( $signed && ! is_wp_error( $signed ) ) {
601
					// the jetpack Provision method is available for blog-token-signed requests
602
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
603
				}
604
			}
605
606
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
607
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
608
		} elseif (
609
			is_admin() &&
610
			isset( $_POST['action'] ) && (
611
				'jetpack_upload_file' == $_POST['action'] ||
612
				'jetpack_update_file' == $_POST['action']
613
			)
614
		) {
615
			$this->require_jetpack_authentication();
616
			$this->add_remote_request_handlers();
617
		} else {
618
			if ( Jetpack::is_active() ) {
619
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
620
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
621
			}
622
		}
623
624
		if ( Jetpack::is_active() ) {
625
			Jetpack_Heartbeat::init();
626
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
627
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
628
				Jetpack_Search_Performance_Logger::init();
629
			}
630
		}
631
632
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
633
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
634
635
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
636
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
637
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
638
		}
639
640
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
641
642
		add_action( 'admin_init', array( $this, 'admin_init' ) );
643
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
644
645
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
646
647
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
648
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
649
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
650
651
		// returns HTTPS support status
652
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
653
654
		// JITM AJAX callback function
655
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
656
657
		// Universal ajax callback for all tracking events triggered via js
658
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
659
660
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
661
662
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
663
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
664
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
665
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
666
667
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
668
669
		/**
670
		 * These actions run checks to load additional files.
671
		 * They check for external files or plugins, so they need to run as late as possible.
672
		 */
673
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
674
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
675
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
676
677
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
678
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
679
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
680
681
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
682
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
683
684
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
685
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
686
687
		// A filter to control all just in time messages
688
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
689
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
690
691
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
692
		// We should make sure to only do this for front end links.
693
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
694
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
695
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
696
697
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
698
			//so they point moderation links on emails to Calypso
699
			jetpack_require_lib( 'functions.wp-notify' );
700
		}
701
702
		// Update the Jetpack plan from API on heartbeats
703
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
704
705
		/**
706
		 * This is the hack to concatenate all css files into one.
707
		 * For description and reasoning see the implode_frontend_css method
708
		 *
709
		 * Super late priority so we catch all the registered styles
710
		 */
711
		if( !is_admin() ) {
712
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
713
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
714
		}
715
716
		/**
717
		 * These are sync actions that we need to keep track of for jitms
718
		 */
719
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
720
721
		// Actually push the stats on shutdown.
722
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
723
			add_action( 'shutdown', array( $this, 'push_stats' ) );
724
		}
725
	}
726
727
	/**
728
	 * This is ported over from the manage module, which has been deprecated and baked in here.
729
	 *
730
	 * @param $domains
731
	 */
732
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
733
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
734
	}
735
736
	/**
737
	 * Return $domains, with 'wordpress.com' appended.
738
	 * This is ported over from the manage module, which has been deprecated and baked in here.
739
	 *
740
	 * @param $domains
741
	 * @return array
742
	 */
743
	function allow_wpcom_domain( $domains ) {
744
		if ( empty( $domains ) ) {
745
			$domains = array();
746
		}
747
		$domains[] = 'wordpress.com';
748
		return array_unique( $domains );
749
	}
750
751
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
752
		$post = get_post( $post_id );
753
754
		if ( empty( $post ) ) {
755
			return $default_url;
756
		}
757
758
		$post_type = $post->post_type;
759
760
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
761
		// https://en.support.wordpress.com/custom-post-types/
762
		$allowed_post_types = array(
763
			'post' => 'post',
764
			'page' => 'page',
765
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
766
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
767
		);
768
769
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
770
			return $default_url;
771
		}
772
773
		$path_prefix = $allowed_post_types[ $post_type ];
774
775
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
776
777
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
778
	}
779
780
	function point_edit_comment_links_to_calypso( $url ) {
781
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
782
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
The variable $query_args does not exist. Did you forget to declare it?

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1774
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1775
	}
1776
1777
	/**
1778
	 * Gets current user IP address.
1779
	 *
1780
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1781
	 *
1782
	 * @return string                  Current user IP address.
1783
	 */
1784
	public static function current_user_ip( $check_all_headers = false ) {
1785
		if ( $check_all_headers ) {
1786
			foreach ( array(
1787
				'HTTP_CF_CONNECTING_IP',
1788
				'HTTP_CLIENT_IP',
1789
				'HTTP_X_FORWARDED_FOR',
1790
				'HTTP_X_FORWARDED',
1791
				'HTTP_X_CLUSTER_CLIENT_IP',
1792
				'HTTP_FORWARDED_FOR',
1793
				'HTTP_FORWARDED',
1794
				'HTTP_VIA',
1795
			) as $key ) {
1796
				if ( ! empty( $_SERVER[ $key ] ) ) {
1797
					return $_SERVER[ $key ];
1798
				}
1799
			}
1800
		}
1801
1802
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1803
	}
1804
1805
	/**
1806
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1807
	 */
1808
	function extra_oembed_providers() {
1809
		// Cloudup: https://dev.cloudup.com/#oembed
1810
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1811
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1812
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1813
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1814
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1815
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1816
	}
1817
1818
	/**
1819
	 * Synchronize connected user role changes
1820
	 */
1821
	function user_role_change( $user_id ) {
1822
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1823
		Jetpack_Sync_Users::user_role_change( $user_id );
1824
	}
1825
1826
	/**
1827
	 * Loads the private module if it has been activated.
1828
	 * Else, updates the admin dashboard with the site's private status.
1829
	 */
1830
	public static function load_private() {
1831
		if ( self::is_module_active( 'private' ) ) {
1832
			self::load_modules( array( 'private' ) );
1833
		} else {
1834
			add_action( 'update_right_now_text', array( __CLASS__, 'add_public_dashboard_glance_items' ) );
1835
			add_action( 'admin_enqueue_scripts', array( __CLASS__, 'wp_admin_glance_dashboard_style' ) );
1836
			add_filter( 'privacy_on_link_text', array( __CLASS__, 'private_site_privacy_on_link_text' ) );
1837
		}
1838
	}
1839
1840
	/**
1841
	 * Adds a line break for the 'Search Engines Discouraged' message
1842
	 * displayed in the 'At a Glance' dashboard widget.
1843
	 *
1844
	 * @param string $content Content of 'At A Glance' wp-admin dashboard widget.
1845
	 * @return string The modified content of the 'At a Glance' dashboard widget.
1846
	 */
1847
1848
	public static function private_site_privacy_on_link_text( $content ) {
1849
		return '<br>' . $content;
1850
	}
1851
1852
	/**
1853
	 * Basic styling for the wp-admin 'At a Glance' dashboard widget.
1854
	 * This is applied when the private module is inactive.
1855
	 *
1856
	 * @param string $hook Page Hook Suffix for the current page.
1857
	 */
1858
	public static function wp_admin_glance_dashboard_style( $hook ) {
1859
		if ( 'index.php' !== $hook ) {
1860
			return;
1861
		}
1862
1863
		$custom_css = '
1864
			.jp-at-a-glance__site-public {
1865
				color: #46B450;
1866
			}
1867
		';
1868
		wp_add_inline_style( 'dashboard', $custom_css );
1869
	}
1870
1871
	/**
1872
	 * Adds a message to the 'At a Glance' dashboard widget.
1873
	 *
1874
	 * @param string $content Content of 'At A Glance' wp-admin dashboard widget.
1875
	 * @return string The modified content of the 'At a Glance' dashboard widget.
1876
	 */
1877 View Code Duplication
	public static function add_public_dashboard_glance_items( $content ) {
1878
		return
1879
			$content .
1880
			'<br><br>' .
1881
			wp_kses(
1882
				sprintf(
1883
					/* translators: URL for Jetpack dashboard. */
1884
					__( '<span class="%1$1s">This site is set to public.</span> <a href="%2$2s">Make private</a>.', 'jetpack' ),
1885
					esc_attr( 'jp-at-a-glance__site-public' ),
1886
					esc_url( admin_url( 'admin.php?page=jetpack#/security?term=private' ) )
1887
				),
1888
				array(
1889
					'a' => array( 'href' => true ),
1890
					'span' => array( 'class' => true ),
1891
				)
1892
			);
1893
	}
1894
1895
	/**
1896
	 * Loads modules from given array, otherwise all the currently active modules.
1897
	 *
1898
	 * @param array $modules Specific modules to be loaded.
1899
	 */
1900
	public static function load_modules( $modules = array() ) {
1901
		if (
1902
			! self::is_active()
1903
			&& ! self::is_development_mode()
1904
			&& ! self::is_onboarding()
1905
			&& (
1906
				! is_multisite()
1907
				|| ! get_site_option( 'jetpack_protect_active' )
1908
			)
1909
		) {
1910
			return;
1911
		}
1912
1913
		$version = Jetpack_Options::get_option( 'version' );
1914 View Code Duplication
		if ( ! $version ) {
1915
			$version = $old_version = JETPACK__VERSION . ':' . time();
1916
			/** This action is documented in class.jetpack.php */
1917
			do_action( 'updating_jetpack_version', $version, false );
1918
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1919
		}
1920
		list( $version )            = explode( ':', $version );
1921
		$fetched_all_active_modules = false;
1922
1923
		if ( empty( $modules ) ) {
1924
			$modules                    = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1925
			$fetched_all_active_modules = true;
1926
		}
1927
1928
		$modules_data = array();
1929
1930
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1931
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1932
			$updated_modules = array();
1933
			foreach ( $modules as $module ) {
1934
				$modules_data[ $module ] = Jetpack::get_module( $module );
1935
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1936
					continue;
1937
				}
1938
1939
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1940
					continue;
1941
				}
1942
1943
				$updated_modules[] = $module;
1944
			}
1945
1946
			$modules = array_diff( $modules, $updated_modules );
1947
		}
1948
1949
		$is_development_mode = Jetpack::is_development_mode();
1950
1951
		foreach ( $modules as $index => $module ) {
1952
			// If we're in dev mode, disable modules requiring a connection
1953
			if ( $is_development_mode ) {
1954
				// Prime the pump if we need to
1955
				if ( empty( $modules_data[ $module ] ) ) {
1956
					$modules_data[ $module ] = Jetpack::get_module( $module );
1957
				}
1958
				// If the module requires a connection, but we're in local mode, don't include it.
1959
				if ( $modules_data[ $module ]['requires_connection'] ) {
1960
					continue;
1961
				}
1962
			}
1963
1964
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1965
				continue;
1966
			}
1967
1968
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1969
				unset( $modules[ $index ] );
1970
				self::update_active_modules( array_values( $modules ) );
1971
				continue;
1972
			}
1973
1974
			/**
1975
			 * Fires when a specific module is loaded.
1976
			 * The dynamic part of the hook, $module, is the module slug.
1977
			 *
1978
			 * @since 1.1.0
1979
			 */
1980
			do_action( 'jetpack_module_loaded_' . $module );
1981
		}
1982
1983
		if ( $fetched_all_active_modules ) {
1984
			/**
1985
			* Fires when all the modules are loaded.
1986
			*
1987
			* @since 1.1.0
1988
			*/
1989
			do_action( 'jetpack_modules_loaded' );
1990
		}
1991
1992
		// 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.
1993
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1994
	}
1995
1996
	/**
1997
	 * Check if Jetpack's REST API compat file should be included
1998
	 * @action plugins_loaded
1999
	 * @return null
2000
	 */
2001
	public function check_rest_api_compat() {
2002
		/**
2003
		 * Filters the list of REST API compat files to be included.
2004
		 *
2005
		 * @since 2.2.5
2006
		 *
2007
		 * @param array $args Array of REST API compat files to include.
2008
		 */
2009
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2010
2011
		if ( function_exists( 'bbpress' ) )
2012
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
2013
2014
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
2015
			require_once $_jetpack_rest_api_compat_include;
2016
	}
2017
2018
	/**
2019
	 * Gets all plugins currently active in values, regardless of whether they're
2020
	 * traditionally activated or network activated.
2021
	 *
2022
	 * @todo Store the result in core's object cache maybe?
2023
	 */
2024
	public static function get_active_plugins() {
2025
		$active_plugins = (array) get_option( 'active_plugins', array() );
2026
2027
		if ( is_multisite() ) {
2028
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2029
			// whereas active_plugins stores them in the values.
2030
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2031
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2032
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2033
			}
2034
		}
2035
2036
		sort( $active_plugins );
2037
2038
		return array_unique( $active_plugins );
2039
	}
2040
2041
	/**
2042
	 * Gets and parses additional plugin data to send with the heartbeat data
2043
	 *
2044
	 * @since 3.8.1
2045
	 *
2046
	 * @return array Array of plugin data
2047
	 */
2048
	public static function get_parsed_plugin_data() {
2049
		if ( ! function_exists( 'get_plugins' ) ) {
2050
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
2051
		}
2052
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2053
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2054
		$active_plugins = Jetpack::get_active_plugins();
2055
2056
		$plugins = array();
2057
		foreach ( $all_plugins as $path => $plugin_data ) {
2058
			$plugins[ $path ] = array(
2059
					'is_active' => in_array( $path, $active_plugins ),
2060
					'file'      => $path,
2061
					'name'      => $plugin_data['Name'],
2062
					'version'   => $plugin_data['Version'],
2063
					'author'    => $plugin_data['Author'],
2064
			);
2065
		}
2066
2067
		return $plugins;
2068
	}
2069
2070
	/**
2071
	 * Gets and parses theme data to send with the heartbeat data
2072
	 *
2073
	 * @since 3.8.1
2074
	 *
2075
	 * @return array Array of theme data
2076
	 */
2077
	public static function get_parsed_theme_data() {
2078
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2079
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2080
2081
		$themes = array();
2082
		foreach ( $all_themes as $slug => $theme_data ) {
2083
			$theme_headers = array();
2084
			foreach ( $header_keys as $header_key ) {
2085
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2086
			}
2087
2088
			$themes[ $slug ] = array(
2089
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2090
					'slug' => $slug,
2091
					'theme_root' => $theme_data->get_theme_root_uri(),
2092
					'parent' => $theme_data->parent(),
2093
					'headers' => $theme_headers
2094
			);
2095
		}
2096
2097
		return $themes;
2098
	}
2099
2100
	/**
2101
	 * Checks whether a specific plugin is active.
2102
	 *
2103
	 * We don't want to store these in a static variable, in case
2104
	 * there are switch_to_blog() calls involved.
2105
	 */
2106
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2107
		return in_array( $plugin, self::get_active_plugins() );
2108
	}
2109
2110
	/**
2111
	 * Check if Jetpack's Open Graph tags should be used.
2112
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2113
	 *
2114
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2115
	 * @action plugins_loaded
2116
	 * @return null
2117
	 */
2118
	public function check_open_graph() {
2119
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2120
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2121
		}
2122
2123
		$active_plugins = self::get_active_plugins();
2124
2125
		if ( ! empty( $active_plugins ) ) {
2126
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2127
				if ( in_array( $plugin, $active_plugins ) ) {
2128
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2129
					break;
2130
				}
2131
			}
2132
		}
2133
2134
		/**
2135
		 * Allow the addition of Open Graph Meta Tags to all pages.
2136
		 *
2137
		 * @since 2.0.3
2138
		 *
2139
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2140
		 */
2141
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2142
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2143
		}
2144
	}
2145
2146
	/**
2147
	 * Check if Jetpack's Twitter tags should be used.
2148
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2149
	 *
2150
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2151
	 * @action plugins_loaded
2152
	 * @return null
2153
	 */
2154
	public function check_twitter_tags() {
2155
2156
		$active_plugins = self::get_active_plugins();
2157
2158
		if ( ! empty( $active_plugins ) ) {
2159
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2160
				if ( in_array( $plugin, $active_plugins ) ) {
2161
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2162
					break;
2163
				}
2164
			}
2165
		}
2166
2167
		/**
2168
		 * Allow Twitter Card Meta tags to be disabled.
2169
		 *
2170
		 * @since 2.6.0
2171
		 *
2172
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2173
		 */
2174
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2175
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2176
		}
2177
	}
2178
2179
	/**
2180
	 * Allows plugins to submit security reports.
2181
 	 *
2182
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2183
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2184
	 * @param array   $args         See definitions above
2185
	 */
2186
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2187
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2188
	}
2189
2190
/* Jetpack Options API */
2191
2192
	public static function get_option_names( $type = 'compact' ) {
2193
		return Jetpack_Options::get_option_names( $type );
2194
	}
2195
2196
	/**
2197
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2198
 	 *
2199
	 * @param string $name    Option name
2200
	 * @param mixed  $default (optional)
2201
	 */
2202
	public static function get_option( $name, $default = false ) {
2203
		return Jetpack_Options::get_option( $name, $default );
2204
	}
2205
2206
	/**
2207
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2208
 	 *
2209
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2210
	 * @param string $name  Option name
2211
	 * @param mixed  $value Option value
2212
	 */
2213
	public static function update_option( $name, $value ) {
2214
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2215
		return Jetpack_Options::update_option( $name, $value );
2216
	}
2217
2218
	/**
2219
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2220
 	 *
2221
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2222
	 * @param array $array array( option name => option value, ... )
2223
	 */
2224
	public static function update_options( $array ) {
2225
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2226
		return Jetpack_Options::update_options( $array );
2227
	}
2228
2229
	/**
2230
	 * Deletes the given option.  May be passed multiple option names as an array.
2231
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2232
	 *
2233
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2234
	 * @param string|array $names
2235
	 */
2236
	public static function delete_option( $names ) {
2237
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2238
		return Jetpack_Options::delete_option( $names );
2239
	}
2240
2241
	/**
2242
	 * Enters a user token into the user_tokens option
2243
	 *
2244
	 * @param int $user_id
2245
	 * @param string $token
2246
	 * return bool
2247
	 */
2248
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2249
		// not designed for concurrent updates
2250
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2251
		if ( ! is_array( $user_tokens ) )
2252
			$user_tokens = array();
2253
		$user_tokens[$user_id] = $token;
2254
		if ( $is_master_user ) {
2255
			$master_user = $user_id;
2256
			$options     = compact( 'user_tokens', 'master_user' );
2257
		} else {
2258
			$options = compact( 'user_tokens' );
2259
		}
2260
		return Jetpack_Options::update_options( $options );
2261
	}
2262
2263
	/**
2264
	 * Returns an array of all PHP files in the specified absolute path.
2265
	 * Equivalent to glob( "$absolute_path/*.php" ).
2266
	 *
2267
	 * @param string $absolute_path The absolute path of the directory to search.
2268
	 * @return array Array of absolute paths to the PHP files.
2269
	 */
2270
	public static function glob_php( $absolute_path ) {
2271
		if ( function_exists( 'glob' ) ) {
2272
			return glob( "$absolute_path/*.php" );
2273
		}
2274
2275
		$absolute_path = untrailingslashit( $absolute_path );
2276
		$files = array();
2277
		if ( ! $dir = @opendir( $absolute_path ) ) {
2278
			return $files;
2279
		}
2280
2281
		while ( false !== $file = readdir( $dir ) ) {
2282
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2283
				continue;
2284
			}
2285
2286
			$file = "$absolute_path/$file";
2287
2288
			if ( ! is_file( $file ) ) {
2289
				continue;
2290
			}
2291
2292
			$files[] = $file;
2293
		}
2294
2295
		closedir( $dir );
2296
2297
		return $files;
2298
	}
2299
2300
	public static function activate_new_modules( $redirect = false ) {
2301
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2302
			return;
2303
		}
2304
2305
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2306 View Code Duplication
		if ( ! $jetpack_old_version ) {
2307
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2308
			/** This action is documented in class.jetpack.php */
2309
			do_action( 'updating_jetpack_version', $version, false );
2310
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2311
		}
2312
2313
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2314
2315
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2316
			return;
2317
		}
2318
2319
		$active_modules     = Jetpack::get_active_modules();
2320
		$reactivate_modules = array();
2321
		foreach ( $active_modules as $active_module ) {
2322
			$module = Jetpack::get_module( $active_module );
2323
			if ( ! isset( $module['changed'] ) ) {
2324
				continue;
2325
			}
2326
2327
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2328
				continue;
2329
			}
2330
2331
			$reactivate_modules[] = $active_module;
2332
			Jetpack::deactivate_module( $active_module );
2333
		}
2334
2335
		$new_version = JETPACK__VERSION . ':' . time();
2336
		/** This action is documented in class.jetpack.php */
2337
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2338
		Jetpack_Options::update_options(
2339
			array(
2340
				'version'     => $new_version,
2341
				'old_version' => $jetpack_old_version,
2342
			)
2343
		);
2344
2345
		Jetpack::state( 'message', 'modules_activated' );
2346
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2347
2348
		if ( $redirect ) {
2349
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2350
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2351
				$page = $_GET['page'];
2352
			}
2353
2354
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2355
			exit;
2356
		}
2357
	}
2358
2359
	/**
2360
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2361
	 * Make sure to tuck away module "library" files in a sub-directory.
2362
	 */
2363
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2364
		static $modules = null;
2365
2366
		if ( ! isset( $modules ) ) {
2367
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2368
			// Use the cache if we're on the front-end and it's available...
2369
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2370
				$modules = $available_modules_option[ JETPACK__VERSION ];
2371
			} else {
2372
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2373
2374
				$modules = array();
2375
2376
				foreach ( $files as $file ) {
2377
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2378
						continue;
2379
					}
2380
2381
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2382
				}
2383
2384
				Jetpack_Options::update_option( 'available_modules', array(
2385
					JETPACK__VERSION => $modules,
2386
				) );
2387
			}
2388
		}
2389
2390
		/**
2391
		 * Filters the array of modules available to be activated.
2392
		 *
2393
		 * @since 2.4.0
2394
		 *
2395
		 * @param array $modules Array of available modules.
2396
		 * @param string $min_version Minimum version number required to use modules.
2397
		 * @param string $max_version Maximum version number required to use modules.
2398
		 */
2399
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2400
2401
		if ( ! $min_version && ! $max_version ) {
2402
			return array_keys( $mods );
2403
		}
2404
2405
		$r = array();
2406
		foreach ( $mods as $slug => $introduced ) {
2407
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2408
				continue;
2409
			}
2410
2411
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2412
				continue;
2413
			}
2414
2415
			$r[] = $slug;
2416
		}
2417
2418
		return $r;
2419
	}
2420
2421
	/**
2422
	 * Default modules loaded on activation.
2423
	 */
2424
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2425
		$return = array();
2426
2427
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2428
			$module_data = Jetpack::get_module( $module );
2429
2430
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2431
				case 'yes' :
2432
					$return[] = $module;
2433
					break;
2434
				case 'public' :
2435
					if ( Jetpack_Options::get_option( 'public' ) ) {
2436
						$return[] = $module;
2437
					}
2438
					break;
2439
				case 'no' :
2440
				default :
2441
					break;
2442
			}
2443
		}
2444
		/**
2445
		 * Filters the array of default modules.
2446
		 *
2447
		 * @since 2.5.0
2448
		 *
2449
		 * @param array $return Array of default modules.
2450
		 * @param string $min_version Minimum version number required to use modules.
2451
		 * @param string $max_version Maximum version number required to use modules.
2452
		 */
2453
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2454
	}
2455
2456
	/**
2457
	 * Checks activated modules during auto-activation to determine
2458
	 * if any of those modules are being deprecated.  If so, close
2459
	 * them out, and add any replacement modules.
2460
	 *
2461
	 * Runs at priority 99 by default.
2462
	 *
2463
	 * This is run late, so that it can still activate a module if
2464
	 * the new module is a replacement for another that the user
2465
	 * currently has active, even if something at the normal priority
2466
	 * would kibosh everything.
2467
	 *
2468
	 * @since 2.6
2469
	 * @uses jetpack_get_default_modules filter
2470
	 * @param array $modules
2471
	 * @return array
2472
	 */
2473
	function handle_deprecated_modules( $modules ) {
2474
		$deprecated_modules = array(
2475
			'debug'            => null,  // Closed out and moved to the debugger library.
2476
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2477
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2478
		);
2479
2480
		// Don't activate SSO if they never completed activating WPCC.
2481
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2482
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2483
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2484
				$deprecated_modules['wpcc'] = null;
2485
			}
2486
		}
2487
2488
		foreach ( $deprecated_modules as $module => $replacement ) {
2489
			if ( Jetpack::is_module_active( $module ) ) {
2490
				self::deactivate_module( $module );
2491
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2492
					$modules[] = $replacement;
2493
				}
2494
			}
2495
		}
2496
2497
		return array_unique( $modules );
2498
	}
2499
2500
	/**
2501
	 * Checks activated plugins during auto-activation to determine
2502
	 * if any of those plugins are in the list with a corresponding module
2503
	 * that is not compatible with the plugin. The module will not be allowed
2504
	 * to auto-activate.
2505
	 *
2506
	 * @since 2.6
2507
	 * @uses jetpack_get_default_modules filter
2508
	 * @param array $modules
2509
	 * @return array
2510
	 */
2511
	function filter_default_modules( $modules ) {
2512
2513
		$active_plugins = self::get_active_plugins();
2514
2515
		if ( ! empty( $active_plugins ) ) {
2516
2517
			// For each module we'd like to auto-activate...
2518
			foreach ( $modules as $key => $module ) {
2519
				// If there are potential conflicts for it...
2520
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2521
					// For each potential conflict...
2522
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2523
						// If that conflicting plugin is active...
2524
						if ( in_array( $plugin, $active_plugins ) ) {
2525
							// Remove that item from being auto-activated.
2526
							unset( $modules[ $key ] );
2527
						}
2528
					}
2529
				}
2530
			}
2531
		}
2532
2533
		return $modules;
2534
	}
2535
2536
	/**
2537
	 * Extract a module's slug from its full path.
2538
	 */
2539
	public static function get_module_slug( $file ) {
2540
		return str_replace( '.php', '', basename( $file ) );
2541
	}
2542
2543
	/**
2544
	 * Generate a module's path from its slug.
2545
	 */
2546
	public static function get_module_path( $slug ) {
2547
		/**
2548
		 * Filters the path of a modules.
2549
		 *
2550
		 * @since 7.4.0
2551
		 *
2552
		 * @param array $return The absolute path to a module's root php file
2553
		 * @param string $slug The module slug
2554
		 */
2555
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2556
	}
2557
2558
	/**
2559
	 * Load module data from module file. Headers differ from WordPress
2560
	 * plugin headers to avoid them being identified as standalone
2561
	 * plugins on the WordPress plugins page.
2562
	 */
2563
	public static function get_module( $module ) {
2564
		$headers = array(
2565
			'name'                      => 'Module Name',
2566
			'description'               => 'Module Description',
2567
			'jumpstart_desc'            => 'Jumpstart Description',
2568
			'sort'                      => 'Sort Order',
2569
			'recommendation_order'      => 'Recommendation Order',
2570
			'introduced'                => 'First Introduced',
2571
			'changed'                   => 'Major Changes In',
2572
			'deactivate'                => 'Deactivate',
2573
			'free'                      => 'Free',
2574
			'requires_connection'       => 'Requires Connection',
2575
			'auto_activate'             => 'Auto Activate',
2576
			'module_tags'               => 'Module Tags',
2577
			'feature'                   => 'Feature',
2578
			'additional_search_queries' => 'Additional Search Queries',
2579
			'plan_classes'              => 'Plans',
2580
		);
2581
2582
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2583
2584
		$mod = Jetpack::get_file_data( $file, $headers );
2585
		if ( empty( $mod['name'] ) ) {
2586
			return false;
2587
		}
2588
2589
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2590
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2591
		$mod['deactivate']              = empty( $mod['deactivate'] );
2592
		$mod['free']                    = empty( $mod['free'] );
2593
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2594
2595
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2596
			$mod['auto_activate'] = 'No';
2597
		} else {
2598
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2599
		}
2600
2601
		if ( $mod['module_tags'] ) {
2602
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2603
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2604
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2605
		} else {
2606
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2607
		}
2608
2609 View Code Duplication
		if ( $mod['plan_classes'] ) {
2610
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2611
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2612
		} else {
2613
			$mod['plan_classes'] = array( 'free' );
2614
		}
2615
2616 View Code Duplication
		if ( $mod['feature'] ) {
2617
			$mod['feature'] = explode( ',', $mod['feature'] );
2618
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2619
		} else {
2620
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2621
		}
2622
2623
		/**
2624
		 * Filters the feature array on a module.
2625
		 *
2626
		 * This filter allows you to control where each module is filtered: Recommended,
2627
		 * Jumpstart, and the default "Other" listing.
2628
		 *
2629
		 * @since 3.5.0
2630
		 *
2631
		 * @param array   $mod['feature'] The areas to feature this module:
2632
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2633
		 *     'Recommended' shows on the main Jetpack admin screen.
2634
		 *     'Other' should be the default if no other value is in the array.
2635
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2636
		 * @param array   $mod All the currently assembled module data.
2637
		 */
2638
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2639
2640
		/**
2641
		 * Filter the returned data about a module.
2642
		 *
2643
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2644
		 * so please be careful.
2645
		 *
2646
		 * @since 3.6.0
2647
		 *
2648
		 * @param array   $mod    The details of the requested module.
2649
		 * @param string  $module The slug of the module, e.g. sharedaddy
2650
		 * @param string  $file   The path to the module source file.
2651
		 */
2652
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2653
	}
2654
2655
	/**
2656
	 * Like core's get_file_data implementation, but caches the result.
2657
	 */
2658
	public static function get_file_data( $file, $headers ) {
2659
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2660
		$file_name = basename( $file );
2661
2662
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2663
2664
		$file_data_option = get_transient( $cache_key );
2665
2666
		if ( false === $file_data_option ) {
2667
			$file_data_option = array();
2668
		}
2669
2670
		$key           = md5( $file_name . serialize( $headers ) );
2671
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2672
2673
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2674
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2675
			return $file_data_option[ $key ];
2676
		}
2677
2678
		$data = get_file_data( $file, $headers );
2679
2680
		$file_data_option[ $key ] = $data;
2681
2682
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2683
2684
		return $data;
2685
	}
2686
2687
2688
	/**
2689
	 * Return translated module tag.
2690
	 *
2691
	 * @param string $tag Tag as it appears in each module heading.
2692
	 *
2693
	 * @return mixed
2694
	 */
2695
	public static function translate_module_tag( $tag ) {
2696
		return jetpack_get_module_i18n_tag( $tag );
2697
	}
2698
2699
	/**
2700
	 * Get i18n strings as a JSON-encoded string
2701
	 *
2702
	 * @return string The locale as JSON
2703
	 */
2704
	public static function get_i18n_data_json() {
2705
2706
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2707
		// JSON files with the file they should be included for. This is an md5
2708
		// of '_inc/build/admin.js'.
2709
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2710
2711
		$i18n_json =
2712
				   JETPACK__PLUGIN_DIR
2713
				   . 'languages/json/jetpack-'
2714
				   . get_user_locale()
2715
				   . '-'
2716
				   . $path_md5
2717
				   . '.json';
2718
2719
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2720
			$locale_data = @file_get_contents( $i18n_json );
2721
			if ( $locale_data ) {
2722
				return $locale_data;
2723
			}
2724
		}
2725
2726
		// Return valid empty Jed locale
2727
		return '{ "locale_data": { "messages": { "": {} } } }';
2728
	}
2729
2730
	/**
2731
	 * Add locale data setup to wp-i18n
2732
	 *
2733
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2734
	 *
2735
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2736
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2737
	 *
2738
	 * This method provides a safe way to request the setup multiple times but add the script at
2739
	 * most once.
2740
	 *
2741
	 * @since 6.7.0
2742
	 *
2743
	 * @return void
2744
	 */
2745
	public static function setup_wp_i18n_locale_data() {
2746
		static $script_added = false;
2747
		if ( ! $script_added ) {
2748
			$script_added = true;
2749
			wp_add_inline_script(
2750
				'wp-i18n',
2751
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2752
			);
2753
		}
2754
	}
2755
2756
	/**
2757
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2758
	 *
2759
	 * @since 3.9.2
2760
	 *
2761
	 * @param array $modules
2762
	 *
2763
	 * @return string|void
2764
	 */
2765
	public static function get_translated_modules( $modules ) {
2766
		foreach ( $modules as $index => $module ) {
2767
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2768
			if ( isset( $module['name'] ) ) {
2769
				$modules[ $index ]['name'] = $i18n_module['name'];
2770
			}
2771
			if ( isset( $module['description'] ) ) {
2772
				$modules[ $index ]['description'] = $i18n_module['description'];
2773
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2774
			}
2775
		}
2776
		return $modules;
2777
	}
2778
2779
	/**
2780
	 * Get a list of activated modules as an array of module slugs.
2781
	 */
2782
	public static function get_active_modules() {
2783
		$active = Jetpack_Options::get_option( 'active_modules' );
2784
2785
		if ( ! is_array( $active ) ) {
2786
			$active = array();
2787
		}
2788
2789
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2790
			$active[] = 'vaultpress';
2791
		} else {
2792
			$active = array_diff( $active, array( 'vaultpress' ) );
2793
		}
2794
2795
		//If protect is active on the main site of a multisite, it should be active on all sites.
2796
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2797
			$active[] = 'protect';
2798
		}
2799
2800
		/**
2801
		 * Allow filtering of the active modules.
2802
		 *
2803
		 * Gives theme and plugin developers the power to alter the modules that
2804
		 * are activated on the fly.
2805
		 *
2806
		 * @since 5.8.0
2807
		 *
2808
		 * @param array $active Array of active module slugs.
2809
		 */
2810
		$active = apply_filters( 'jetpack_active_modules', $active );
2811
2812
		return array_unique( $active );
2813
	}
2814
2815
	/**
2816
	 * Check whether or not a Jetpack module is active.
2817
	 *
2818
	 * @param string $module The slug of a Jetpack module.
2819
	 * @return bool
2820
	 *
2821
	 * @static
2822
	 */
2823
	public static function is_module_active( $module ) {
2824
		return in_array( $module, self::get_active_modules() );
2825
	}
2826
2827
	public static function is_module( $module ) {
2828
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2829
	}
2830
2831
	/**
2832
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2833
	 *
2834
	 * @param bool $catch True to start catching, False to stop.
2835
	 *
2836
	 * @static
2837
	 */
2838
	public static function catch_errors( $catch ) {
2839
		static $display_errors, $error_reporting;
2840
2841
		if ( $catch ) {
2842
			$display_errors  = @ini_set( 'display_errors', 1 );
2843
			$error_reporting = @error_reporting( E_ALL );
2844
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2845
		} else {
2846
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2847
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2848
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2849
		}
2850
	}
2851
2852
	/**
2853
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2854
	 */
2855
	public static function catch_errors_on_shutdown() {
2856
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2857
	}
2858
2859
	/**
2860
	 * Rewrite any string to make paths easier to read.
2861
	 *
2862
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2863
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2864
	 *
2865
	 * @param $string
2866
	 * @return mixed
2867
	 */
2868
	public static function alias_directories( $string ) {
2869
		// ABSPATH has a trailing slash.
2870
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2871
		// WP_CONTENT_DIR does not have a trailing slash.
2872
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2873
2874
		return $string;
2875
	}
2876
2877
	public static function activate_default_modules(
2878
		$min_version = false,
2879
		$max_version = false,
2880
		$other_modules = array(),
2881
		$redirect = true,
2882
		$send_state_messages = true
2883
	) {
2884
		$jetpack = Jetpack::init();
2885
2886
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2887
		$modules = array_merge( $other_modules, $modules );
2888
2889
		// Look for standalone plugins and disable if active.
2890
2891
		$to_deactivate = array();
2892
		foreach ( $modules as $module ) {
2893
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2894
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2895
			}
2896
		}
2897
2898
		$deactivated = array();
2899
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2900
			list( $probable_file, $probable_title ) = $deactivate_me;
2901
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2902
				$deactivated[] = $module;
2903
			}
2904
		}
2905
2906
		if ( $deactivated && $redirect ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2907
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2908
2909
			$url = add_query_arg(
2910
				array(
2911
					'action'   => 'activate_default_modules',
2912
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2913
				),
2914
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2915
			);
2916
			wp_safe_redirect( $url );
2917
			exit;
2918
		}
2919
2920
		/**
2921
		 * Fires before default modules are activated.
2922
		 *
2923
		 * @since 1.9.0
2924
		 *
2925
		 * @param string $min_version Minimum version number required to use modules.
2926
		 * @param string $max_version Maximum version number required to use modules.
2927
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2928
		 */
2929
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2930
2931
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2932
		if ( $send_state_messages ) {
2933
			Jetpack::restate();
2934
			Jetpack::catch_errors( true );
2935
		}
2936
2937
		$active = Jetpack::get_active_modules();
2938
2939
		foreach ( $modules as $module ) {
2940
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2941
				$active[] = $module;
2942
				self::update_active_modules( $active );
2943
				continue;
2944
			}
2945
2946
			if ( $send_state_messages && in_array( $module, $active ) ) {
2947
				$module_info = Jetpack::get_module( $module );
2948 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2949
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2950
					if ( $active_state = Jetpack::state( $state ) ) {
2951
						$active_state = explode( ',', $active_state );
2952
					} else {
2953
						$active_state = array();
2954
					}
2955
					$active_state[] = $module;
2956
					Jetpack::state( $state, implode( ',', $active_state ) );
2957
				}
2958
				continue;
2959
			}
2960
2961
			$file = Jetpack::get_module_path( $module );
2962
			if ( ! file_exists( $file ) ) {
2963
				continue;
2964
			}
2965
2966
			// we'll override this later if the plugin can be included without fatal error
2967
			if ( $redirect ) {
2968
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2969
			}
2970
2971
			if ( $send_state_messages ) {
2972
				Jetpack::state( 'error', 'module_activation_failed' );
2973
				Jetpack::state( 'module', $module );
2974
			}
2975
2976
			ob_start();
2977
			require_once $file;
2978
2979
			$active[] = $module;
2980
2981 View Code Duplication
			if ( $send_state_messages ) {
2982
2983
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2984
				if ( $active_state = Jetpack::state( $state ) ) {
2985
					$active_state = explode( ',', $active_state );
2986
				} else {
2987
					$active_state = array();
2988
				}
2989
				$active_state[] = $module;
2990
				Jetpack::state( $state, implode( ',', $active_state ) );
2991
			}
2992
2993
			Jetpack::update_active_modules( $active );
2994
2995
			ob_end_clean();
2996
		}
2997
2998
		if ( $send_state_messages ) {
2999
			Jetpack::state( 'error', false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3001
		}
3002
3003
		Jetpack::catch_errors( false );
3004
		/**
3005
		 * Fires when default modules are activated.
3006
		 *
3007
		 * @since 1.9.0
3008
		 *
3009
		 * @param string $min_version Minimum version number required to use modules.
3010
		 * @param string $max_version Maximum version number required to use modules.
3011
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3012
		 */
3013
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3014
	}
3015
3016
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3017
		/**
3018
		 * Fires before a module is activated.
3019
		 *
3020
		 * @since 2.6.0
3021
		 *
3022
		 * @param string $module Module slug.
3023
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3024
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3025
		 */
3026
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3027
3028
		$jetpack = Jetpack::init();
3029
3030
		if ( ! strlen( $module ) )
3031
			return false;
3032
3033
		if ( ! Jetpack::is_module( $module ) )
3034
			return false;
3035
3036
		// If it's already active, then don't do it again
3037
		$active = Jetpack::get_active_modules();
3038
		foreach ( $active as $act ) {
3039
			if ( $act == $module )
3040
				return true;
3041
		}
3042
3043
		$module_data = Jetpack::get_module( $module );
3044
3045
		if ( ! Jetpack::is_active() ) {
3046
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
3047
				return false;
3048
3049
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3050
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
3051
				return false;
3052
		}
3053
3054
		// Check and see if the old plugin is active
3055
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3056
			// Deactivate the old plugin
3057
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3058
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3059
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3060
				Jetpack::state( 'deactivated_plugins', $module );
3061
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3062
				exit;
3063
			}
3064
		}
3065
3066
		// Protect won't work with mis-configured IPs
3067
		if ( 'protect' === $module ) {
3068
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3069
			if ( ! jetpack_protect_get_ip() ) {
3070
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3071
				return false;
3072
			}
3073
		}
3074
3075
		if ( ! Jetpack_Plan::supports( $module ) ) {
3076
			return false;
3077
		}
3078
3079
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3080
		Jetpack::state( 'module', $module );
3081
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3082
3083
		Jetpack::catch_errors( true );
3084
		ob_start();
3085
		require Jetpack::get_module_path( $module );
3086
		/** This action is documented in class.jetpack.php */
3087
		do_action( 'jetpack_activate_module', $module );
3088
		$active[] = $module;
3089
		Jetpack::update_active_modules( $active );
3090
3091
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3092
		ob_end_clean();
3093
		Jetpack::catch_errors( false );
3094
3095
		if ( $redirect ) {
3096
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3097
		}
3098
		if ( $exit ) {
3099
			exit;
3100
		}
3101
		return true;
3102
	}
3103
3104
	function activate_module_actions( $module ) {
3105
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3106
	}
3107
3108
	public static function deactivate_module( $module ) {
3109
		/**
3110
		 * Fires when a module is deactivated.
3111
		 *
3112
		 * @since 1.9.0
3113
		 *
3114
		 * @param string $module Module slug.
3115
		 */
3116
		do_action( 'jetpack_pre_deactivate_module', $module );
3117
3118
		$jetpack = Jetpack::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3119
3120
		$active = Jetpack::get_active_modules();
3121
		$new    = array_filter( array_diff( $active, (array) $module ) );
3122
3123
		return self::update_active_modules( $new );
3124
	}
3125
3126
	public static function enable_module_configurable( $module ) {
3127
		$module = Jetpack::get_module_slug( $module );
3128
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3129
	}
3130
3131
	/**
3132
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3133
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3134
	 *
3135
	 * @param string $module Module slug
3136
	 * @return string $url module configuration URL
3137
	 */
3138
	public static function module_configuration_url( $module ) {
3139
		$module = Jetpack::get_module_slug( $module );
3140
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3141
		/**
3142
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3143
		 *
3144
		 * @since 6.9.0
3145
		 *
3146
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3147
		 */
3148
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3149
3150
		return $url;
3151
	}
3152
3153
/* Installation */
3154
	public static function bail_on_activation( $message, $deactivate = true ) {
3155
?>
3156
<!doctype html>
3157
<html>
3158
<head>
3159
<meta charset="<?php bloginfo( 'charset' ); ?>">
3160
<style>
3161
* {
3162
	text-align: center;
3163
	margin: 0;
3164
	padding: 0;
3165
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3166
}
3167
p {
3168
	margin-top: 1em;
3169
	font-size: 18px;
3170
}
3171
</style>
3172
<body>
3173
<p><?php echo esc_html( $message ); ?></p>
3174
</body>
3175
</html>
3176
<?php
3177
		if ( $deactivate ) {
3178
			$plugins = get_option( 'active_plugins' );
3179
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3180
			$update  = false;
3181
			foreach ( $plugins as $i => $plugin ) {
3182
				if ( $plugin === $jetpack ) {
3183
					$plugins[$i] = false;
3184
					$update = true;
3185
				}
3186
			}
3187
3188
			if ( $update ) {
3189
				update_option( 'active_plugins', array_filter( $plugins ) );
3190
			}
3191
		}
3192
		exit;
3193
	}
3194
3195
	/**
3196
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3197
	 * @static
3198
	 */
3199
	public static function plugin_activation( $network_wide ) {
3200
		Jetpack_Options::update_option( 'activated', 1 );
3201
3202
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3203
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3204
		}
3205
3206
		if ( $network_wide )
3207
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3208
3209
		// For firing one-off events (notices) immediately after activation
3210
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3211
3212
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3213
3214
		Jetpack::plugin_initialize();
3215
	}
3216
3217
	public static function get_activation_source( $referer_url ) {
3218
3219
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3220
			return array( 'wp-cli', null );
3221
		}
3222
3223
		$referer = parse_url( $referer_url );
3224
3225
		$source_type = 'unknown';
3226
		$source_query = null;
3227
3228
		if ( ! is_array( $referer ) ) {
3229
			return array( $source_type, $source_query );
3230
		}
3231
3232
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3233
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3234
3235
		if ( isset( $referer['query'] ) ) {
3236
			parse_str( $referer['query'], $query_parts );
3237
		} else {
3238
			$query_parts = array();
3239
		}
3240
3241
		if ( $plugins_path === $referer['path'] ) {
3242
			$source_type = 'list';
3243
		} elseif ( $plugins_install_path === $referer['path'] ) {
3244
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3245
			switch( $tab ) {
3246
				case 'popular':
3247
					$source_type = 'popular';
3248
					break;
3249
				case 'recommended':
3250
					$source_type = 'recommended';
3251
					break;
3252
				case 'favorites':
3253
					$source_type = 'favorites';
3254
					break;
3255
				case 'search':
3256
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3257
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3258
					break;
3259
				default:
3260
					$source_type = 'featured';
3261
			}
3262
		}
3263
3264
		return array( $source_type, $source_query );
3265
	}
3266
3267
	/**
3268
	 * Runs before bumping version numbers up to a new version
3269
	 * @param  string $version    Version:timestamp
3270
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3271
	 * @return null              [description]
3272
	 */
3273
	public static function do_version_bump( $version, $old_version ) {
3274
		if ( ! $old_version ) { // For new sites
3275
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3276
		}
3277
	}
3278
3279
	/**
3280
	 * Sets the internal version number and activation state.
3281
	 * @static
3282
	 */
3283
	public static function plugin_initialize() {
3284
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3285
			Jetpack_Options::update_option( 'activated', 2 );
3286
		}
3287
3288 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3289
			$version = $old_version = JETPACK__VERSION . ':' . time();
3290
			/** This action is documented in class.jetpack.php */
3291
			do_action( 'updating_jetpack_version', $version, false );
3292
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3293
		}
3294
3295
		Jetpack::load_modules();
3296
3297
		Jetpack_Options::delete_option( 'do_activate' );
3298
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3299
	}
3300
3301
	/**
3302
	 * Removes all connection options
3303
	 * @static
3304
	 */
3305
	public static function plugin_deactivation( ) {
3306
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3307
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3308
			Jetpack_Network::init()->deactivate();
3309
		} else {
3310
			Jetpack::disconnect( false );
3311
			//Jetpack_Heartbeat::init()->deactivate();
3312
		}
3313
	}
3314
3315
	/**
3316
	 * Disconnects from the Jetpack servers.
3317
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3318
	 * @static
3319
	 */
3320
	public static function disconnect( $update_activated_state = true ) {
3321
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3322
		Jetpack::clean_nonces( true );
3323
3324
		// If the site is in an IDC because sync is not allowed,
3325
		// let's make sure to not disconnect the production site.
3326
		if ( ! self::validate_sync_error_idc_option() ) {
3327
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3328
			Jetpack::load_xml_rpc_client();
3329
			$xml = new Jetpack_IXR_Client();
3330
			$xml->query( 'jetpack.deregister' );
3331
		}
3332
3333
		Jetpack_Options::delete_option(
3334
			array(
3335
				'blog_token',
3336
				'user_token',
3337
				'user_tokens',
3338
				'master_user',
3339
				'time_diff',
3340
				'fallback_no_verify_ssl_certs',
3341
			)
3342
		);
3343
3344
		Jetpack_IDC::clear_all_idc_options();
3345
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3346
3347
		if ( $update_activated_state ) {
3348
			Jetpack_Options::update_option( 'activated', 4 );
3349
		}
3350
3351
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3352
			// Check then record unique disconnection if site has never been disconnected previously
3353
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3354
				$jetpack_unique_connection['disconnected'] = 1;
3355
			} else {
3356
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3357
					//track unique disconnect
3358
					$jetpack = Jetpack::init();
3359
3360
					$jetpack->stat( 'connections', 'unique-disconnect' );
3361
					$jetpack->do_stats( 'server_side' );
3362
				}
3363
				// increment number of times disconnected
3364
				$jetpack_unique_connection['disconnected'] += 1;
3365
			}
3366
3367
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3368
		}
3369
3370
		// Delete cached connected user data
3371
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3372
		delete_transient( $transient_key );
3373
3374
		// Delete all the sync related data. Since it could be taking up space.
3375
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3376
		Jetpack_Sync_Sender::get_instance()->uninstall();
3377
3378
		// Disable the Heartbeat cron
3379
		Jetpack_Heartbeat::init()->deactivate();
3380
	}
3381
3382
	/**
3383
	 * Unlinks the current user from the linked WordPress.com user
3384
	 */
3385
	public static function unlink_user( $user_id = null ) {
3386
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3387
			return false;
3388
3389
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3390
3391
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3392
			return false;
3393
3394
		if ( ! isset( $tokens[ $user_id ] ) )
3395
			return false;
3396
3397
		Jetpack::load_xml_rpc_client();
3398
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3399
		$xml->query( 'jetpack.unlink_user', $user_id );
3400
3401
		unset( $tokens[ $user_id ] );
3402
3403
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3404
3405
		/**
3406
		 * Fires after the current user has been unlinked from WordPress.com.
3407
		 *
3408
		 * @since 4.1.0
3409
		 *
3410
		 * @param int $user_id The current user's ID.
3411
		 */
3412
		do_action( 'jetpack_unlinked_user', $user_id );
3413
3414
		return true;
3415
	}
3416
3417
	/**
3418
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3419
	 */
3420
	public static function try_registration() {
3421
		// The user has agreed to the TOS at some point by now.
3422
		Jetpack_Options::update_option( 'tos_agreed', true );
3423
3424
		// Let's get some testing in beta versions and such.
3425
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3426
			// Before attempting to connect, let's make sure that the domains are viable.
3427
			$domains_to_check = array_unique( array(
3428
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3429
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3430
			) );
3431
			foreach ( $domains_to_check as $domain ) {
3432
				$result = Jetpack_Data::is_usable_domain( $domain );
3433
				if ( is_wp_error( $result ) ) {
3434
					return $result;
3435
				}
3436
			}
3437
		}
3438
3439
		$result = Jetpack::register();
3440
3441
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3442
		if ( ! $result || is_wp_error( $result ) ) {
3443
			return $result;
3444
		} else {
3445
			return true;
3446
		}
3447
	}
3448
3449
	/**
3450
	 * Tracking an internal event log. Try not to put too much chaff in here.
3451
	 *
3452
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3453
	 */
3454
	public static function log( $code, $data = null ) {
3455
		// only grab the latest 200 entries
3456
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3457
3458
		// Append our event to the log
3459
		$log_entry = array(
3460
			'time'    => time(),
3461
			'user_id' => get_current_user_id(),
3462
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3463
			'code'    => $code,
3464
		);
3465
		// Don't bother storing it unless we've got some.
3466
		if ( ! is_null( $data ) ) {
3467
			$log_entry['data'] = $data;
3468
		}
3469
		$log[] = $log_entry;
3470
3471
		// Try add_option first, to make sure it's not autoloaded.
3472
		// @todo: Add an add_option method to Jetpack_Options
3473
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3474
			Jetpack_Options::update_option( 'log', $log );
3475
		}
3476
3477
		/**
3478
		 * Fires when Jetpack logs an internal event.
3479
		 *
3480
		 * @since 3.0.0
3481
		 *
3482
		 * @param array $log_entry {
3483
		 *	Array of details about the log entry.
3484
		 *
3485
		 *	@param string time Time of the event.
3486
		 *	@param int user_id ID of the user who trigerred the event.
3487
		 *	@param int blog_id Jetpack Blog ID.
3488
		 *	@param string code Unique name for the event.
3489
		 *	@param string data Data about the event.
3490
		 * }
3491
		 */
3492
		do_action( 'jetpack_log_entry', $log_entry );
3493
	}
3494
3495
	/**
3496
	 * Get the internal event log.
3497
	 *
3498
	 * @param $event (string) - only return the specific log events
3499
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3500
	 *
3501
	 * @return array of log events || WP_Error for invalid params
3502
	 */
3503
	public static function get_log( $event = false, $num = false ) {
3504
		if ( $event && ! is_string( $event ) ) {
3505
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3506
		}
3507
3508
		if ( $num && ! is_numeric( $num ) ) {
3509
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3510
		}
3511
3512
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3513
3514
		// If nothing set - act as it did before, otherwise let's start customizing the output
3515
		if ( ! $num && ! $event ) {
3516
			return $entire_log;
3517
		} else {
3518
			$entire_log = array_reverse( $entire_log );
3519
		}
3520
3521
		$custom_log_output = array();
3522
3523
		if ( $event ) {
3524
			foreach ( $entire_log as $log_event ) {
3525
				if ( $event == $log_event[ 'code' ] ) {
3526
					$custom_log_output[] = $log_event;
3527
				}
3528
			}
3529
		} else {
3530
			$custom_log_output = $entire_log;
3531
		}
3532
3533
		if ( $num ) {
3534
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3535
		}
3536
3537
		return $custom_log_output;
3538
	}
3539
3540
	/**
3541
	 * Log modification of important settings.
3542
	 */
3543
	public static function log_settings_change( $option, $old_value, $value ) {
3544
		switch( $option ) {
3545
			case 'jetpack_sync_non_public_post_stati':
3546
				self::log( $option, $value );
3547
				break;
3548
		}
3549
	}
3550
3551
	/**
3552
	 * Return stat data for WPCOM sync
3553
	 */
3554
	public static function get_stat_data( $encode = true, $extended = true ) {
3555
		$data = Jetpack_Heartbeat::generate_stats_array();
3556
3557
		if ( $extended ) {
3558
			$additional_data = self::get_additional_stat_data();
3559
			$data = array_merge( $data, $additional_data );
3560
		}
3561
3562
		if ( $encode ) {
3563
			return json_encode( $data );
3564
		}
3565
3566
		return $data;
3567
	}
3568
3569
	/**
3570
	 * Get additional stat data to sync to WPCOM
3571
	 */
3572
	public static function get_additional_stat_data( $prefix = '' ) {
3573
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3574
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3575
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3576
		$return["{$prefix}site-count"]     = 0;
3577
3578
		if ( function_exists( 'get_blog_count' ) ) {
3579
			$return["{$prefix}site-count"] = get_blog_count();
3580
		}
3581
		return $return;
3582
	}
3583
3584
	private static function get_site_user_count() {
3585
		global $wpdb;
3586
3587
		if ( function_exists( 'wp_is_large_network' ) ) {
3588
			if ( wp_is_large_network( 'users' ) ) {
3589
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3590
			}
3591
		}
3592 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3593
			// It wasn't there, so regenerate the data and save the transient
3594
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3595
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3596
		}
3597
		return $user_count;
3598
	}
3599
3600
	/* Admin Pages */
3601
3602
	function admin_init() {
3603
		// If the plugin is not connected, display a connect message.
3604
		if (
3605
			// the plugin was auto-activated and needs its candy
3606
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3607
		||
3608
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3609
			! Jetpack_Options::get_option( 'activated' )
3610
		) {
3611
			Jetpack::plugin_initialize();
3612
		}
3613
3614
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3615
			Jetpack_Connection_Banner::init();
3616
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3617
			// Upgrade: 1.1 -> 1.1.1
3618
			// Check and see if host can verify the Jetpack servers' SSL certificate
3619
			$args = array();
3620
			Jetpack_Client::_wp_remote_request(
3621
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3622
				$args,
3623
				true
3624
			);
3625
		}
3626
3627
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3628
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3629
		}
3630
3631
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3632
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3633
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3634
3635
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3636
			// Artificially throw errors in certain whitelisted cases during plugin activation
3637
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3638
		}
3639
3640
		// Add custom column in wp-admin/users.php to show whether user is linked.
3641
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3642
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3643
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3644
	}
3645
3646
	function admin_body_class( $admin_body_class = '' ) {
3647
		$classes = explode( ' ', trim( $admin_body_class ) );
3648
3649
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3650
3651
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3652
		return " $admin_body_class ";
3653
	}
3654
3655
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3656
		return $admin_body_class . ' jetpack-pagestyles ';
3657
	}
3658
3659
	/**
3660
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3661
	 * This function artificially throws errors for such cases (whitelisted).
3662
	 *
3663
	 * @param string $plugin The activated plugin.
3664
	 */
3665
	function throw_error_on_activate_plugin( $plugin ) {
3666
		$active_modules = Jetpack::get_active_modules();
3667
3668
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3669
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3670
			$throw = false;
3671
3672
			// Try and make sure it really was the stats plugin
3673
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3674
				if ( 'stats.php' == basename( $plugin ) ) {
3675
					$throw = true;
3676
				}
3677
			} else {
3678
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3679
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3680
					$throw = true;
3681
				}
3682
			}
3683
3684
			if ( $throw ) {
3685
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3686
			}
3687
		}
3688
	}
3689
3690
	function intercept_plugin_error_scrape_init() {
3691
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3692
	}
3693
3694
	function intercept_plugin_error_scrape( $action, $result ) {
3695
		if ( ! $result ) {
3696
			return;
3697
		}
3698
3699
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3700
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3701
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3702
			}
3703
		}
3704
	}
3705
3706
	function add_remote_request_handlers() {
3707
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3708
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3709
	}
3710
3711
	function remote_request_handlers() {
3712
		$action = current_filter();
0 ignored issues
show
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3713
3714
		switch ( current_filter() ) {
3715
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3716
			$response = $this->upload_handler();
3717
			break;
3718
3719
		case 'wp_ajax_nopriv_jetpack_update_file' :
3720
			$response = $this->upload_handler( true );
3721
			break;
3722
		default :
3723
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3724
			break;
3725
		}
3726
3727
		if ( ! $response ) {
3728
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3729
		}
3730
3731
		if ( is_wp_error( $response ) ) {
3732
			$status_code       = $response->get_error_data();
3733
			$error             = $response->get_error_code();
3734
			$error_description = $response->get_error_message();
3735
3736
			if ( ! is_int( $status_code ) ) {
3737
				$status_code = 400;
3738
			}
3739
3740
			status_header( $status_code );
3741
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3742
		}
3743
3744
		status_header( 200 );
3745
		if ( true === $response ) {
3746
			exit;
3747
		}
3748
3749
		die( json_encode( (object) $response ) );
3750
	}
3751
3752
	/**
3753
	 * Uploads a file gotten from the global $_FILES.
3754
	 * If `$update_media_item` is true and `post_id` is defined
3755
	 * the attachment file of the media item (gotten through of the post_id)
3756
	 * will be updated instead of add a new one.
3757
	 *
3758
	 * @param  boolean $update_media_item - update media attachment
3759
	 * @return array - An array describing the uploadind files process
3760
	 */
3761
	function upload_handler( $update_media_item = false ) {
3762
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3763
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3764
		}
3765
3766
		$user = wp_authenticate( '', '' );
3767
		if ( ! $user || is_wp_error( $user ) ) {
3768
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3769
		}
3770
3771
		wp_set_current_user( $user->ID );
3772
3773
		if ( ! current_user_can( 'upload_files' ) ) {
3774
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3775
		}
3776
3777
		if ( empty( $_FILES ) ) {
3778
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3779
		}
3780
3781
		foreach ( array_keys( $_FILES ) as $files_key ) {
3782
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3783
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3784
			}
3785
		}
3786
3787
		$media_keys = array_keys( $_FILES['media'] );
3788
3789
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3790
		if ( ! $token || is_wp_error( $token ) ) {
3791
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3792
		}
3793
3794
		$uploaded_files = array();
3795
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3796
		unset( $GLOBALS['post'] );
3797
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3798
			$file = array();
3799
			foreach ( $media_keys as $media_key ) {
3800
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3801
			}
3802
3803
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3804
3805
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3806
			if ( $hmac_provided !== $hmac_file ) {
3807
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3808
				continue;
3809
			}
3810
3811
			$_FILES['.jetpack.upload.'] = $file;
3812
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3813
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3814
				$post_id = 0;
3815
			}
3816
3817
			if ( $update_media_item ) {
3818
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3819
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3820
				}
3821
3822
				$media_array = $_FILES['media'];
3823
3824
				$file_array['name'] = $media_array['name'][0];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$file_array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $file_array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3825
				$file_array['type'] = $media_array['type'][0];
3826
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3827
				$file_array['error'] = $media_array['error'][0];
3828
				$file_array['size'] = $media_array['size'][0];
3829
3830
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3831
3832
				if ( is_wp_error( $edited_media_item ) ) {
3833
					return $edited_media_item;
3834
				}
3835
3836
				$response = (object) array(
3837
					'id'   => (string) $post_id,
3838
					'file' => (string) $edited_media_item->post_title,
3839
					'url'  => (string) wp_get_attachment_url( $post_id ),
3840
					'type' => (string) $edited_media_item->post_mime_type,
3841
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3842
				);
3843
3844
				return (array) array( $response );
3845
			}
3846
3847
			$attachment_id = media_handle_upload(
3848
				'.jetpack.upload.',
3849
				$post_id,
3850
				array(),
3851
				array(
3852
					'action' => 'jetpack_upload_file',
3853
				)
3854
			);
3855
3856
			if ( ! $attachment_id ) {
3857
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3858
			} elseif ( is_wp_error( $attachment_id ) ) {
3859
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3860
			} else {
3861
				$attachment = get_post( $attachment_id );
3862
				$uploaded_files[$index] = (object) array(
3863
					'id'   => (string) $attachment_id,
3864
					'file' => $attachment->post_title,
3865
					'url'  => wp_get_attachment_url( $attachment_id ),
3866
					'type' => $attachment->post_mime_type,
3867
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3868
				);
3869
				// Zip files uploads are not supported unless they are done for installation purposed
3870
				// lets delete them in case something goes wrong in this whole process
3871
				if ( 'application/zip' === $attachment->post_mime_type ) {
3872
					// Schedule a cleanup for 2 hours from now in case of failed install.
3873
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3874
				}
3875
			}
3876
		}
3877
		if ( ! is_null( $global_post ) ) {
3878
			$GLOBALS['post'] = $global_post;
3879
		}
3880
3881
		return $uploaded_files;
3882
	}
3883
3884
	/**
3885
	 * Add help to the Jetpack page
3886
	 *
3887
	 * @since Jetpack (1.2.3)
3888
	 * @return false if not the Jetpack page
3889
	 */
3890
	function admin_help() {
3891
		$current_screen = get_current_screen();
3892
3893
		// Overview
3894
		$current_screen->add_help_tab(
3895
			array(
3896
				'id'		=> 'home',
3897
				'title'		=> __( 'Home', 'jetpack' ),
3898
				'content'	=>
3899
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3900
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3901
					'<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>',
3902
			)
3903
		);
3904
3905
		// Screen Content
3906
		if ( current_user_can( 'manage_options' ) ) {
3907
			$current_screen->add_help_tab(
3908
				array(
3909
					'id'		=> 'settings',
3910
					'title'		=> __( 'Settings', 'jetpack' ),
3911
					'content'	=>
3912
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3913
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3914
						'<ol>' .
3915
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3916
							'<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>' .
3917
						'</ol>' .
3918
						'<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>'
3919
				)
3920
			);
3921
		}
3922
3923
		// Help Sidebar
3924
		$current_screen->set_help_sidebar(
3925
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3926
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3927
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3928
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3929
		);
3930
	}
3931
3932
	function admin_menu_css() {
3933
		wp_enqueue_style( 'jetpack-icons' );
3934
	}
3935
3936
	function admin_menu_order() {
3937
		return true;
3938
	}
3939
3940 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3941
		$jp_menu_order = array();
3942
3943
		foreach ( $menu_order as $index => $item ) {
3944
			if ( $item != 'jetpack' ) {
3945
				$jp_menu_order[] = $item;
3946
			}
3947
3948
			if ( $index == 0 ) {
3949
				$jp_menu_order[] = 'jetpack';
3950
			}
3951
		}
3952
3953
		return $jp_menu_order;
3954
	}
3955
3956
	function admin_banner_styles() {
3957
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3958
3959 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3960
			wp_register_style(
3961
				'jetpack-dops-style',
3962
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3963
				array(),
3964
				JETPACK__VERSION
3965
			);
3966
		}
3967
3968
		wp_enqueue_style(
3969
			'jetpack',
3970
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3971
			array( 'jetpack-dops-style' ),
3972
			 JETPACK__VERSION . '-20121016'
3973
		);
3974
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3975
		wp_style_add_data( 'jetpack', 'suffix', $min );
3976
	}
3977
3978
	function plugin_action_links( $actions ) {
3979
3980
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3981
3982
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3983
			return array_merge(
3984
				$jetpack_home,
3985
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3986
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3987
				$actions
3988
				);
3989
			}
3990
3991
		return array_merge( $jetpack_home, $actions );
3992
	}
3993
3994
	/*
3995
	 * Registration flow:
3996
	 * 1 - ::admin_page_load() action=register
3997
	 * 2 - ::try_registration()
3998
	 * 3 - ::register()
3999
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4000
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4001
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4002
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4003
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4004
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4005
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4006
	 *       jetpack_id, jetpack_secret, jetpack_public
4007
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4008
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4009
	 * 5 - user logs in with WP.com account
4010
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4011
	 *		- Jetpack_Client_Server::authorize()
4012
	 *		- Jetpack_Client_Server::get_token()
4013
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4014
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4015
	 *			- which responds with access_token, token_type, scope
4016
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
4017
	 *		- Jetpack::activate_default_modules()
4018
	 *     		- Deactivates deprecated plugins
4019
	 *     		- Activates all default modules
4020
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4021
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4022
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4023
	 *     Done!
4024
	 */
4025
4026
	/**
4027
	 * Handles the page load events for the Jetpack admin page
4028
	 */
4029
	function admin_page_load() {
4030
		$error = false;
4031
4032
		// Make sure we have the right body class to hook stylings for subpages off of.
4033
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
4034
4035
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4036
			// Should only be used in intermediate redirects to preserve state across redirects
4037
			Jetpack::restate();
4038
		}
4039
4040
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4041
			// @todo: Add validation against a known whitelist
4042
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4043
			// User clicked in the iframe to link their accounts
4044
			if ( ! Jetpack::is_user_connected() ) {
4045
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4046
4047
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4048
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4049
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4050
4051
				if ( isset( $_GET['notes_iframe'] ) )
4052
					$connect_url .= '&notes_iframe';
4053
				wp_redirect( $connect_url );
4054
				exit;
4055
			} else {
4056
				if ( ! isset( $_GET['calypso_env'] ) ) {
4057
					Jetpack::state( 'message', 'already_authorized' );
4058
					wp_safe_redirect( Jetpack::admin_url() );
4059
					exit;
4060
				} else {
4061
					$connect_url = $this->build_connect_url( true, false, $from );
4062
					$connect_url .= '&already_authorized=true';
4063
					wp_redirect( $connect_url );
4064
					exit;
4065
				}
4066
			}
4067
		}
4068
4069
4070
		if ( isset( $_GET['action'] ) ) {
4071
			switch ( $_GET['action'] ) {
4072
			case 'authorize':
4073
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4074
					Jetpack::state( 'message', 'already_authorized' );
4075
					wp_safe_redirect( Jetpack::admin_url() );
4076
					exit;
4077
				}
4078
				Jetpack::log( 'authorize' );
4079
				$client_server = new Jetpack_Client_Server;
4080
				$client_server->client_authorize();
4081
				exit;
4082
			case 'register' :
4083
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4084
					$error = 'cheatin';
4085
					break;
4086
				}
4087
				check_admin_referer( 'jetpack-register' );
4088
				Jetpack::log( 'register' );
4089
				Jetpack::maybe_set_version_option();
4090
				$registered = Jetpack::try_registration();
4091
				if ( is_wp_error( $registered ) ) {
4092
					$error = $registered->get_error_code();
4093
					Jetpack::state( 'error', $error );
4094
					Jetpack::state( 'error', $registered->get_error_message() );
4095
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4096
						'error_code' => $error,
4097
						'error_message' => $registered->get_error_message()
4098
					) );
4099
					break;
4100
				}
4101
4102
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4103
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4104
4105
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4106
					'from' => $from
4107
				) );
4108
4109
				$url = $this->build_connect_url( true, $redirect, $from );
4110
4111
				if ( ! empty( $_GET['onboarding'] ) ) {
4112
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4113
				}
4114
4115
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4116
					$url = add_query_arg( 'auth_approved', 'true', $url );
4117
				}
4118
4119
				wp_redirect( $url );
4120
				exit;
4121
			case 'activate' :
4122
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4123
					$error = 'cheatin';
4124
					break;
4125
				}
4126
4127
				$module = stripslashes( $_GET['module'] );
4128
				check_admin_referer( "jetpack_activate-$module" );
4129
				Jetpack::log( 'activate', $module );
4130
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::activate_module($module) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
4131
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4132
				}
4133
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4134
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4135
				exit;
4136
			case 'activate_default_modules' :
4137
				check_admin_referer( 'activate_default_modules' );
4138
				Jetpack::log( 'activate_default_modules' );
4139
				Jetpack::restate();
4140
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4141
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4142
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4143
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4144
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4145
				exit;
4146
			case 'disconnect' :
4147
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4148
					$error = 'cheatin';
4149
					break;
4150
				}
4151
4152
				check_admin_referer( 'jetpack-disconnect' );
4153
				Jetpack::log( 'disconnect' );
4154
				Jetpack::disconnect();
4155
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4156
				exit;
4157
			case 'reconnect' :
4158
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4159
					$error = 'cheatin';
4160
					break;
4161
				}
4162
4163
				check_admin_referer( 'jetpack-reconnect' );
4164
				Jetpack::log( 'reconnect' );
4165
				$this->disconnect();
4166
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4167
				exit;
4168 View Code Duplication
			case 'deactivate' :
4169
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4170
					$error = 'cheatin';
4171
					break;
4172
				}
4173
4174
				$modules = stripslashes( $_GET['module'] );
4175
				check_admin_referer( "jetpack_deactivate-$modules" );
4176
				foreach ( explode( ',', $modules ) as $module ) {
4177
					Jetpack::log( 'deactivate', $module );
4178
					Jetpack::deactivate_module( $module );
4179
					Jetpack::state( 'message', 'module_deactivated' );
4180
				}
4181
				Jetpack::state( 'module', $modules );
4182
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4183
				exit;
4184
			case 'unlink' :
4185
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4186
				check_admin_referer( 'jetpack-unlink' );
4187
				Jetpack::log( 'unlink' );
4188
				$this->unlink_user();
4189
				Jetpack::state( 'message', 'unlinked' );
4190
				if ( 'sub-unlink' == $redirect ) {
4191
					wp_safe_redirect( admin_url() );
4192
				} else {
4193
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4194
				}
4195
				exit;
4196
			case 'onboard' :
4197
				if ( ! current_user_can( 'manage_options' ) ) {
4198
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4199
				} else {
4200
					Jetpack::create_onboarding_token();
4201
					$url = $this->build_connect_url( true );
4202
4203
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4204
						$url = add_query_arg( 'onboarding', $token, $url );
4205
					}
4206
4207
					$calypso_env = $this->get_calypso_env();
4208
					if ( ! empty( $calypso_env ) ) {
4209
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4210
					}
4211
4212
					wp_redirect( $url );
4213
					exit;
4214
				}
4215
				exit;
4216
			default:
4217
				/**
4218
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4219
				 *
4220
				 * @since 2.6.0
4221
				 *
4222
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4223
				 */
4224
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4225
			}
4226
		}
4227
4228
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4229
			self::activate_new_modules( true );
4230
		}
4231
4232
		$message_code = Jetpack::state( 'message' );
4233
		if ( Jetpack::state( 'optin-manage' ) ) {
4234
			$activated_manage = $message_code;
4235
			$message_code = 'jetpack-manage';
4236
		}
4237
4238
		switch ( $message_code ) {
4239
		case 'jetpack-manage':
4240
			$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>';
4241
			if ( $activated_manage ) {
0 ignored issues
show
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4242
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4243
			}
4244
			break;
4245
4246
		}
4247
4248
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4249
4250
		if ( ! empty( $deactivated_plugins ) ) {
4251
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4252
			$deactivated_titles  = array();
4253
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4254
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4255
					continue;
4256
				}
4257
4258
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4259
			}
4260
4261
			if ( $deactivated_titles ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated_titles of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
4262
				if ( $this->message ) {
4263
					$this->message .= "<br /><br />\n";
4264
				}
4265
4266
				$this->message .= wp_sprintf(
4267
					_n(
4268
						'Jetpack contains the most recent version of the old %l plugin.',
4269
						'Jetpack contains the most recent versions of the old %l plugins.',
4270
						count( $deactivated_titles ),
4271
						'jetpack'
4272
					),
4273
					$deactivated_titles
4274
				);
4275
4276
				$this->message .= "<br />\n";
4277
4278
				$this->message .= _n(
4279
					'The old version has been deactivated and can be removed from your site.',
4280
					'The old versions have been deactivated and can be removed from your site.',
4281
					count( $deactivated_titles ),
4282
					'jetpack'
4283
				);
4284
			}
4285
		}
4286
4287
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4288
4289
		if ( $this->message || $this->error || $this->privacy_checks ) {
4290
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4291
		}
4292
4293
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4294
	}
4295
4296
	function admin_notices() {
4297
4298
		if ( $this->error ) {
4299
?>
4300
<div id="message" class="jetpack-message jetpack-err">
4301
	<div class="squeezer">
4302
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4303
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4304
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4305
<?php	endif; ?>
4306
	</div>
4307
</div>
4308
<?php
4309
		}
4310
4311
		if ( $this->message ) {
4312
?>
4313
<div id="message" class="jetpack-message">
4314
	<div class="squeezer">
4315
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4316
	</div>
4317
</div>
4318
<?php
4319
		}
4320
4321
		if ( $this->privacy_checks ) :
4322
			$module_names = $module_slugs = array();
4323
4324
			$privacy_checks = explode( ',', $this->privacy_checks );
4325
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4326
			foreach ( $privacy_checks as $module_slug ) {
4327
				$module = Jetpack::get_module( $module_slug );
4328
				if ( ! $module ) {
4329
					continue;
4330
				}
4331
4332
				$module_slugs[] = $module_slug;
4333
				$module_names[] = "<strong>{$module['name']}</strong>";
4334
			}
4335
4336
			$module_slugs = join( ',', $module_slugs );
4337
?>
4338
<div id="message" class="jetpack-message jetpack-err">
4339
	<div class="squeezer">
4340
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4341
		<p><?php
4342
			echo wp_kses(
4343
				wptexturize(
4344
					wp_sprintf(
4345
						_nx(
4346
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4347
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4348
							count( $privacy_checks ),
4349
							'%l = list of Jetpack module/feature names',
4350
							'jetpack'
4351
						),
4352
						$module_names
4353
					)
4354
				),
4355
				array( 'strong' => true )
4356
			);
4357
4358
			echo "\n<br />\n";
4359
4360
			echo wp_kses(
4361
				sprintf(
4362
					_nx(
4363
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4364
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4365
						count( $privacy_checks ),
4366
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4367
						'jetpack'
4368
					),
4369
					wp_nonce_url(
4370
						Jetpack::admin_url(
4371
							array(
4372
								'page'   => 'jetpack',
4373
								'action' => 'deactivate',
4374
								'module' => urlencode( $module_slugs ),
4375
							)
4376
						),
4377
						"jetpack_deactivate-$module_slugs"
4378
					),
4379
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4380
				),
4381
				array( 'a' => array( 'href' => true, 'title' => true ) )
4382
			);
4383
		?></p>
4384
	</div>
4385
</div>
4386
<?php endif;
4387
	}
4388
4389
	/**
4390
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4391
	 */
4392
	function stat( $group, $detail ) {
4393
		if ( ! isset( $this->stats[ $group ] ) )
4394
			$this->stats[ $group ] = array();
4395
		$this->stats[ $group ][] = $detail;
4396
	}
4397
4398
	/**
4399
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4400
	 */
4401
	function do_stats( $method = '' ) {
4402
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4403
			foreach ( $this->stats as $group => $stats ) {
4404
				if ( is_array( $stats ) && count( $stats ) ) {
4405
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4406
					if ( 'server_side' === $method ) {
4407
						self::do_server_side_stat( $args );
4408
					} else {
4409
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4410
					}
4411
				}
4412
				unset( $this->stats[ $group ] );
4413
			}
4414
		}
4415
	}
4416
4417
	/**
4418
	 * Runs stats code for a one-off, server-side.
4419
	 *
4420
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4421
	 *
4422
	 * @return bool If it worked.
4423
	 */
4424
	static function do_server_side_stat( $args ) {
4425
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4426
		if ( is_wp_error( $response ) )
4427
			return false;
4428
4429
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4430
			return false;
4431
4432
		return true;
4433
	}
4434
4435
	/**
4436
	 * Builds the stats url.
4437
	 *
4438
	 * @param $args array|string The arguments to append to the URL.
4439
	 *
4440
	 * @return string The URL to be pinged.
4441
	 */
4442
	static function build_stats_url( $args ) {
4443
		$defaults = array(
4444
			'v'    => 'wpcom2',
4445
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4446
		);
4447
		$args     = wp_parse_args( $args, $defaults );
4448
		/**
4449
		 * Filter the URL used as the Stats tracking pixel.
4450
		 *
4451
		 * @since 2.3.2
4452
		 *
4453
		 * @param string $url Base URL used as the Stats tracking pixel.
4454
		 */
4455
		$base_url = apply_filters(
4456
			'jetpack_stats_base_url',
4457
			'https://pixel.wp.com/g.gif'
4458
		);
4459
		$url      = add_query_arg( $args, $base_url );
4460
		return $url;
4461
	}
4462
4463
	static function translate_current_user_to_role() {
4464
		foreach ( self::$capability_translations as $role => $cap ) {
4465
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4466
				return $role;
4467
			}
4468
		}
4469
4470
		return false;
4471
	}
4472
4473
	static function translate_user_to_role( $user ) {
4474
		foreach ( self::$capability_translations as $role => $cap ) {
4475
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4476
				return $role;
4477
			}
4478
		}
4479
4480
		return false;
4481
    }
4482
4483
	static function translate_role_to_cap( $role ) {
4484
		if ( ! isset( self::$capability_translations[$role] ) ) {
4485
			return false;
4486
		}
4487
4488
		return self::$capability_translations[$role];
4489
	}
4490
4491
	static function sign_role( $role, $user_id = null ) {
4492
		if ( empty( $user_id ) ) {
4493
			$user_id = (int) get_current_user_id();
4494
		}
4495
4496
		if ( ! $user_id  ) {
4497
			return false;
4498
		}
4499
4500
		$token = Jetpack_Data::get_access_token();
4501
		if ( ! $token || is_wp_error( $token ) ) {
4502
			return false;
4503
		}
4504
4505
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4506
	}
4507
4508
4509
	/**
4510
	 * Builds a URL to the Jetpack connection auth page
4511
	 *
4512
	 * @since 3.9.5
4513
	 *
4514
	 * @param bool $raw If true, URL will not be escaped.
4515
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4516
	 *                              If string, will be a custom redirect.
4517
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4518
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4519
	 *
4520
	 * @return string Connect URL
4521
	 */
4522
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4523
		$site_id = Jetpack_Options::get_option( 'id' );
4524
		$blog_token = Jetpack_Data::get_access_token();
4525
4526
		if ( $register || ! $blog_token || ! $site_id ) {
4527
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4528
4529
			if ( ! empty( $redirect ) ) {
4530
				$url = add_query_arg(
4531
					'redirect',
4532
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4533
					$url
4534
				);
4535
			}
4536
4537
			if( is_network_admin() ) {
4538
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4539
			}
4540
		} else {
4541
4542
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4543
			// because otherwise this logic can get us in to a loop.
4544
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4545
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4546
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4547
4548
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4549
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4550
					'1.1'
4551
				);
4552
4553
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4554
4555
					// Generating a register URL instead to refresh the existing token
4556
					return $this->build_connect_url( $raw, $redirect, $from, true );
4557
				}
4558
			}
4559
4560
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4561
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4562
			}
4563
4564
			$role = self::translate_current_user_to_role();
4565
			$signed_role = self::sign_role( $role );
4566
4567
			$user = wp_get_current_user();
4568
4569
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4570
			$redirect = $redirect
4571
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4572
				: $jetpack_admin_page;
4573
4574
			if( isset( $_REQUEST['is_multisite'] ) ) {
4575
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4576
			}
4577
4578
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4579
4580
			/**
4581
			 * Filter the type of authorization.
4582
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4583
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4584
			 *
4585
			 * @since 4.3.3
4586
			 *
4587
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4588
			 */
4589
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4590
4591
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4592
4593
			$args = urlencode_deep(
4594
				array(
4595
					'response_type' => 'code',
4596
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4597
					'redirect_uri'  => add_query_arg(
4598
						array(
4599
							'action'   => 'authorize',
4600
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4601
							'redirect' => urlencode( $redirect ),
4602
						),
4603
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4604
					),
4605
					'state'         => $user->ID,
4606
					'scope'         => $signed_role,
4607
					'user_email'    => $user->user_email,
4608
					'user_login'    => $user->user_login,
4609
					'is_active'     => Jetpack::is_active(),
4610
					'jp_version'    => JETPACK__VERSION,
4611
					'auth_type'     => $auth_type,
4612
					'secret'        => $secrets['secret_1'],
4613
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4614
					'blogname'      => get_option( 'blogname' ),
4615
					'site_url'      => site_url(),
4616
					'home_url'      => home_url(),
4617
					'site_icon'     => get_site_icon_url(),
4618
					'site_lang'     => get_locale(),
4619
					'_ui'           => $tracks_identity['_ui'],
4620
					'_ut'           => $tracks_identity['_ut'],
4621
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4622
				)
4623
			);
4624
4625
			self::apply_activation_source_to_args( $args );
4626
4627
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4628
		}
4629
4630
		if ( $from ) {
4631
			$url = add_query_arg( 'from', $from, $url );
4632
		}
4633
4634
		// Ensure that class to get the affiliate code is loaded
4635
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4636
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4637
		}
4638
		// Get affiliate code and add it to the URL
4639
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4640
4641
		$calypso_env = $this->get_calypso_env();
4642
4643
		if ( ! empty( $calypso_env ) ) {
4644
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4645
		}
4646
4647
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4648
	}
4649
4650
	/**
4651
	 * Get our assumed site creation date.
4652
	 * Calculated based on the earlier date of either:
4653
	 * - Earliest admin user registration date.
4654
	 * - Earliest date of post of any post type.
4655
	 *
4656
	 * @since 7.2.0
4657
	 *
4658
	 * @return string Assumed site creation date and time.
4659
	 */
4660
	public static function get_assumed_site_creation_date() {
4661
		$earliest_registered_users = get_users( array(
4662
			'role'    => 'administrator',
4663
			'orderby' => 'user_registered',
4664
			'order'   => 'ASC',
4665
			'fields'  => array( 'user_registered' ),
4666
			'number'  => 1,
4667
		) );
4668
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4669
4670
		$earliest_posts = get_posts( array(
4671
			'posts_per_page' => 1,
4672
			'post_type'      => 'any',
4673
			'post_status'    => 'any',
4674
			'orderby'        => 'date',
4675
			'order'          => 'ASC',
4676
		) );
4677
4678
		// If there are no posts at all, we'll count only on user registration date.
4679
		if ( $earliest_posts ) {
4680
			$earliest_post_date = $earliest_posts[0]->post_date;
4681
		} else {
4682
			$earliest_post_date = PHP_INT_MAX;
4683
		}
4684
4685
		return min( $earliest_registration_date, $earliest_post_date );
4686
	}
4687
4688
	public static function apply_activation_source_to_args( &$args ) {
4689
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4690
4691
		if ( $activation_source_name ) {
4692
			$args['_as'] = urlencode( $activation_source_name );
4693
		}
4694
4695
		if ( $activation_source_keyword ) {
4696
			$args['_ak'] = urlencode( $activation_source_keyword );
4697
		}
4698
	}
4699
4700
	function build_reconnect_url( $raw = false ) {
4701
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4702
		return $raw ? $url : esc_url( $url );
4703
	}
4704
4705
	public static function admin_url( $args = null ) {
4706
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4707
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4708
		return $url;
4709
	}
4710
4711
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4712
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4713
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4714
	}
4715
4716
	function dismiss_jetpack_notice() {
4717
4718
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4719
			return;
4720
		}
4721
4722
		switch( $_GET['jetpack-notice'] ) {
4723
			case 'dismiss':
4724
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4725
4726
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4727
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4728
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4729
				}
4730
				break;
4731
			case 'jetpack-protect-multisite-opt-out':
4732
4733
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4734
					// Don't show the banner again
4735
4736
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4737
					// redirect back to the page that had the notice
4738
					if ( wp_get_referer() ) {
4739
						wp_safe_redirect( wp_get_referer() );
4740
					} else {
4741
						// Take me to Jetpack
4742
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4743
					}
4744
				}
4745
				break;
4746
		}
4747
	}
4748
4749
	public static function sort_modules( $a, $b ) {
4750
		if ( $a['sort'] == $b['sort'] )
4751
			return 0;
4752
4753
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4754
	}
4755
4756
	function ajax_recheck_ssl() {
4757
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4758
		$result = Jetpack::permit_ssl( true );
4759
		wp_send_json( array(
4760
			'enabled' => $result,
4761
			'message' => get_transient( 'jetpack_https_test_message' )
4762
		) );
4763
	}
4764
4765
/* Client API */
4766
4767
	/**
4768
	 * Returns the requested Jetpack API URL
4769
	 *
4770
	 * @return string
4771
	 */
4772
	public static function api_url( $relative_url ) {
4773
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4774
	}
4775
4776
	/**
4777
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4778
	 */
4779
	public static function fix_url_for_bad_hosts( $url ) {
4780
		if ( 0 !== strpos( $url, 'https://' ) ) {
4781
			return $url;
4782
		}
4783
4784
		switch ( JETPACK_CLIENT__HTTPS ) {
4785
			case 'ALWAYS' :
4786
				return $url;
4787
			case 'NEVER' :
4788
				return set_url_scheme( $url, 'http' );
4789
			// default : case 'AUTO' :
4790
		}
4791
4792
		// we now return the unmodified SSL URL by default, as a security precaution
4793
		return $url;
4794
	}
4795
4796
	/**
4797
	 * Create a random secret for validating onboarding payload
4798
	 *
4799
	 * @return string Secret token
4800
	 */
4801
	public static function create_onboarding_token() {
4802
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4803
			$token = wp_generate_password( 32, false );
4804
			Jetpack_Options::update_option( 'onboarding', $token );
4805
		}
4806
4807
		return $token;
4808
	}
4809
4810
	/**
4811
	 * Remove the onboarding token
4812
	 *
4813
	 * @return bool True on success, false on failure
4814
	 */
4815
	public static function invalidate_onboarding_token() {
4816
		return Jetpack_Options::delete_option( 'onboarding' );
4817
	}
4818
4819
	/**
4820
	 * Validate an onboarding token for a specific action
4821
	 *
4822
	 * @return boolean True if token/action pair is accepted, false if not
4823
	 */
4824
	public static function validate_onboarding_token_action( $token, $action ) {
4825
		// Compare tokens, bail if tokens do not match
4826
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4827
			return false;
4828
		}
4829
4830
		// List of valid actions we can take
4831
		$valid_actions = array(
4832
			'/jetpack/v4/settings',
4833
		);
4834
4835
		// Whitelist the action
4836
		if ( ! in_array( $action, $valid_actions ) ) {
4837
			return false;
4838
		}
4839
4840
		return true;
4841
	}
4842
4843
	/**
4844
	 * Checks to see if the URL is using SSL to connect with Jetpack
4845
	 *
4846
	 * @since 2.3.3
4847
	 * @return boolean
4848
	 */
4849
	public static function permit_ssl( $force_recheck = false ) {
4850
		// Do some fancy tests to see if ssl is being supported
4851
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4852
			$message = '';
4853
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4854
				$ssl = 0;
4855
			} else {
4856
				switch ( JETPACK_CLIENT__HTTPS ) {
4857
					case 'NEVER':
4858
						$ssl = 0;
4859
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4860
						break;
4861
					case 'ALWAYS':
4862
					case 'AUTO':
4863
					default:
4864
						$ssl = 1;
4865
						break;
4866
				}
4867
4868
				// If it's not 'NEVER', test to see
4869
				if ( $ssl ) {
4870
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4871
						$ssl = 0;
4872
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4873
					} else {
4874
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4875
						if ( is_wp_error( $response ) ) {
4876
							$ssl = 0;
4877
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4878
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4879
							$ssl = 0;
4880
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4881
						}
4882
					}
4883
				}
4884
			}
4885
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4886
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4887
		}
4888
4889
		return (bool) $ssl;
4890
	}
4891
4892
	/*
4893
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4894
	 */
4895
	public function alert_auto_ssl_fail() {
4896
		if ( ! current_user_can( 'manage_options' ) )
4897
			return;
4898
4899
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4900
		?>
4901
4902
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4903
			<div class="jp-banner__content">
4904
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4905
				<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>
4906
				<p>
4907
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4908
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4909
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4910
				</p>
4911
				<p>
4912
					<?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' ),
4913
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4914
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4915
				</p>
4916
			</div>
4917
		</div>
4918
		<style>
4919
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4920
		</style>
4921
		<script type="text/javascript">
4922
			jQuery( document ).ready( function( $ ) {
4923
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4924
					var $this = $( this );
4925
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4926
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4927
					e.preventDefault();
4928
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4929
					$.post( ajaxurl, data )
4930
					  .done( function( response ) {
4931
					  	if ( response.enabled ) {
4932
					  		$( '#jetpack-ssl-warning' ).hide();
4933
					  	} else {
4934
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4935
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4936
					  	}
4937
					  }.bind( $this ) );
4938
				} );
4939
			} );
4940
		</script>
4941
4942
		<?php
4943
	}
4944
4945
	/**
4946
	 * Returns the Jetpack XML-RPC API
4947
	 *
4948
	 * @return string
4949
	 */
4950
	public static function xmlrpc_api_url() {
4951
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4952
		return untrailingslashit( $base ) . '/xmlrpc.php';
4953
	}
4954
4955
	/**
4956
	 * Creates two secret tokens and the end of life timestamp for them.
4957
	 *
4958
	 * Note these tokens are unique per call, NOT static per site for connecting.
4959
	 *
4960
	 * @since 2.6
4961
	 * @return array
4962
	 */
4963
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4964
		if ( false === $user_id ) {
4965
			$user_id = get_current_user_id();
4966
		}
4967
4968
		return self::init()->connection_manager->generate_secrets( $action, $user_id, $exp );
4969
	}
4970
4971
	public static function get_secrets( $action, $user_id ) {
4972
		$secrets = self::init()->connection_manager->get_secrets( $action, $user_id );
4973
4974
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4975
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4976
		}
4977
4978
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4979
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4980
		}
4981
4982
		return $secrets;
4983
	}
4984
4985
	public static function delete_secrets( $action, $user_id ) {
4986
		return self::init()->connection_manager->delete_secrets( $action, $user_id );
4987
	}
4988
4989
	/**
4990
	 * Builds the timeout limit for queries talking with the wpcom servers.
4991
	 *
4992
	 * Based on local php max_execution_time in php.ini
4993
	 *
4994
	 * @since 2.6
4995
	 * @return int
4996
	 * @deprecated
4997
	 **/
4998
	public function get_remote_query_timeout_limit() {
4999
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5000
		return Jetpack::get_max_execution_time();
5001
	}
5002
5003
	/**
5004
	 * Builds the timeout limit for queries talking with the wpcom servers.
5005
	 *
5006
	 * Based on local php max_execution_time in php.ini
5007
	 *
5008
	 * @since 5.4
5009
	 * @return int
5010
	 **/
5011
	public static function get_max_execution_time() {
5012
		$timeout = (int) ini_get( 'max_execution_time' );
5013
5014
		// Ensure exec time set in php.ini
5015
		if ( ! $timeout ) {
5016
			$timeout = 30;
5017
		}
5018
		return $timeout;
5019
	}
5020
5021
	/**
5022
	 * Sets a minimum request timeout, and returns the current timeout
5023
	 *
5024
	 * @since 5.4
5025
	 **/
5026
	public static function set_min_time_limit( $min_timeout ) {
5027
		$timeout = self::get_max_execution_time();
5028
		if ( $timeout < $min_timeout ) {
5029
			$timeout = $min_timeout;
5030
			set_time_limit( $timeout );
5031
		}
5032
		return $timeout;
5033
	}
5034
5035
5036
	/**
5037
	 * Takes the response from the Jetpack register new site endpoint and
5038
	 * verifies it worked properly.
5039
	 *
5040
	 * @since 2.6
5041
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5042
	 **/
5043
	public function validate_remote_register_response( $response ) {
5044
	  if ( is_wp_error( $response ) ) {
5045
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5046
		}
5047
5048
		$code   = wp_remote_retrieve_response_code( $response );
5049
		$entity = wp_remote_retrieve_body( $response );
5050
		if ( $entity )
5051
			$registration_response = json_decode( $entity );
5052
		else
5053
			$registration_response = false;
5054
5055
		$code_type = intval( $code / 100 );
5056
		if ( 5 == $code_type ) {
5057
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5058
		} elseif ( 408 == $code ) {
5059
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5060
		} elseif ( ! empty( $registration_response->error ) ) {
5061
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5062
				$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' );
5063
			} else {
5064
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5065
			}
5066
5067
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5068
		} elseif ( 200 != $code ) {
5069
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5070
		}
5071
5072
		// Jetpack ID error block
5073
		if ( empty( $registration_response->jetpack_id ) ) {
5074
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5075
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5076
			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 );
5077
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5078
			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 );
5079
		}
5080
5081
	    return $registration_response;
5082
	}
5083
	/**
5084
	 * @return bool|WP_Error
5085
	 */
5086
	public static function register() {
5087
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5088
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5089
		$secrets = Jetpack::generate_secrets( 'register' );
5090
5091 View Code Duplication
		if (
5092
			empty( $secrets['secret_1'] ) ||
5093
			empty( $secrets['secret_2'] ) ||
5094
			empty( $secrets['exp'] )
5095
		) {
5096
			return new Jetpack_Error( 'missing_secrets' );
5097
		}
5098
5099
		// better to try (and fail) to set a higher timeout than this system
5100
		// supports than to have register fail for more users than it should
5101
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5102
5103
		$gmt_offset = get_option( 'gmt_offset' );
5104
		if ( ! $gmt_offset ) {
5105
			$gmt_offset = 0;
5106
		}
5107
5108
		$stats_options = get_option( 'stats_options' );
5109
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5110
5111
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5112
5113
		$args = array(
5114
			'method'  => 'POST',
5115
			'body'    => array(
5116
				'siteurl'         => site_url(),
5117
				'home'            => home_url(),
5118
				'gmt_offset'      => $gmt_offset,
5119
				'timezone_string' => (string) get_option( 'timezone_string' ),
5120
				'site_name'       => (string) get_option( 'blogname' ),
5121
				'secret_1'        => $secrets['secret_1'],
5122
				'secret_2'        => $secrets['secret_2'],
5123
				'site_lang'       => get_locale(),
5124
				'timeout'         => $timeout,
5125
				'stats_id'        => $stats_id,
5126
				'state'           => get_current_user_id(),
5127
				'_ui'             => $tracks_identity['_ui'],
5128
				'_ut'             => $tracks_identity['_ut'],
5129
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5130
				'jetpack_version' => JETPACK__VERSION
5131
			),
5132
			'headers' => array(
5133
				'Accept' => 'application/json',
5134
			),
5135
			'timeout' => $timeout,
5136
		);
5137
5138
		self::apply_activation_source_to_args( $args['body'] );
5139
5140
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5141
5142
		// Make sure the response is valid and does not contain any Jetpack errors
5143
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5144
		if ( is_wp_error( $registration_details ) ) {
5145
			return $registration_details;
5146
		} elseif ( ! $registration_details ) {
5147
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5148
		}
5149
5150 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5151
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5152
		}
5153
5154
		if ( isset( $registration_details->jetpack_public ) ) {
5155
			$jetpack_public = (int) $registration_details->jetpack_public;
5156
		} else {
5157
			$jetpack_public = false;
5158
		}
5159
5160
		Jetpack_Options::update_options(
5161
			array(
5162
				'id'         => (int)    $registration_details->jetpack_id,
5163
				'blog_token' => (string) $registration_details->jetpack_secret,
5164
				'public'     => $jetpack_public,
5165
			)
5166
		);
5167
5168
		/**
5169
		 * Fires when a site is registered on WordPress.com.
5170
		 *
5171
		 * @since 3.7.0
5172
		 *
5173
		 * @param int $json->jetpack_id Jetpack Blog ID.
5174
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5175
		 * @param int|bool $jetpack_public Is the site public.
5176
		 */
5177
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5178
5179
		// Initialize Jump Start for the first and only time.
5180
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5181
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5182
5183
			$jetpack = Jetpack::init();
5184
5185
			$jetpack->stat( 'jumpstart', 'unique-views' );
5186
			$jetpack->do_stats( 'server_side' );
5187
		};
5188
5189
		return true;
5190
	}
5191
5192
	/**
5193
	 * If the db version is showing something other that what we've got now, bump it to current.
5194
	 *
5195
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5196
	 */
5197
	public static function maybe_set_version_option() {
5198
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5199
		if ( JETPACK__VERSION != $version ) {
5200
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5201
5202
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5203
				/** This action is documented in class.jetpack.php */
5204
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5205
			}
5206
5207
			return true;
5208
		}
5209
		return false;
5210
	}
5211
5212
/* Client Server API */
5213
5214
	/**
5215
	 * Loads the Jetpack XML-RPC client
5216
	 */
5217
	public static function load_xml_rpc_client() {
5218
		require_once ABSPATH . WPINC . '/class-IXR.php';
5219
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5220
	}
5221
5222
	/**
5223
	 * Resets the saved authentication state in between testing requests.
5224
	 */
5225
	public function reset_saved_auth_state() {
5226
		$this->xmlrpc_verification = null;
5227
		$this->rest_authentication_status = null;
5228
	}
5229
5230
	function verify_xml_rpc_signature() {
5231
		if ( $this->xmlrpc_verification ) {
5232
			return $this->xmlrpc_verification;
5233
		}
5234
5235
		// It's not for us
5236
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5237
			return false;
5238
		}
5239
5240
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

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

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

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5241
		if (
5242
			empty( $token_key )
5243
		||
5244
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5245
		) {
5246
			return false;
5247
		}
5248
5249
		if ( '0' === $user_id ) {
5250
			$token_type = 'blog';
5251
			$user_id = 0;
5252
		} else {
5253
			$token_type = 'user';
5254
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5255
				return false;
5256
			}
5257
			$user_id = (int) $user_id;
5258
5259
			$user = new WP_User( $user_id );
5260
			if ( ! $user || ! $user->exists() ) {
5261
				return false;
5262
			}
5263
		}
5264
5265
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
5266
		if ( ! $token ) {
5267
			return false;
5268
		}
5269
5270
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5271
5272
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5273
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5274
			$post_data   = $_POST;
5275
			$file_hashes = array();
5276
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5277
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5278
					continue;
5279
				}
5280
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5281
				$file_hashes[$post_data_key] = $post_data_value;
5282
			}
5283
5284
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5285
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5286
				$post_data[$post_data_key] = $post_data_value;
5287
			}
5288
5289
			ksort( $post_data );
5290
5291
			$body = http_build_query( stripslashes_deep( $post_data ) );
5292
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5293
			$body = file_get_contents( 'php://input' );
5294
		} else {
5295
			$body = null;
5296
		}
5297
5298
		$signature = $jetpack_signature->sign_current_request(
5299
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5300
		);
5301
5302
		if ( ! $signature ) {
5303
			return false;
5304
		} else if ( is_wp_error( $signature ) ) {
5305
			return $signature;
5306
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5307
			return false;
5308
		}
5309
5310
		$timestamp = (int) $_GET['timestamp'];
5311
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5312
5313
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5314
			return false;
5315
		}
5316
5317
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5318
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5319
			if ( ! empty( $_GET['onboarding'] ) ) {
5320
				$jpo = $_GET;
5321
			} else {
5322
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5323
			}
5324
5325
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5326
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5327
5328
			if (
5329
				isset( $jpo_user ) && isset( $jpo_token ) &&
5330
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5331
				isset( $_GET['rest_route'] ) &&
5332
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5333
			) {
5334
				$jpUser = get_user_by( 'email', $jpo_user );
5335
				if ( is_a( $jpUser, 'WP_User' ) ) {
5336
					wp_set_current_user( $jpUser->ID );
5337
					$user_can = is_multisite()
5338
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5339
						: current_user_can( 'manage_options' );
5340
					if ( $user_can ) {
5341
						$token_type = 'user';
5342
						$token->external_user_id = $jpUser->ID;
5343
					}
5344
				}
5345
			}
5346
		}
5347
5348
		$this->xmlrpc_verification = array(
5349
			'type'      => $token_type,
5350
			'token_key' => $token_key,
5351
			'user_id'   => $token->external_user_id,
5352
		);
5353
5354
		return $this->xmlrpc_verification;
5355
	}
5356
5357
	/**
5358
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5359
	 */
5360
	function authenticate_jetpack( $user, $username, $password ) {
5361
		if ( is_a( $user, 'WP_User' ) ) {
5362
			return $user;
5363
		}
5364
5365
		$token_details = $this->verify_xml_rpc_signature();
5366
5367
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5368
			return $user;
5369
		}
5370
5371
		if ( 'user' !== $token_details['type'] ) {
5372
			return $user;
5373
		}
5374
5375
		if ( ! $token_details['user_id'] ) {
5376
			return $user;
5377
		}
5378
5379
		nocache_headers();
5380
5381
		return new WP_User( $token_details['user_id'] );
5382
	}
5383
5384
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5385
	// Uses the existing XMLRPC request signing implementation.
5386
	function wp_rest_authenticate( $user ) {
5387
		if ( ! empty( $user ) ) {
5388
			// Another authentication method is in effect.
5389
			return $user;
5390
		}
5391
5392
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5393
			// Nothing to do for this authentication method.
5394
			return null;
5395
		}
5396
5397
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5398
			// Nothing to do for this authentication method.
5399
			return null;
5400
		}
5401
5402
		// Ensure that we always have the request body available.  At this
5403
		// point, the WP REST API code to determine the request body has not
5404
		// run yet.  That code may try to read from 'php://input' later, but
5405
		// this can only be done once per request in PHP versions prior to 5.6.
5406
		// So we will go ahead and perform this read now if needed, and save
5407
		// the request body where both the Jetpack signature verification code
5408
		// and the WP REST API code can see it.
5409
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5410
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5411
		}
5412
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5413
5414
		// Only support specific request parameters that have been tested and
5415
		// are known to work with signature verification.  A different method
5416
		// can be passed to the WP REST API via the '?_method=' parameter if
5417
		// needed.
5418
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5419
			$this->rest_authentication_status = new WP_Error(
5420
				'rest_invalid_request',
5421
				__( 'This request method is not supported.', 'jetpack' ),
5422
				array( 'status' => 400 )
5423
			);
5424
			return null;
5425
		}
5426
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5427
			$this->rest_authentication_status = new WP_Error(
5428
				'rest_invalid_request',
5429
				__( 'This request method does not support body parameters.', 'jetpack' ),
5430
				array( 'status' => 400 )
5431
			);
5432
			return null;
5433
		}
5434
5435
		$verified = $this->verify_xml_rpc_signature();
5436
5437
		if ( is_wp_error( $verified ) ) {
5438
			$this->rest_authentication_status = $verified;
5439
			return null;
5440
		}
5441
5442
		if (
5443
			$verified &&
5444
			isset( $verified['type'] ) &&
5445
			'user' === $verified['type'] &&
5446
			! empty( $verified['user_id'] )
5447
		) {
5448
			// Authentication successful.
5449
			$this->rest_authentication_status = true;
5450
			return $verified['user_id'];
5451
		}
5452
5453
		// Something else went wrong.  Probably a signature error.
5454
		$this->rest_authentication_status = new WP_Error(
5455
			'rest_invalid_signature',
5456
			__( 'The request is not signed correctly.', 'jetpack' ),
5457
			array( 'status' => 400 )
5458
		);
5459
		return null;
5460
	}
5461
5462
	/**
5463
	 * Report authentication status to the WP REST API.
5464
	 *
5465
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5466
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5467
	 */
5468
	public function wp_rest_authentication_errors( $value ) {
5469
		if ( $value !== null ) {
5470
			return $value;
5471
		}
5472
		return $this->rest_authentication_status;
5473
	}
5474
5475
	function add_nonce( $timestamp, $nonce ) {
5476
		global $wpdb;
5477
		static $nonces_used_this_request = array();
5478
5479
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5480
			return $nonces_used_this_request["$timestamp:$nonce"];
5481
		}
5482
5483
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5484
		$timestamp = (int) $timestamp;
5485
		$nonce     = esc_sql( $nonce );
5486
5487
		// Raw query so we can avoid races: add_option will also update
5488
		$show_errors = $wpdb->show_errors( false );
5489
5490
		$old_nonce = $wpdb->get_row(
5491
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5492
		);
5493
5494
		if ( is_null( $old_nonce ) ) {
5495
			$return = $wpdb->query(
5496
				$wpdb->prepare(
5497
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5498
					"jetpack_nonce_{$timestamp}_{$nonce}",
5499
					time(),
5500
					'no'
5501
				)
5502
			);
5503
		} else {
5504
			$return = false;
5505
		}
5506
5507
		$wpdb->show_errors( $show_errors );
5508
5509
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5510
5511
		return $return;
5512
	}
5513
5514
	/**
5515
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5516
	 * Capture it here so we can verify the signature later.
5517
	 */
5518
	function xmlrpc_methods( $methods ) {
5519
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5520
		return $methods;
5521
	}
5522
5523
	function public_xmlrpc_methods( $methods ) {
5524
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5525
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5526
		}
5527
		return $methods;
5528
	}
5529
5530
	function jetpack_getOptions( $args ) {
5531
		global $wp_xmlrpc_server;
5532
5533
		$wp_xmlrpc_server->escape( $args );
5534
5535
		$username	= $args[1];
5536
		$password	= $args[2];
5537
5538
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5539
			return $wp_xmlrpc_server->error;
5540
		}
5541
5542
		$options = array();
5543
		$user_data = $this->get_connected_user_data();
5544
		if ( is_array( $user_data ) ) {
5545
			$options['jetpack_user_id'] = array(
5546
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5547
				'readonly'      => true,
5548
				'value'         => $user_data['ID'],
5549
			);
5550
			$options['jetpack_user_login'] = array(
5551
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5552
				'readonly'      => true,
5553
				'value'         => $user_data['login'],
5554
			);
5555
			$options['jetpack_user_email'] = array(
5556
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5557
				'readonly'      => true,
5558
				'value'         => $user_data['email'],
5559
			);
5560
			$options['jetpack_user_site_count'] = array(
5561
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5562
				'readonly'      => true,
5563
				'value'         => $user_data['site_count'],
5564
			);
5565
		}
5566
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5567
		$args = stripslashes_deep( $args );
5568
		return $wp_xmlrpc_server->wp_getOptions( $args );
5569
	}
5570
5571
	function xmlrpc_options( $options ) {
5572
		$jetpack_client_id = false;
5573
		if ( self::is_active() ) {
5574
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5575
		}
5576
		$options['jetpack_version'] = array(
5577
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5578
				'readonly'      => true,
5579
				'value'         => JETPACK__VERSION,
5580
		);
5581
5582
		$options['jetpack_client_id'] = array(
5583
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5584
				'readonly'      => true,
5585
				'value'         => $jetpack_client_id,
5586
		);
5587
		return $options;
5588
	}
5589
5590
	public static function clean_nonces( $all = false ) {
5591
		global $wpdb;
5592
5593
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5594
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5595
5596
		if ( true !== $all ) {
5597
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5598
			$sql_args[] = time() - 3600;
5599
		}
5600
5601
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5602
5603
		$sql = $wpdb->prepare( $sql, $sql_args );
5604
5605
		for ( $i = 0; $i < 1000; $i++ ) {
5606
			if ( ! $wpdb->query( $sql ) ) {
5607
				break;
5608
			}
5609
		}
5610
	}
5611
5612
	/**
5613
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5614
	 * SET: state( $key, $value );
5615
	 * GET: $value = state( $key );
5616
	 *
5617
	 * @param string $key
0 ignored issues
show
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5619
	 * @param bool $restate private
5620
	 */
5621
	public static function state( $key = null, $value = null, $restate = false ) {
5622
		static $state = array();
5623
		static $path, $domain;
5624
		if ( ! isset( $path ) ) {
5625
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5626
			$admin_url = Jetpack::admin_url();
5627
			$bits      = wp_parse_url( $admin_url );
5628
5629
			if ( is_array( $bits ) ) {
5630
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5631
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5632
			} else {
5633
				$path = $domain = null;
5634
			}
5635
		}
5636
5637
		// Extract state from cookies and delete cookies
5638
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5639
			$yum = $_COOKIE[ 'jetpackState' ];
5640
			unset( $_COOKIE[ 'jetpackState' ] );
5641
			foreach ( $yum as $k => $v ) {
5642
				if ( strlen( $v ) )
5643
					$state[ $k ] = $v;
5644
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5645
			}
5646
		}
5647
5648
		if ( $restate ) {
5649
			foreach ( $state as $k => $v ) {
5650
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5651
			}
5652
			return;
5653
		}
5654
5655
		// Get a state variable
5656
		if ( isset( $key ) && ! isset( $value ) ) {
5657
			if ( array_key_exists( $key, $state ) )
5658
				return $state[ $key ];
5659
			return null;
5660
		}
5661
5662
		// Set a state variable
5663
		if ( isset ( $key ) && isset( $value ) ) {
5664
			if( is_array( $value ) && isset( $value[0] ) ) {
5665
				$value = $value[0];
5666
			}
5667
			$state[ $key ] = $value;
5668
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5669
		}
5670
	}
5671
5672
	public static function restate() {
5673
		Jetpack::state( null, null, true );
5674
	}
5675
5676
	public static function check_privacy( $file ) {
5677
		static $is_site_publicly_accessible = null;
5678
5679
		if ( is_null( $is_site_publicly_accessible ) ) {
5680
			$is_site_publicly_accessible = false;
5681
5682
			Jetpack::load_xml_rpc_client();
5683
			$rpc = new Jetpack_IXR_Client();
5684
5685
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5686
			if ( $success ) {
5687
				$response = $rpc->getResponse();
5688
				if ( $response ) {
5689
					$is_site_publicly_accessible = true;
5690
				}
5691
			}
5692
5693
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5694
		}
5695
5696
		if ( $is_site_publicly_accessible ) {
5697
			return;
5698
		}
5699
5700
		$module_slug = self::get_module_slug( $file );
5701
5702
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5703
		if ( ! $privacy_checks ) {
5704
			$privacy_checks = $module_slug;
5705
		} else {
5706
			$privacy_checks .= ",$module_slug";
5707
		}
5708
5709
		Jetpack::state( 'privacy_checks', $privacy_checks );
5710
	}
5711
5712
	/**
5713
	 * Helper method for multicall XMLRPC.
5714
	 */
5715
	public static function xmlrpc_async_call() {
5716
		global $blog_id;
5717
		static $clients = array();
5718
5719
		$client_blog_id = is_multisite() ? $blog_id : 0;
5720
5721
		if ( ! isset( $clients[$client_blog_id] ) ) {
5722
			Jetpack::load_xml_rpc_client();
5723
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5724
			if ( function_exists( 'ignore_user_abort' ) ) {
5725
				ignore_user_abort( true );
5726
			}
5727
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5728
		}
5729
5730
		$args = func_get_args();
5731
5732
		if ( ! empty( $args[0] ) ) {
5733
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5734
		} elseif ( is_multisite() ) {
5735
			foreach ( $clients as $client_blog_id => $client ) {
5736
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5737
					continue;
5738
				}
5739
5740
				$switch_success = switch_to_blog( $client_blog_id, true );
5741
				if ( ! $switch_success ) {
5742
					continue;
5743
				}
5744
5745
				flush();
5746
				$client->query();
5747
5748
				restore_current_blog();
5749
			}
5750
		} else {
5751
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5752
				flush();
5753
				$clients[0]->query();
5754
			}
5755
		}
5756
	}
5757
5758
	public static function staticize_subdomain( $url ) {
5759
5760
		// Extract hostname from URL
5761
		$host = parse_url( $url, PHP_URL_HOST );
5762
5763
		// Explode hostname on '.'
5764
		$exploded_host = explode( '.', $host );
5765
5766
		// Retrieve the name and TLD
5767
		if ( count( $exploded_host ) > 1 ) {
5768
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5769
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5770
			// Rebuild domain excluding subdomains
5771
			$domain = $name . '.' . $tld;
5772
		} else {
5773
			$domain = $host;
5774
		}
5775
		// Array of Automattic domains
5776
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5777
5778
		// Return $url if not an Automattic domain
5779
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5780
			return $url;
5781
		}
5782
5783
		if ( is_ssl() ) {
5784
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5785
		}
5786
5787
		srand( crc32( basename( $url ) ) );
5788
		$static_counter = rand( 0, 2 );
5789
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5790
5791
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5792
	}
5793
5794
/* JSON API Authorization */
5795
5796
	/**
5797
	 * Handles the login action for Authorizing the JSON API
5798
	 */
5799
	function login_form_json_api_authorization() {
5800
		$this->verify_json_api_authorization_request();
5801
5802
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5803
5804
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5805
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5806
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5807
	}
5808
5809
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5810
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5811
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5812
			return $url;
5813
		}
5814
5815
		$parsed_url = parse_url( $url );
5816
		$url = strtok( $url, '?' );
5817
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5818
		if ( ! empty( $parsed_url['query'] ) )
5819
			$url .= "&{$parsed_url['query']}";
5820
5821
		return $url;
5822
	}
5823
5824
	// Make sure the POSTed request is handled by the same action
5825
	function preserve_action_in_login_form_for_json_api_authorization() {
5826
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5827
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5828
	}
5829
5830
	// If someone logs in to approve API access, store the Access Code in usermeta
5831
	function store_json_api_authorization_token( $user_login, $user ) {
5832
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5833
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5834
		$token = wp_generate_password( 32, false );
5835
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5836
	}
5837
5838
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5839
	function allow_wpcom_public_api_domain( $domains ) {
5840
		$domains[] = 'public-api.wordpress.com';
5841
		return $domains;
5842
	}
5843
5844
	static function is_redirect_encoded( $redirect_url ) {
5845
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5846
	}
5847
5848
	// Add all wordpress.com environments to the safe redirect whitelist
5849
	function allow_wpcom_environments( $domains ) {
5850
		$domains[] = 'wordpress.com';
5851
		$domains[] = 'wpcalypso.wordpress.com';
5852
		$domains[] = 'horizon.wordpress.com';
5853
		$domains[] = 'calypso.localhost';
5854
		return $domains;
5855
	}
5856
5857
	// Add the Access Code details to the public-api.wordpress.com redirect
5858
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5859
		return add_query_arg(
5860
			urlencode_deep(
5861
				array(
5862
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5863
					'jetpack-user-id' => (int) $user->ID,
5864
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5865
				)
5866
			),
5867
			$redirect_to
5868
		);
5869
	}
5870
5871
5872
	/**
5873
	 * Verifies the request by checking the signature
5874
	 *
5875
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5876
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5877
	 *
5878
	 * @param null|array $environment
5879
	 */
5880
	function verify_json_api_authorization_request( $environment = null ) {
5881
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5882
5883
		$environment = is_null( $environment )
5884
			? $_REQUEST
5885
			: $environment;
5886
5887
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5888
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
5889
		if ( ! $token || empty( $token->secret ) ) {
5890
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5891
		}
5892
5893
		$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' );
5894
5895
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5896
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5897
			JetpackTracking::record_user_event( 'error_double_encode' );
5898
5899
			$die_error = sprintf(
5900
				/* translators: %s is a URL */
5901
				__( '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' ),
5902
				'https://jetpack.com/support/double-encoding/'
5903
			);
5904
		}
5905
5906
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5907
5908
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5909
			$signature = $jetpack_signature->sign_request(
5910
				$environment['token'],
5911
				$environment['timestamp'],
5912
				$environment['nonce'],
5913
				'',
5914
				'GET',
5915
				$environment['jetpack_json_api_original_query'],
5916
				null,
5917
				true
5918
			);
5919
		} else {
5920
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5921
		}
5922
5923
		if ( ! $signature ) {
5924
			wp_die( $die_error );
5925
		} else if ( is_wp_error( $signature ) ) {
5926
			wp_die( $die_error );
5927
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5928
			if ( is_ssl() ) {
5929
				// 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
5930
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5931
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5932
					wp_die( $die_error );
5933
				}
5934
			} else {
5935
				wp_die( $die_error );
5936
			}
5937
		}
5938
5939
		$timestamp = (int) $environment['timestamp'];
5940
		$nonce     = stripslashes( (string) $environment['nonce'] );
5941
5942
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5943
			// De-nonce the nonce, at least for 5 minutes.
5944
			// 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)
5945
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5946
			if ( $old_nonce_time < time() - 300 ) {
5947
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5948
			}
5949
		}
5950
5951
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5952
		$data_filters = array(
5953
			'state'        => 'opaque',
5954
			'client_id'    => 'int',
5955
			'client_title' => 'string',
5956
			'client_image' => 'url',
5957
		);
5958
5959
		foreach ( $data_filters as $key => $sanitation ) {
5960
			if ( ! isset( $data->$key ) ) {
5961
				wp_die( $die_error );
5962
			}
5963
5964
			switch ( $sanitation ) {
5965
			case 'int' :
5966
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5967
				break;
5968
			case 'opaque' :
5969
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5970
				break;
5971
			case 'string' :
5972
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5973
				break;
5974
			case 'url' :
5975
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5976
				break;
5977
			}
5978
		}
5979
5980
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5981
			wp_die( $die_error );
5982
		}
5983
	}
5984
5985
	function login_message_json_api_authorization( $message ) {
5986
		return '<p class="message">' . sprintf(
5987
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5988
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5989
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5990
	}
5991
5992
	/**
5993
	 * Get $content_width, but with a <s>twist</s> filter.
5994
	 */
5995
	public static function get_content_width() {
5996
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5997
			? $GLOBALS['content_width']
5998
			: false;
5999
		/**
6000
		 * Filter the Content Width value.
6001
		 *
6002
		 * @since 2.2.3
6003
		 *
6004
		 * @param string $content_width Content Width value.
6005
		 */
6006
		return apply_filters( 'jetpack_content_width', $content_width );
6007
	}
6008
6009
	/**
6010
	 * Pings the WordPress.com Mirror Site for the specified options.
6011
	 *
6012
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6013
	 *
6014
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6015
	 */
6016
	public function get_cloud_site_options( $option_names ) {
6017
		$option_names = array_filter( (array) $option_names, 'is_string' );
6018
6019
		Jetpack::load_xml_rpc_client();
6020
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6021
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6022
		if ( $xml->isError() ) {
6023
			return array(
6024
				'error_code' => $xml->getErrorCode(),
6025
				'error_msg'  => $xml->getErrorMessage(),
6026
			);
6027
		}
6028
		$cloud_site_options = $xml->getResponse();
6029
6030
		return $cloud_site_options;
6031
	}
6032
6033
	/**
6034
	 * Checks if the site is currently in an identity crisis.
6035
	 *
6036
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6037
	 */
6038
	public static function check_identity_crisis() {
6039
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6040
			return false;
6041
		}
6042
6043
		return Jetpack_Options::get_option( 'sync_error_idc' );
6044
	}
6045
6046
	/**
6047
	 * Checks whether the home and siteurl specifically are whitelisted
6048
	 * Written so that we don't have re-check $key and $value params every time
6049
	 * we want to check if this site is whitelisted, for example in footer.php
6050
	 *
6051
	 * @since  3.8.0
6052
	 * @return bool True = already whitelisted False = not whitelisted
6053
	 */
6054
	public static function is_staging_site() {
6055
		$is_staging = false;
6056
6057
		$known_staging = array(
6058
			'urls' => array(
6059
				'#\.staging\.wpengine\.com$#i', // WP Engine
6060
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6061
				),
6062
			'constants' => array(
6063
				'IS_WPE_SNAPSHOT',      // WP Engine
6064
				'KINSTA_DEV_ENV',       // Kinsta.com
6065
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6066
				'JETPACK_STAGING_MODE', // Generic
6067
				)
6068
			);
6069
		/**
6070
		 * Filters the flags of known staging sites.
6071
		 *
6072
		 * @since 3.9.0
6073
		 *
6074
		 * @param array $known_staging {
6075
		 *     An array of arrays that each are used to check if the current site is staging.
6076
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6077
		 *     @type array $constants PHP constants of known staging/developement environments.
6078
		 *  }
6079
		 */
6080
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6081
6082
		if ( isset( $known_staging['urls'] ) ) {
6083
			foreach ( $known_staging['urls'] as $url ){
6084
				if ( preg_match( $url, site_url() ) ) {
6085
					$is_staging = true;
6086
					break;
6087
				}
6088
			}
6089
		}
6090
6091
		if ( isset( $known_staging['constants'] ) ) {
6092
			foreach ( $known_staging['constants'] as $constant ) {
6093
				if ( defined( $constant ) && constant( $constant ) ) {
6094
					$is_staging = true;
6095
				}
6096
			}
6097
		}
6098
6099
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6100
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6101
			$is_staging = true;
6102
		}
6103
6104
		/**
6105
		 * Filters is_staging_site check.
6106
		 *
6107
		 * @since 3.9.0
6108
		 *
6109
		 * @param bool $is_staging If the current site is a staging site.
6110
		 */
6111
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6112
	}
6113
6114
	/**
6115
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6116
	 *
6117
	 * @since 4.4.0
6118
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6119
	 *
6120
	 * @return bool
6121
	 */
6122
	public static function validate_sync_error_idc_option() {
6123
		$is_valid = false;
6124
6125
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6126
		if ( false === $idc_allowed ) {
6127
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6128
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6129
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6130
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6131
				$transient_duration = HOUR_IN_SECONDS;
6132
			} else {
6133
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6134
				$idc_allowed = '1';
6135
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6136
			}
6137
6138
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6139
		}
6140
6141
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6142
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6143
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6144
			$local_options = self::get_sync_error_idc_option();
6145
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6146
				$is_valid = true;
6147
			}
6148
		}
6149
6150
		/**
6151
		 * Filters whether the sync_error_idc option is valid.
6152
		 *
6153
		 * @since 4.4.0
6154
		 *
6155
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6156
		 */
6157
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6158
6159
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6160
			// Since the option exists, and did not validate, delete it
6161
			Jetpack_Options::delete_option( 'sync_error_idc' );
6162
		}
6163
6164
		return $is_valid;
6165
	}
6166
6167
	/**
6168
	 * Normalizes a url by doing three things:
6169
	 *  - Strips protocol
6170
	 *  - Strips www
6171
	 *  - Adds a trailing slash
6172
	 *
6173
	 * @since 4.4.0
6174
	 * @param string $url
6175
	 * @return WP_Error|string
6176
	 */
6177
	public static function normalize_url_protocol_agnostic( $url ) {
6178
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6179
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6180
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6181
		}
6182
6183
		// Strip www and protocols
6184
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6185
		return $url;
6186
	}
6187
6188
	/**
6189
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6190
	 *
6191
	 * @since 4.4.0
6192
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6193
	 *
6194
	 * @param array $response
6195
	 * @return array Array of the local urls, wpcom urls, and error code
6196
	 */
6197
	public static function get_sync_error_idc_option( $response = array() ) {
6198
		// Since the local options will hit the database directly, store the values
6199
		// in a transient to allow for autoloading and caching on subsequent views.
6200
		$local_options = get_transient( 'jetpack_idc_local' );
6201
		if ( false === $local_options ) {
6202
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6203
			$local_options = array(
6204
				'home'    => Jetpack_Sync_Functions::home_url(),
6205
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6206
			);
6207
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6208
		}
6209
6210
		$options = array_merge( $local_options, $response );
6211
6212
		$returned_values = array();
6213
		foreach( $options as $key => $option ) {
6214
			if ( 'error_code' === $key ) {
6215
				$returned_values[ $key ] = $option;
6216
				continue;
6217
			}
6218
6219
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6220
				continue;
6221
			}
6222
6223
			$returned_values[ $key ] = $normalized_url;
6224
		}
6225
6226
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6227
6228
		return $returned_values;
6229
	}
6230
6231
	/**
6232
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6233
	 * If set to true, the site will be put into staging mode.
6234
	 *
6235
	 * @since 4.3.2
6236
	 * @return bool
6237
	 */
6238
	public static function sync_idc_optin() {
6239
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6240
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6241
		} else {
6242
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6243
		}
6244
6245
		/**
6246
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6247
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6248
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6249
		 *
6250
		 * @since 4.3.2
6251
		 *
6252
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6253
		 */
6254
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6255
	}
6256
6257
	/**
6258
	 * Maybe Use a .min.css stylesheet, maybe not.
6259
	 *
6260
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6261
	 */
6262
	public static function maybe_min_asset( $url, $path, $plugin ) {
6263
		// Short out on things trying to find actual paths.
6264
		if ( ! $path || empty( $plugin ) ) {
6265
			return $url;
6266
		}
6267
6268
		$path = ltrim( $path, '/' );
6269
6270
		// Strip out the abspath.
6271
		$base = dirname( plugin_basename( $plugin ) );
6272
6273
		// Short out on non-Jetpack assets.
6274
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6275
			return $url;
6276
		}
6277
6278
		// File name parsing.
6279
		$file              = "{$base}/{$path}";
6280
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6281
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6282
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6283
		$extension         = array_shift( $file_name_parts_r );
6284
6285
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6286
			// Already pointing at the minified version.
6287
			if ( 'min' === $file_name_parts_r[0] ) {
6288
				return $url;
6289
			}
6290
6291
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6292
			if ( file_exists( $min_full_path ) ) {
6293
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6294
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6295
				if ( 'css' === $extension ) {
6296
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6297
					self::$min_assets[ $key ] = $path;
6298
				}
6299
			}
6300
		}
6301
6302
		return $url;
6303
	}
6304
6305
	/**
6306
	 * If the asset is minified, let's flag .min as the suffix.
6307
	 *
6308
	 * Attached to `style_loader_src` filter.
6309
	 *
6310
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

Loading history...
6311
	 * @param string $handle The registered handle of the script in question.
6312
	 * @param string $href The url of the asset in question.
0 ignored issues
show
There is no parameter named $href. Was it maybe removed?

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

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

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

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

Loading history...
6313
	 */
6314
	public static function set_suffix_on_min( $src, $handle ) {
6315
		if ( false === strpos( $src, '.min.css' ) ) {
6316
			return $src;
6317
		}
6318
6319
		if ( ! empty( self::$min_assets ) ) {
6320
			foreach ( self::$min_assets as $file => $path ) {
6321
				if ( false !== strpos( $src, $file ) ) {
6322
					wp_style_add_data( $handle, 'suffix', '.min' );
6323
					return $src;
6324
				}
6325
			}
6326
		}
6327
6328
		return $src;
6329
	}
6330
6331
	/**
6332
	 * Maybe inlines a stylesheet.
6333
	 *
6334
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6335
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6336
	 *
6337
	 * Attached to `style_loader_tag` filter.
6338
	 *
6339
	 * @param string $tag The tag that would link to the external asset.
6340
	 * @param string $handle The registered handle of the script in question.
6341
	 *
6342
	 * @return string
6343
	 */
6344
	public static function maybe_inline_style( $tag, $handle ) {
6345
		global $wp_styles;
6346
		$item = $wp_styles->registered[ $handle ];
6347
6348
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6349
			return $tag;
6350
		}
6351
6352
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6353
			$href = $matches[1];
6354
			// Strip off query string
6355
			if ( $pos = strpos( $href, '?' ) ) {
6356
				$href = substr( $href, 0, $pos );
6357
			}
6358
			// Strip off fragment
6359
			if ( $pos = strpos( $href, '#' ) ) {
6360
				$href = substr( $href, 0, $pos );
6361
			}
6362
		} else {
6363
			return $tag;
6364
		}
6365
6366
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6367
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6368
			return $tag;
6369
		}
6370
6371
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6372
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6373
			// And this isn't the pass that actually deals with the RTL version...
6374
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6375
				// Short out, as the RTL version will deal with it in a moment.
6376
				return $tag;
6377
			}
6378
		}
6379
6380
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6381
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6382
		if ( $css ) {
6383
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6384
			if ( empty( $item->extra['after'] ) ) {
6385
				wp_add_inline_style( $handle, $css );
6386
			} else {
6387
				array_unshift( $item->extra['after'], $css );
6388
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6389
			}
6390
		}
6391
6392
		return $tag;
6393
	}
6394
6395
	/**
6396
	 * Loads a view file from the views
6397
	 *
6398
	 * Data passed in with the $data parameter will be available in the
6399
	 * template file as $data['value']
6400
	 *
6401
	 * @param string $template - Template file to load
6402
	 * @param array $data - Any data to pass along to the template
6403
	 * @return boolean - If template file was found
6404
	 **/
6405
	public function load_view( $template, $data = array() ) {
6406
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6407
6408
		if( file_exists( $views_dir . $template ) ) {
6409
			require_once( $views_dir . $template );
6410
			return true;
6411
		}
6412
6413
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6414
		return false;
6415
	}
6416
6417
	/**
6418
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6419
	 */
6420
	public function deprecated_hooks() {
6421
		global $wp_filter;
6422
6423
		/*
6424
		 * Format:
6425
		 * deprecated_filter_name => replacement_name
6426
		 *
6427
		 * If there is no replacement, use null for replacement_name
6428
		 */
6429
		$deprecated_list = array(
6430
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6431
			'wpl_sharing_2014_1'                                     => null,
6432
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6433
			'jetpack_identity_crisis_options_to_check'               => null,
6434
			'update_option_jetpack_single_user_site'                 => null,
6435
			'audio_player_default_colors'                            => null,
6436
			'add_option_jetpack_featured_images_enabled'             => null,
6437
			'add_option_jetpack_update_details'                      => null,
6438
			'add_option_jetpack_updates'                             => null,
6439
			'add_option_jetpack_network_name'                        => null,
6440
			'add_option_jetpack_network_allow_new_registrations'     => null,
6441
			'add_option_jetpack_network_add_new_users'               => null,
6442
			'add_option_jetpack_network_site_upload_space'           => null,
6443
			'add_option_jetpack_network_upload_file_types'           => null,
6444
			'add_option_jetpack_network_enable_administration_menus' => null,
6445
			'add_option_jetpack_is_multi_site'                       => null,
6446
			'add_option_jetpack_is_main_network'                     => null,
6447
			'add_option_jetpack_main_network_site'                   => null,
6448
			'jetpack_sync_all_registered_options'                    => null,
6449
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6450
			'jetpack_is_post_mailable'                               => null,
6451
			'jetpack_seo_site_host'                                  => null,
6452
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6453
			'jetpack_holiday_snow_option_name'                       => null,
6454
			'jetpack_holiday_chance_of_snow'                         => null,
6455
			'jetpack_holiday_snow_js_url'                            => null,
6456
			'jetpack_is_holiday_snow_season'                         => null,
6457
			'jetpack_holiday_snow_option_updated'                    => null,
6458
			'jetpack_holiday_snowing'                                => null,
6459
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6460
			'jetpack_cache_plans'                                    => null,
6461
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6462
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6463
			'jetpack_enable_site_verification'                       => null,
6464
			'can_display_jetpack_manage_notice'                      => null,
6465
			// Removed in Jetpack 7.3.0
6466
			'atd_load_scripts'                                       => null,
6467
			'atd_http_post_timeout'                                  => null,
6468
			'atd_http_post_error'                                    => null,
6469
			'atd_service_domain'                                     => null,
6470
		);
6471
6472
		// This is a silly loop depth. Better way?
6473
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6474
			if ( has_action( $hook ) ) {
6475
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6476
					foreach( $values AS $hooked ) {
6477
						if ( is_callable( $hooked['function'] ) ) {
6478
							$function_name = 'an anonymous function';
6479
						} else {
6480
							$function_name = $hooked['function'];
6481
						}
6482
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6483
					}
6484
				}
6485
			}
6486
		}
6487
	}
6488
6489
	/**
6490
	 * Converts any url in a stylesheet, to the correct absolute url.
6491
	 *
6492
	 * Considerations:
6493
	 *  - Normal, relative URLs     `feh.png`
6494
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6495
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6496
	 *  - Absolute URLs             `http://domain.com/feh.png`
6497
	 *  - Domain root relative URLs `/feh.png`
6498
	 *
6499
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6500
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6501
	 *
6502
	 * @return mixed|string
6503
	 */
6504
	public static function absolutize_css_urls( $css, $css_file_url ) {
6505
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6506
		$css_dir = dirname( $css_file_url );
6507
		$p       = parse_url( $css_dir );
6508
		$domain  = sprintf(
6509
					'%1$s//%2$s%3$s%4$s',
6510
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6511
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6512
					$p['host'],
6513
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6514
				);
6515
6516
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6517
			$find = $replace = array();
6518
			foreach ( $matches as $match ) {
6519
				$url = trim( $match['path'], "'\" \t" );
6520
6521
				// If this is a data url, we don't want to mess with it.
6522
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6523
					continue;
6524
				}
6525
6526
				// If this is an absolute or protocol-agnostic url,
6527
				// we don't want to mess with it.
6528
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6529
					continue;
6530
				}
6531
6532
				switch ( substr( $url, 0, 1 ) ) {
6533
					case '/':
6534
						$absolute = $domain . $url;
6535
						break;
6536
					default:
6537
						$absolute = $css_dir . '/' . $url;
6538
				}
6539
6540
				$find[]    = $match[0];
6541
				$replace[] = sprintf( 'url("%s")', $absolute );
6542
			}
6543
			$css = str_replace( $find, $replace, $css );
6544
		}
6545
6546
		return $css;
6547
	}
6548
6549
	/**
6550
	 * This methods removes all of the registered css files on the front end
6551
	 * from Jetpack in favor of using a single file. In effect "imploding"
6552
	 * all the files into one file.
6553
	 *
6554
	 * Pros:
6555
	 * - Uses only ONE css asset connection instead of 15
6556
	 * - Saves a minimum of 56k
6557
	 * - Reduces server load
6558
	 * - Reduces time to first painted byte
6559
	 *
6560
	 * Cons:
6561
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6562
	 *		should not cause any issues with themes.
6563
	 * - Plugins/themes dequeuing styles no longer do anything. See
6564
	 *		jetpack_implode_frontend_css filter for a workaround
6565
	 *
6566
	 * For some situations developers may wish to disable css imploding and
6567
	 * instead operate in legacy mode where each file loads seperately and
6568
	 * can be edited individually or dequeued. This can be accomplished with
6569
	 * the following line:
6570
	 *
6571
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6572
	 *
6573
	 * @since 3.2
6574
	 **/
6575
	public function implode_frontend_css( $travis_test = false ) {
6576
		$do_implode = true;
6577
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6578
			$do_implode = false;
6579
		}
6580
6581
		// Do not implode CSS when the page loads via the AMP plugin.
6582
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6583
			$do_implode = false;
6584
		}
6585
6586
		/**
6587
		 * Allow CSS to be concatenated into a single jetpack.css file.
6588
		 *
6589
		 * @since 3.2.0
6590
		 *
6591
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6592
		 */
6593
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6594
6595
		// Do not use the imploded file when default behavior was altered through the filter
6596
		if ( ! $do_implode ) {
6597
			return;
6598
		}
6599
6600
		// We do not want to use the imploded file in dev mode, or if not connected
6601
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6602
			if ( ! $travis_test ) {
6603
				return;
6604
			}
6605
		}
6606
6607
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6608
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6609
			return;
6610
		}
6611
6612
		/*
6613
		 * Now we assume Jetpack is connected and able to serve the single
6614
		 * file.
6615
		 *
6616
		 * In the future there will be a check here to serve the file locally
6617
		 * or potentially from the Jetpack CDN
6618
		 *
6619
		 * For now:
6620
		 * - Enqueue a single imploded css file
6621
		 * - Zero out the style_loader_tag for the bundled ones
6622
		 * - Be happy, drink scotch
6623
		 */
6624
6625
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6626
6627
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6628
6629
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6630
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6631
	}
6632
6633
	function concat_remove_style_loader_tag( $tag, $handle ) {
6634
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6635
			$tag = '';
6636
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6637
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6638
			}
6639
		}
6640
6641
		return $tag;
6642
	}
6643
6644
	/*
6645
	 * Check the heartbeat data
6646
	 *
6647
	 * Organizes the heartbeat data by severity.  For example, if the site
6648
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6649
	 *
6650
	 * Data will be added to "caution" array, if it either:
6651
	 *  - Out of date Jetpack version
6652
	 *  - Out of date WP version
6653
	 *  - Out of date PHP version
6654
	 *
6655
	 * $return array $filtered_data
6656
	 */
6657
	public static function jetpack_check_heartbeat_data() {
6658
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6659
6660
		$good    = array();
6661
		$caution = array();
6662
		$bad     = array();
6663
6664
		foreach ( $raw_data as $stat => $value ) {
6665
6666
			// Check jetpack version
6667
			if ( 'version' == $stat ) {
6668
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6669
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6670
					continue;
6671
				}
6672
			}
6673
6674
			// Check WP version
6675
			if ( 'wp-version' == $stat ) {
6676
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6677
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6678
					continue;
6679
				}
6680
			}
6681
6682
			// Check PHP version
6683
			if ( 'php-version' == $stat ) {
6684
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6685
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6686
					continue;
6687
				}
6688
			}
6689
6690
			// Check ID crisis
6691
			if ( 'identitycrisis' == $stat ) {
6692
				if ( 'yes' == $value ) {
6693
					$bad[ $stat ] = $value;
6694
					continue;
6695
				}
6696
			}
6697
6698
			// The rest are good :)
6699
			$good[ $stat ] = $value;
6700
		}
6701
6702
		$filtered_data = array(
6703
			'good'    => $good,
6704
			'caution' => $caution,
6705
			'bad'     => $bad
6706
		);
6707
6708
		return $filtered_data;
6709
	}
6710
6711
6712
	/*
6713
	 * This method is used to organize all options that can be reset
6714
	 * without disconnecting Jetpack.
6715
	 *
6716
	 * It is used in class.jetpack-cli.php to reset options
6717
	 *
6718
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6719
	 *
6720
	 * @return array of options to delete.
6721
	 */
6722
	public static function get_jetpack_options_for_reset() {
6723
		return Jetpack_Options::get_options_for_reset();
6724
	}
6725
6726
	/*
6727
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6728
	 * so we can bring them directly to their site in calypso.
6729
	 *
6730
	 * @param string | url
6731
	 * @return string | url without the guff
6732
	 */
6733
	public static function build_raw_urls( $url ) {
6734
		$strip_http = '/.*?:\/\//i';
6735
		$url = preg_replace( $strip_http, '', $url  );
6736
		$url = str_replace( '/', '::', $url );
6737
		return $url;
6738
	}
6739
6740
	/**
6741
	 * Stores and prints out domains to prefetch for page speed optimization.
6742
	 *
6743
	 * @param mixed $new_urls
6744
	 */
6745
	public static function dns_prefetch( $new_urls = null ) {
6746
		static $prefetch_urls = array();
6747
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6748
			echo "\r\n";
6749
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6750
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6751
			}
6752
		} elseif ( ! empty( $new_urls ) ) {
6753
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6754
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6755
			}
6756
			foreach ( (array) $new_urls as $this_new_url ) {
6757
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6758
			}
6759
			$prefetch_urls = array_unique( $prefetch_urls );
6760
		}
6761
	}
6762
6763
	public function wp_dashboard_setup() {
6764
		if ( self::is_active() ) {
6765
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6766
		}
6767
6768
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6769
			$widget_title = sprintf(
6770
				wp_kses(
6771
					/* translators: Placeholder is a Jetpack logo. */
6772
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6773
					array( 'span' => array() )
6774
				),
6775
				Jetpack::get_jp_emblem( true )
6776
			);
6777
6778
			wp_add_dashboard_widget(
6779
				'jetpack_summary_widget',
6780
				$widget_title,
6781
				array( __CLASS__, 'dashboard_widget' )
6782
			);
6783
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6784
6785
			// If we're inactive and not in development mode, sort our box to the top.
6786
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6787
				global $wp_meta_boxes;
6788
6789
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6790
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6791
6792
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6793
			}
6794
		}
6795
	}
6796
6797
	/**
6798
	 * @param mixed $result Value for the user's option
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
6799
	 * @return mixed
6800
	 */
6801
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6802
		if ( ! is_array( $sorted ) ) {
6803
			return $sorted;
6804
		}
6805
6806
		foreach ( $sorted as $box_context => $ids ) {
6807
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6808
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6809
				continue;
6810
			}
6811
6812
			$ids_array = explode( ',', $ids );
6813
			$key = array_search( 'dashboard_stats', $ids_array );
6814
6815
			if ( false !== $key ) {
6816
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6817
				$ids_array[ $key ] = 'jetpack_summary_widget';
6818
				$sorted[ $box_context ] = implode( ',', $ids_array );
6819
				// We've found it, stop searching, and just return.
6820
				break;
6821
			}
6822
		}
6823
6824
		return $sorted;
6825
	}
6826
6827
	public static function dashboard_widget() {
6828
		/**
6829
		 * Fires when the dashboard is loaded.
6830
		 *
6831
		 * @since 3.4.0
6832
		 */
6833
		do_action( 'jetpack_dashboard_widget' );
6834
	}
6835
6836
	public static function dashboard_widget_footer() {
6837
		?>
6838
		<footer>
6839
6840
		<div class="protect">
6841
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6842
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6843
				<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>
6844
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6845
				<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' ); ?>">
6846
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6847
				</a>
6848
			<?php else : ?>
6849
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6850
			<?php endif; ?>
6851
		</div>
6852
6853
		<div class="akismet">
6854
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6855
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6856
				<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>
6857
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6858
				<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">
6859
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6860
				</a>
6861
			<?php else : ?>
6862
				<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>
6863
			<?php endif; ?>
6864
		</div>
6865
6866
		</footer>
6867
		<?php
6868
	}
6869
6870
	/**
6871
	 * Return string containing the Jetpack logo.
6872
	 *
6873
	 * @since 3.9.0
6874
	 *
6875
	 * @param bool $logotype Should we use the full logotype (logo + text). Default to false.
6876
	 *
6877
	 * @return string
6878
	 */
6879
	public static function get_jp_emblem( $logotype = false ) {
6880
		$logo = '<path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/>';
6881
		$text = '
6882
<path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z" />
6883
<path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z" />
6884
<path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z" />
6885
<path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z" />
6886
<path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z" />
6887
<path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z" />
6888
<path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z" />
6889
		';
6890
6891
		return sprintf(
6892
			'<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 %1$s 32">%2$s</svg>',
6893
			( true === $logotype ? '118' : '32' ),
6894
			( true === $logotype ? $logo . $text : $logo )
6895
		);
6896
	}
6897
6898
	/*
6899
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6900
	 */
6901
	function jetpack_icon_user_connected( $columns ) {
6902
		$columns['user_jetpack'] = '';
6903
		return $columns;
6904
	}
6905
6906
	/*
6907
	 * Show Jetpack icon if the user is linked.
6908
	 */
6909
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6910
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6911
			$emblem_html = sprintf(
6912
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6913
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6914
				Jetpack::get_jp_emblem()
6915
			);
6916
			return $emblem_html;
6917
		}
6918
6919
		return $val;
6920
	}
6921
6922
	/*
6923
	 * Style the Jetpack user column
6924
	 */
6925
	function jetpack_user_col_style() {
6926
		global $current_screen;
6927
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6928
			<style>
6929
				.fixed .column-user_jetpack {
6930
					width: 21px;
6931
				}
6932
				.jp-emblem-user-admin svg {
6933
					width: 20px;
6934
					height: 20px;
6935
				}
6936
				.jp-emblem-user-admin path {
6937
					fill: #00BE28;
6938
				}
6939
			</style>
6940
		<?php }
6941
	}
6942
6943
	/**
6944
	 * Checks if Akismet is active and working.
6945
	 *
6946
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6947
	 * that implied usage of methods present since more recent version.
6948
	 * See https://github.com/Automattic/jetpack/pull/9585
6949
	 *
6950
	 * @since  5.1.0
6951
	 *
6952
	 * @return bool True = Akismet available. False = Aksimet not available.
6953
	 */
6954
	public static function is_akismet_active() {
6955
		static $status = null;
6956
6957
		if ( ! is_null( $status ) ) {
6958
			return $status;
6959
		}
6960
6961
		// Check if a modern version of Akismet is active.
6962
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6963
			$status = false;
6964
			return $status;
6965
		}
6966
6967
		// Make sure there is a key known to Akismet at all before verifying key.
6968
		$akismet_key = Akismet::get_api_key();
6969
		if ( ! $akismet_key ) {
6970
			$status = false;
6971
			return $status;
6972
		}
6973
6974
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6975
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6976
6977
		// 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.
6978
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6979
		// We cache the result of the Akismet key verification for ten minutes.
6980
		if ( ! $akismet_key_state || $recheck ) {
6981
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6982
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6983
		}
6984
6985
		$status = 'valid' === $akismet_key_state;
6986
6987
		return $status;
6988
	}
6989
6990
	/**
6991
	 * Checks if one or more function names is in debug_backtrace
6992
	 *
6993
	 * @param $names Mixed string name of function or array of string names of functions
6994
	 *
6995
	 * @return bool
6996
	 */
6997
	public static function is_function_in_backtrace( $names ) {
6998
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6999
		if ( ! is_array( $names ) ) {
7000
			$names = array( $names );
7001
		}
7002
		$names_as_keys = array_flip( $names );
7003
7004
		//Do check in constant O(1) time for PHP5.5+
7005
		if ( function_exists( 'array_column' ) ) {
7006
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
7007
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
7008
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
7009
			return ! empty ( $intersection );
7010
		}
7011
7012
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
7013
		foreach ( $backtrace as $call ) {
7014
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
7015
				return true;
7016
			}
7017
		}
7018
		return false;
7019
	}
7020
7021
	/**
7022
	 * Given a minified path, and a non-minified path, will return
7023
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7024
	 *
7025
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7026
	 * root Jetpack directory.
7027
	 *
7028
	 * @since 5.6.0
7029
	 *
7030
	 * @param string $min_path
7031
	 * @param string $non_min_path
7032
	 * @return string The URL to the file
7033
	 */
7034
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7035
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
7036
			? $non_min_path
7037
			: $min_path;
7038
7039
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7040
	}
7041
7042
	/**
7043
	 * Checks for whether Jetpack Backup & Scan is enabled.
7044
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7045
	 * @return bool|int|mixed
7046
	 */
7047
	public static function is_rewind_enabled() {
7048
		if ( ! Jetpack::is_active() ) {
7049
			return false;
7050
		}
7051
7052
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7053
		if ( false === $rewind_enabled ) {
7054
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7055
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7056
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7057
				&& ! empty( $rewind_data['state'] )
7058
				&& 'active' === $rewind_data['state'] )
7059
				? 1
7060
				: 0;
7061
7062
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7063
		}
7064
		return $rewind_enabled;
7065
	}
7066
7067
	/**
7068
	 * Return Calypso environment value; used for developing Jetpack and pairing
7069
	 * it with different Calypso enrionments, such as localhost.
7070
	 *
7071
	 * @since 7.4.0
7072
	 *
7073
	 * @return string Calypso environment
7074
	 */
7075
	public static function get_calypso_env() {
7076
		if ( isset( $_GET['calypso_env'] ) ) {
7077
			return sanitize_key( $_GET['calypso_env'] );
7078
		}
7079
7080
		if ( getenv( 'CALYPSO_ENV' ) ) {
7081
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7082
		}
7083
7084
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7085
			return sanitize_key( CALYPSO_ENV );
7086
		}
7087
7088
		return '';
7089
	}
7090
7091
	/**
7092
	 * Checks whether or not TOS has been agreed upon.
7093
	 * Will return true if a user has clicked to register, or is already connected.
7094
	 */
7095
	public static function jetpack_tos_agreed() {
7096
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7097
	}
7098
7099
	/**
7100
	 * Handles activating default modules as well general cleanup for the new connection.
7101
	 *
7102
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7103
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7104
	 * @param boolean $send_state_messages          Whether to send state messages.
7105
	 * @return void
7106
	 */
7107
	public static function handle_post_authorization_actions(
7108
		$activate_sso = false,
7109
		$redirect_on_activation_error = false,
7110
		$send_state_messages = true
7111
	) {
7112
		$other_modules = $activate_sso
7113
			? array( 'sso' )
7114
			: array();
7115
7116
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7117
			Jetpack::delete_active_modules();
7118
7119
			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...
7120
		} else {
7121
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7122
		}
7123
7124
		// Since this is a fresh connection, be sure to clear out IDC options
7125
		Jetpack_IDC::clear_all_idc_options();
7126
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7127
7128
		// Start nonce cleaner
7129
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7130
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7131
7132
		if ( $send_state_messages ) {
7133
			Jetpack::state( 'message', 'authorized' );
7134
		}
7135
	}
7136
7137
	/**
7138
	 * Returns a boolean for whether backups UI should be displayed or not.
7139
	 *
7140
	 * @return bool Should backups UI be displayed?
7141
	 */
7142
	public static function show_backups_ui() {
7143
		/**
7144
		 * Whether UI for backups should be displayed.
7145
		 *
7146
		 * @since 6.5.0
7147
		 *
7148
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7149
		 */
7150
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7151
	}
7152
7153
	/*
7154
	 * Deprecated manage functions
7155
	 */
7156
	function prepare_manage_jetpack_notice() {
7157
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7158
	}
7159
	function manage_activate_screen() {
7160
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7161
	}
7162
	function admin_jetpack_manage_notice() {
7163
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7164
	}
7165
	function opt_out_jetpack_manage_url() {
7166
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7167
	}
7168
	function opt_in_jetpack_manage_url() {
7169
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7170
	}
7171
	function opt_in_jetpack_manage_notice() {
7172
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7173
	}
7174
	function can_display_jetpack_manage_notice() {
7175
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7176
	}
7177
7178
	/**
7179
	 * Clean leftoveruser meta.
7180
	 *
7181
	 * Delete Jetpack-related user meta when it is no longer needed.
7182
	 *
7183
	 * @since 7.3.0
7184
	 *
7185
	 * @param int $user_id User ID being updated.
7186
	 */
7187
	public static function user_meta_cleanup( $user_id ) {
7188
		$meta_keys = array(
7189
			// AtD removed from Jetpack 7.3
7190
			'AtD_options',
7191
			'AtD_check_when',
7192
			'AtD_guess_lang',
7193
			'AtD_ignored_phrases',
7194
		);
7195
7196
		foreach ( $meta_keys as $meta_key ) {
7197
			if ( get_user_meta( $user_id, $meta_key ) ) {
7198
				delete_user_meta( $user_id, $meta_key );
7199
			}
7200
		}
7201
	}
7202
}
7203