Completed
Push — add/signature-error-reporting ( b95622...dc097f )
by
unknown
17:50 queued 08:19
created

class.jetpack.php (41 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

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

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

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

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

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

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

Loading history...
1788
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1789
	}
1790
1791
	/**
1792
	 * Gets current user IP address.
1793
	 *
1794
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1795
	 *
1796
	 * @return string                  Current user IP address.
1797
	 */
1798
	public static function current_user_ip( $check_all_headers = false ) {
1799
		if ( $check_all_headers ) {
1800
			foreach ( array(
1801
				'HTTP_CF_CONNECTING_IP',
1802
				'HTTP_CLIENT_IP',
1803
				'HTTP_X_FORWARDED_FOR',
1804
				'HTTP_X_FORWARDED',
1805
				'HTTP_X_CLUSTER_CLIENT_IP',
1806
				'HTTP_FORWARDED_FOR',
1807
				'HTTP_FORWARDED',
1808
				'HTTP_VIA',
1809
			) as $key ) {
1810
				if ( ! empty( $_SERVER[ $key ] ) ) {
1811
					return $_SERVER[ $key ];
1812
				}
1813
			}
1814
		}
1815
1816
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1817
	}
1818
1819
	/**
1820
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1821
	 */
1822
	function extra_oembed_providers() {
1823
		// Cloudup: https://dev.cloudup.com/#oembed
1824
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1825
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1826
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1827
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1828
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1829
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1830
	}
1831
1832
	/**
1833
	 * Synchronize connected user role changes
1834
	 */
1835
	function user_role_change( $user_id ) {
1836
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1837
		Jetpack_Sync_Users::user_role_change( $user_id );
1838
	}
1839
1840
	/**
1841
	 * Loads the currently active modules.
1842
	 */
1843
	public static function load_modules() {
1844
		if (
1845
			! self::is_active()
1846
			&& ! self::is_development_mode()
1847
			&& ! self::is_onboarding()
1848
			&& (
1849
				! is_multisite()
1850
				|| ! get_site_option( 'jetpack_protect_active' )
1851
			)
1852
		) {
1853
			return;
1854
		}
1855
1856
		$version = Jetpack_Options::get_option( 'version' );
1857 View Code Duplication
		if ( ! $version ) {
1858
			$version = $old_version = JETPACK__VERSION . ':' . time();
1859
			/** This action is documented in class.jetpack.php */
1860
			do_action( 'updating_jetpack_version', $version, false );
1861
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1862
		}
1863
		list( $version ) = explode( ':', $version );
1864
1865
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1866
1867
		$modules_data = array();
1868
1869
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1870
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1871
			$updated_modules = array();
1872
			foreach ( $modules as $module ) {
1873
				$modules_data[ $module ] = Jetpack::get_module( $module );
1874
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1875
					continue;
1876
				}
1877
1878
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1879
					continue;
1880
				}
1881
1882
				$updated_modules[] = $module;
1883
			}
1884
1885
			$modules = array_diff( $modules, $updated_modules );
1886
		}
1887
1888
		$is_development_mode = Jetpack::is_development_mode();
1889
1890
		foreach ( $modules as $index => $module ) {
1891
			// If we're in dev mode, disable modules requiring a connection
1892
			if ( $is_development_mode ) {
1893
				// Prime the pump if we need to
1894
				if ( empty( $modules_data[ $module ] ) ) {
1895
					$modules_data[ $module ] = Jetpack::get_module( $module );
1896
				}
1897
				// If the module requires a connection, but we're in local mode, don't include it.
1898
				if ( $modules_data[ $module ]['requires_connection'] ) {
1899
					continue;
1900
				}
1901
			}
1902
1903
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1904
				continue;
1905
			}
1906
1907
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1908
				unset( $modules[ $index ] );
1909
				self::update_active_modules( array_values( $modules ) );
1910
				continue;
1911
			}
1912
1913
			/**
1914
			 * Fires when a specific module is loaded.
1915
			 * The dynamic part of the hook, $module, is the module slug.
1916
			 *
1917
			 * @since 1.1.0
1918
			 */
1919
			do_action( 'jetpack_module_loaded_' . $module );
1920
		}
1921
1922
		/**
1923
		 * Fires when all the modules are loaded.
1924
		 *
1925
		 * @since 1.1.0
1926
		 */
1927
		do_action( 'jetpack_modules_loaded' );
1928
1929
		// 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.
1930
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1931
	}
1932
1933
	/**
1934
	 * Check if Jetpack's REST API compat file should be included
1935
	 * @action plugins_loaded
1936
	 * @return null
1937
	 */
1938
	public function check_rest_api_compat() {
1939
		/**
1940
		 * Filters the list of REST API compat files to be included.
1941
		 *
1942
		 * @since 2.2.5
1943
		 *
1944
		 * @param array $args Array of REST API compat files to include.
1945
		 */
1946
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1947
1948
		if ( function_exists( 'bbpress' ) )
1949
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1950
1951
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1952
			require_once $_jetpack_rest_api_compat_include;
1953
	}
1954
1955
	/**
1956
	 * Gets all plugins currently active in values, regardless of whether they're
1957
	 * traditionally activated or network activated.
1958
	 *
1959
	 * @todo Store the result in core's object cache maybe?
1960
	 */
1961
	public static function get_active_plugins() {
1962
		$active_plugins = (array) get_option( 'active_plugins', array() );
1963
1964
		if ( is_multisite() ) {
1965
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1966
			// whereas active_plugins stores them in the values.
1967
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1968
			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...
1969
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1970
			}
1971
		}
1972
1973
		sort( $active_plugins );
1974
1975
		return array_unique( $active_plugins );
1976
	}
1977
1978
	/**
1979
	 * Gets and parses additional plugin data to send with the heartbeat data
1980
	 *
1981
	 * @since 3.8.1
1982
	 *
1983
	 * @return array Array of plugin data
1984
	 */
1985
	public static function get_parsed_plugin_data() {
1986
		if ( ! function_exists( 'get_plugins' ) ) {
1987
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1988
		}
1989
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1990
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1991
		$active_plugins = Jetpack::get_active_plugins();
1992
1993
		$plugins = array();
1994
		foreach ( $all_plugins as $path => $plugin_data ) {
1995
			$plugins[ $path ] = array(
1996
					'is_active' => in_array( $path, $active_plugins ),
1997
					'file'      => $path,
1998
					'name'      => $plugin_data['Name'],
1999
					'version'   => $plugin_data['Version'],
2000
					'author'    => $plugin_data['Author'],
2001
			);
2002
		}
2003
2004
		return $plugins;
2005
	}
2006
2007
	/**
2008
	 * Gets and parses theme data to send with the heartbeat data
2009
	 *
2010
	 * @since 3.8.1
2011
	 *
2012
	 * @return array Array of theme data
2013
	 */
2014
	public static function get_parsed_theme_data() {
2015
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2016
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2017
2018
		$themes = array();
2019
		foreach ( $all_themes as $slug => $theme_data ) {
2020
			$theme_headers = array();
2021
			foreach ( $header_keys as $header_key ) {
2022
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2023
			}
2024
2025
			$themes[ $slug ] = array(
2026
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2027
					'slug' => $slug,
2028
					'theme_root' => $theme_data->get_theme_root_uri(),
2029
					'parent' => $theme_data->parent(),
2030
					'headers' => $theme_headers
2031
			);
2032
		}
2033
2034
		return $themes;
2035
	}
2036
2037
	/**
2038
	 * Checks whether a specific plugin is active.
2039
	 *
2040
	 * We don't want to store these in a static variable, in case
2041
	 * there are switch_to_blog() calls involved.
2042
	 */
2043
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2044
		return in_array( $plugin, self::get_active_plugins() );
2045
	}
2046
2047
	/**
2048
	 * Check if Jetpack's Open Graph tags should be used.
2049
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2050
	 *
2051
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2052
	 * @action plugins_loaded
2053
	 * @return null
2054
	 */
2055
	public function check_open_graph() {
2056
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2057
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2058
		}
2059
2060
		$active_plugins = self::get_active_plugins();
2061
2062
		if ( ! empty( $active_plugins ) ) {
2063
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2064
				if ( in_array( $plugin, $active_plugins ) ) {
2065
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2066
					break;
2067
				}
2068
			}
2069
		}
2070
2071
		/**
2072
		 * Allow the addition of Open Graph Meta Tags to all pages.
2073
		 *
2074
		 * @since 2.0.3
2075
		 *
2076
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2077
		 */
2078
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2079
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2080
		}
2081
	}
2082
2083
	/**
2084
	 * Check if Jetpack's Twitter tags should be used.
2085
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2086
	 *
2087
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2088
	 * @action plugins_loaded
2089
	 * @return null
2090
	 */
2091
	public function check_twitter_tags() {
2092
2093
		$active_plugins = self::get_active_plugins();
2094
2095
		if ( ! empty( $active_plugins ) ) {
2096
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2097
				if ( in_array( $plugin, $active_plugins ) ) {
2098
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2099
					break;
2100
				}
2101
			}
2102
		}
2103
2104
		/**
2105
		 * Allow Twitter Card Meta tags to be disabled.
2106
		 *
2107
		 * @since 2.6.0
2108
		 *
2109
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2110
		 */
2111
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2112
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2113
		}
2114
	}
2115
2116
	/**
2117
	 * Allows plugins to submit security reports.
2118
 	 *
2119
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2120
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2121
	 * @param array   $args         See definitions above
2122
	 */
2123
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2124
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2125
	}
2126
2127
/* Jetpack Options API */
2128
2129
	public static function get_option_names( $type = 'compact' ) {
2130
		return Jetpack_Options::get_option_names( $type );
2131
	}
2132
2133
	/**
2134
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2135
 	 *
2136
	 * @param string $name    Option name
2137
	 * @param mixed  $default (optional)
2138
	 */
2139
	public static function get_option( $name, $default = false ) {
2140
		return Jetpack_Options::get_option( $name, $default );
2141
	}
2142
2143
	/**
2144
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2145
 	 *
2146
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2147
	 * @param string $name  Option name
2148
	 * @param mixed  $value Option value
2149
	 */
2150
	public static function update_option( $name, $value ) {
2151
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2152
		return Jetpack_Options::update_option( $name, $value );
2153
	}
2154
2155
	/**
2156
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2157
 	 *
2158
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2159
	 * @param array $array array( option name => option value, ... )
2160
	 */
2161
	public static function update_options( $array ) {
2162
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2163
		return Jetpack_Options::update_options( $array );
2164
	}
2165
2166
	/**
2167
	 * Deletes the given option.  May be passed multiple option names as an array.
2168
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2169
	 *
2170
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2171
	 * @param string|array $names
2172
	 */
2173
	public static function delete_option( $names ) {
2174
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2175
		return Jetpack_Options::delete_option( $names );
2176
	}
2177
2178
	/**
2179
	 * Enters a user token into the user_tokens option
2180
	 *
2181
	 * @param int $user_id
2182
	 * @param string $token
2183
	 * return bool
2184
	 */
2185
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2186
		// not designed for concurrent updates
2187
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2188
		if ( ! is_array( $user_tokens ) )
2189
			$user_tokens = array();
2190
		$user_tokens[$user_id] = $token;
2191
		if ( $is_master_user ) {
2192
			$master_user = $user_id;
2193
			$options     = compact( 'user_tokens', 'master_user' );
2194
		} else {
2195
			$options = compact( 'user_tokens' );
2196
		}
2197
		return Jetpack_Options::update_options( $options );
2198
	}
2199
2200
	/**
2201
	 * Returns an array of all PHP files in the specified absolute path.
2202
	 * Equivalent to glob( "$absolute_path/*.php" ).
2203
	 *
2204
	 * @param string $absolute_path The absolute path of the directory to search.
2205
	 * @return array Array of absolute paths to the PHP files.
2206
	 */
2207
	public static function glob_php( $absolute_path ) {
2208
		if ( function_exists( 'glob' ) ) {
2209
			return glob( "$absolute_path/*.php" );
2210
		}
2211
2212
		$absolute_path = untrailingslashit( $absolute_path );
2213
		$files = array();
2214
		if ( ! $dir = @opendir( $absolute_path ) ) {
2215
			return $files;
2216
		}
2217
2218
		while ( false !== $file = readdir( $dir ) ) {
2219
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2220
				continue;
2221
			}
2222
2223
			$file = "$absolute_path/$file";
2224
2225
			if ( ! is_file( $file ) ) {
2226
				continue;
2227
			}
2228
2229
			$files[] = $file;
2230
		}
2231
2232
		closedir( $dir );
2233
2234
		return $files;
2235
	}
2236
2237
	public static function activate_new_modules( $redirect = false ) {
2238
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2239
			return;
2240
		}
2241
2242
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2243 View Code Duplication
		if ( ! $jetpack_old_version ) {
2244
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2245
			/** This action is documented in class.jetpack.php */
2246
			do_action( 'updating_jetpack_version', $version, false );
2247
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2248
		}
2249
2250
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2251
2252
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2253
			return;
2254
		}
2255
2256
		$active_modules     = Jetpack::get_active_modules();
2257
		$reactivate_modules = array();
2258
		foreach ( $active_modules as $active_module ) {
2259
			$module = Jetpack::get_module( $active_module );
2260
			if ( ! isset( $module['changed'] ) ) {
2261
				continue;
2262
			}
2263
2264
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2265
				continue;
2266
			}
2267
2268
			$reactivate_modules[] = $active_module;
2269
			Jetpack::deactivate_module( $active_module );
2270
		}
2271
2272
		$new_version = JETPACK__VERSION . ':' . time();
2273
		/** This action is documented in class.jetpack.php */
2274
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2275
		Jetpack_Options::update_options(
2276
			array(
2277
				'version'     => $new_version,
2278
				'old_version' => $jetpack_old_version,
2279
			)
2280
		);
2281
2282
		Jetpack::state( 'message', 'modules_activated' );
2283
		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...
2284
2285
		if ( $redirect ) {
2286
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2287
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2288
				$page = $_GET['page'];
2289
			}
2290
2291
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2292
			exit;
2293
		}
2294
	}
2295
2296
	/**
2297
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2298
	 * Make sure to tuck away module "library" files in a sub-directory.
2299
	 */
2300
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2301
		static $modules = null;
2302
2303
		if ( ! isset( $modules ) ) {
2304
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2305
			// Use the cache if we're on the front-end and it's available...
2306
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2307
				$modules = $available_modules_option[ JETPACK__VERSION ];
2308
			} else {
2309
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2310
2311
				$modules = array();
2312
2313
				foreach ( $files as $file ) {
2314
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2315
						continue;
2316
					}
2317
2318
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2319
				}
2320
2321
				Jetpack_Options::update_option( 'available_modules', array(
2322
					JETPACK__VERSION => $modules,
2323
				) );
2324
			}
2325
		}
2326
2327
		/**
2328
		 * Filters the array of modules available to be activated.
2329
		 *
2330
		 * @since 2.4.0
2331
		 *
2332
		 * @param array $modules Array of available modules.
2333
		 * @param string $min_version Minimum version number required to use modules.
2334
		 * @param string $max_version Maximum version number required to use modules.
2335
		 */
2336
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2337
2338
		if ( ! $min_version && ! $max_version ) {
2339
			return array_keys( $mods );
2340
		}
2341
2342
		$r = array();
2343
		foreach ( $mods as $slug => $introduced ) {
2344
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2345
				continue;
2346
			}
2347
2348
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2349
				continue;
2350
			}
2351
2352
			$r[] = $slug;
2353
		}
2354
2355
		return $r;
2356
	}
2357
2358
	/**
2359
	 * Default modules loaded on activation.
2360
	 */
2361
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2362
		$return = array();
2363
2364
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2365
			$module_data = Jetpack::get_module( $module );
2366
2367
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2368
				case 'yes' :
2369
					$return[] = $module;
2370
					break;
2371
				case 'public' :
2372
					if ( Jetpack_Options::get_option( 'public' ) ) {
2373
						$return[] = $module;
2374
					}
2375
					break;
2376
				case 'no' :
2377
				default :
2378
					break;
2379
			}
2380
		}
2381
		/**
2382
		 * Filters the array of default modules.
2383
		 *
2384
		 * @since 2.5.0
2385
		 *
2386
		 * @param array $return Array of default modules.
2387
		 * @param string $min_version Minimum version number required to use modules.
2388
		 * @param string $max_version Maximum version number required to use modules.
2389
		 */
2390
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2391
	}
2392
2393
	/**
2394
	 * Checks activated modules during auto-activation to determine
2395
	 * if any of those modules are being deprecated.  If so, close
2396
	 * them out, and add any replacement modules.
2397
	 *
2398
	 * Runs at priority 99 by default.
2399
	 *
2400
	 * This is run late, so that it can still activate a module if
2401
	 * the new module is a replacement for another that the user
2402
	 * currently has active, even if something at the normal priority
2403
	 * would kibosh everything.
2404
	 *
2405
	 * @since 2.6
2406
	 * @uses jetpack_get_default_modules filter
2407
	 * @param array $modules
2408
	 * @return array
2409
	 */
2410
	function handle_deprecated_modules( $modules ) {
2411
		$deprecated_modules = array(
2412
			'debug'            => null,  // Closed out and moved to the debugger library.
2413
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2414
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2415
		);
2416
2417
		// Don't activate SSO if they never completed activating WPCC.
2418
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2419
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2420
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2421
				$deprecated_modules['wpcc'] = null;
2422
			}
2423
		}
2424
2425
		foreach ( $deprecated_modules as $module => $replacement ) {
2426
			if ( Jetpack::is_module_active( $module ) ) {
2427
				self::deactivate_module( $module );
2428
				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...
2429
					$modules[] = $replacement;
2430
				}
2431
			}
2432
		}
2433
2434
		return array_unique( $modules );
2435
	}
2436
2437
	/**
2438
	 * Checks activated plugins during auto-activation to determine
2439
	 * if any of those plugins are in the list with a corresponding module
2440
	 * that is not compatible with the plugin. The module will not be allowed
2441
	 * to auto-activate.
2442
	 *
2443
	 * @since 2.6
2444
	 * @uses jetpack_get_default_modules filter
2445
	 * @param array $modules
2446
	 * @return array
2447
	 */
2448
	function filter_default_modules( $modules ) {
2449
2450
		$active_plugins = self::get_active_plugins();
2451
2452
		if ( ! empty( $active_plugins ) ) {
2453
2454
			// For each module we'd like to auto-activate...
2455
			foreach ( $modules as $key => $module ) {
2456
				// If there are potential conflicts for it...
2457
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2458
					// For each potential conflict...
2459
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2460
						// If that conflicting plugin is active...
2461
						if ( in_array( $plugin, $active_plugins ) ) {
2462
							// Remove that item from being auto-activated.
2463
							unset( $modules[ $key ] );
2464
						}
2465
					}
2466
				}
2467
			}
2468
		}
2469
2470
		return $modules;
2471
	}
2472
2473
	/**
2474
	 * Extract a module's slug from its full path.
2475
	 */
2476
	public static function get_module_slug( $file ) {
2477
		return str_replace( '.php', '', basename( $file ) );
2478
	}
2479
2480
	/**
2481
	 * Generate a module's path from its slug.
2482
	 */
2483
	public static function get_module_path( $slug ) {
2484
		/**
2485
		 * Filters the path of a modules.
2486
		 *
2487
		 * @since 7.4.0
2488
		 *
2489
		 * @param array $return The absolute path to a module's root php file
2490
		 * @param string $slug The module slug
2491
		 */
2492
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2493
	}
2494
2495
	/**
2496
	 * Load module data from module file. Headers differ from WordPress
2497
	 * plugin headers to avoid them being identified as standalone
2498
	 * plugins on the WordPress plugins page.
2499
	 */
2500
	public static function get_module( $module ) {
2501
		$headers = array(
2502
			'name'                      => 'Module Name',
2503
			'description'               => 'Module Description',
2504
			'jumpstart_desc'            => 'Jumpstart Description',
2505
			'sort'                      => 'Sort Order',
2506
			'recommendation_order'      => 'Recommendation Order',
2507
			'introduced'                => 'First Introduced',
2508
			'changed'                   => 'Major Changes In',
2509
			'deactivate'                => 'Deactivate',
2510
			'free'                      => 'Free',
2511
			'requires_connection'       => 'Requires Connection',
2512
			'auto_activate'             => 'Auto Activate',
2513
			'module_tags'               => 'Module Tags',
2514
			'feature'                   => 'Feature',
2515
			'additional_search_queries' => 'Additional Search Queries',
2516
			'plan_classes'              => 'Plans',
2517
		);
2518
2519
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2520
2521
		$mod = Jetpack::get_file_data( $file, $headers );
2522
		if ( empty( $mod['name'] ) ) {
2523
			return false;
2524
		}
2525
2526
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2527
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2528
		$mod['deactivate']              = empty( $mod['deactivate'] );
2529
		$mod['free']                    = empty( $mod['free'] );
2530
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2531
2532
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2533
			$mod['auto_activate'] = 'No';
2534
		} else {
2535
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2536
		}
2537
2538
		if ( $mod['module_tags'] ) {
2539
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2540
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2541
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2542
		} else {
2543
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2544
		}
2545
2546 View Code Duplication
		if ( $mod['plan_classes'] ) {
2547
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2548
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2549
		} else {
2550
			$mod['plan_classes'] = array( 'free' );
2551
		}
2552
2553 View Code Duplication
		if ( $mod['feature'] ) {
2554
			$mod['feature'] = explode( ',', $mod['feature'] );
2555
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2556
		} else {
2557
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2558
		}
2559
2560
		/**
2561
		 * Filters the feature array on a module.
2562
		 *
2563
		 * This filter allows you to control where each module is filtered: Recommended,
2564
		 * Jumpstart, and the default "Other" listing.
2565
		 *
2566
		 * @since 3.5.0
2567
		 *
2568
		 * @param array   $mod['feature'] The areas to feature this module:
2569
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2570
		 *     'Recommended' shows on the main Jetpack admin screen.
2571
		 *     'Other' should be the default if no other value is in the array.
2572
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2573
		 * @param array   $mod All the currently assembled module data.
2574
		 */
2575
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2576
2577
		/**
2578
		 * Filter the returned data about a module.
2579
		 *
2580
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2581
		 * so please be careful.
2582
		 *
2583
		 * @since 3.6.0
2584
		 *
2585
		 * @param array   $mod    The details of the requested module.
2586
		 * @param string  $module The slug of the module, e.g. sharedaddy
2587
		 * @param string  $file   The path to the module source file.
2588
		 */
2589
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2590
	}
2591
2592
	/**
2593
	 * Like core's get_file_data implementation, but caches the result.
2594
	 */
2595
	public static function get_file_data( $file, $headers ) {
2596
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2597
		$file_name = basename( $file );
2598
2599
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2600
2601
		$file_data_option = get_transient( $cache_key );
2602
2603
		if ( false === $file_data_option ) {
2604
			$file_data_option = array();
2605
		}
2606
2607
		$key           = md5( $file_name . serialize( $headers ) );
2608
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2609
2610
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2611
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2612
			return $file_data_option[ $key ];
2613
		}
2614
2615
		$data = get_file_data( $file, $headers );
2616
2617
		$file_data_option[ $key ] = $data;
2618
2619
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2620
2621
		return $data;
2622
	}
2623
2624
2625
	/**
2626
	 * Return translated module tag.
2627
	 *
2628
	 * @param string $tag Tag as it appears in each module heading.
2629
	 *
2630
	 * @return mixed
2631
	 */
2632
	public static function translate_module_tag( $tag ) {
2633
		return jetpack_get_module_i18n_tag( $tag );
2634
	}
2635
2636
	/**
2637
	 * Get i18n strings as a JSON-encoded string
2638
	 *
2639
	 * @return string The locale as JSON
2640
	 */
2641
	public static function get_i18n_data_json() {
2642
2643
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2644
		// JSON files with the file they should be included for. This is an md5
2645
		// of '_inc/build/admin.js'.
2646
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2647
2648
		$i18n_json =
2649
				   JETPACK__PLUGIN_DIR
2650
				   . 'languages/json/jetpack-'
2651
				   . get_user_locale()
2652
				   . '-'
2653
				   . $path_md5
2654
				   . '.json';
2655
2656
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2657
			$locale_data = @file_get_contents( $i18n_json );
2658
			if ( $locale_data ) {
2659
				return $locale_data;
2660
			}
2661
		}
2662
2663
		// Return valid empty Jed locale
2664
		return '{ "locale_data": { "messages": { "": {} } } }';
2665
	}
2666
2667
	/**
2668
	 * Add locale data setup to wp-i18n
2669
	 *
2670
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2671
	 *
2672
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2673
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2674
	 *
2675
	 * This method provides a safe way to request the setup multiple times but add the script at
2676
	 * most once.
2677
	 *
2678
	 * @since 6.7.0
2679
	 *
2680
	 * @return void
2681
	 */
2682
	public static function setup_wp_i18n_locale_data() {
2683
		static $script_added = false;
2684
		if ( ! $script_added ) {
2685
			$script_added = true;
2686
			wp_add_inline_script(
2687
				'wp-i18n',
2688
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2689
			);
2690
		}
2691
	}
2692
2693
	/**
2694
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2695
	 *
2696
	 * @since 3.9.2
2697
	 *
2698
	 * @param array $modules
2699
	 *
2700
	 * @return string|void
2701
	 */
2702
	public static function get_translated_modules( $modules ) {
2703
		foreach ( $modules as $index => $module ) {
2704
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2705
			if ( isset( $module['name'] ) ) {
2706
				$modules[ $index ]['name'] = $i18n_module['name'];
2707
			}
2708
			if ( isset( $module['description'] ) ) {
2709
				$modules[ $index ]['description'] = $i18n_module['description'];
2710
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2711
			}
2712
		}
2713
		return $modules;
2714
	}
2715
2716
	/**
2717
	 * Get a list of activated modules as an array of module slugs.
2718
	 */
2719
	public static function get_active_modules() {
2720
		$active = Jetpack_Options::get_option( 'active_modules' );
2721
2722
		if ( ! is_array( $active ) ) {
2723
			$active = array();
2724
		}
2725
2726
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2727
			$active[] = 'vaultpress';
2728
		} else {
2729
			$active = array_diff( $active, array( 'vaultpress' ) );
2730
		}
2731
2732
		//If protect is active on the main site of a multisite, it should be active on all sites.
2733
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2734
			$active[] = 'protect';
2735
		}
2736
2737
		/**
2738
		 * Allow filtering of the active modules.
2739
		 *
2740
		 * Gives theme and plugin developers the power to alter the modules that
2741
		 * are activated on the fly.
2742
		 *
2743
		 * @since 5.8.0
2744
		 *
2745
		 * @param array $active Array of active module slugs.
2746
		 */
2747
		$active = apply_filters( 'jetpack_active_modules', $active );
2748
2749
		return array_unique( $active );
2750
	}
2751
2752
	/**
2753
	 * Check whether or not a Jetpack module is active.
2754
	 *
2755
	 * @param string $module The slug of a Jetpack module.
2756
	 * @return bool
2757
	 *
2758
	 * @static
2759
	 */
2760
	public static function is_module_active( $module ) {
2761
		return in_array( $module, self::get_active_modules() );
2762
	}
2763
2764
	public static function is_module( $module ) {
2765
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2766
	}
2767
2768
	/**
2769
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2770
	 *
2771
	 * @param bool $catch True to start catching, False to stop.
2772
	 *
2773
	 * @static
2774
	 */
2775
	public static function catch_errors( $catch ) {
2776
		static $display_errors, $error_reporting;
2777
2778
		if ( $catch ) {
2779
			$display_errors  = @ini_set( 'display_errors', 1 );
2780
			$error_reporting = @error_reporting( E_ALL );
2781
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2782
		} else {
2783
			@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...
2784
			@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...
2785
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2786
		}
2787
	}
2788
2789
	/**
2790
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2791
	 */
2792
	public static function catch_errors_on_shutdown() {
2793
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2794
	}
2795
2796
	/**
2797
	 * Rewrite any string to make paths easier to read.
2798
	 *
2799
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2800
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2801
	 *
2802
	 * @param $string
2803
	 * @return mixed
2804
	 */
2805
	public static function alias_directories( $string ) {
2806
		// ABSPATH has a trailing slash.
2807
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2808
		// WP_CONTENT_DIR does not have a trailing slash.
2809
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2810
2811
		return $string;
2812
	}
2813
2814
	public static function activate_default_modules(
2815
		$min_version = false,
2816
		$max_version = false,
2817
		$other_modules = array(),
2818
		$redirect = true,
2819
		$send_state_messages = true
2820
	) {
2821
		$jetpack = Jetpack::init();
2822
2823
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2824
		$modules = array_merge( $other_modules, $modules );
2825
2826
		// Look for standalone plugins and disable if active.
2827
2828
		$to_deactivate = array();
2829
		foreach ( $modules as $module ) {
2830
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2831
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2832
			}
2833
		}
2834
2835
		$deactivated = array();
2836
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2837
			list( $probable_file, $probable_title ) = $deactivate_me;
2838
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2839
				$deactivated[] = $module;
2840
			}
2841
		}
2842
2843
		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...
2844
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2845
2846
			$url = add_query_arg(
2847
				array(
2848
					'action'   => 'activate_default_modules',
2849
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2850
				),
2851
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2852
			);
2853
			wp_safe_redirect( $url );
2854
			exit;
2855
		}
2856
2857
		/**
2858
		 * Fires before default modules are activated.
2859
		 *
2860
		 * @since 1.9.0
2861
		 *
2862
		 * @param string $min_version Minimum version number required to use modules.
2863
		 * @param string $max_version Maximum version number required to use modules.
2864
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2865
		 */
2866
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2867
2868
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2869
		if ( $send_state_messages ) {
2870
			Jetpack::restate();
2871
			Jetpack::catch_errors( true );
2872
		}
2873
2874
		$active = Jetpack::get_active_modules();
2875
2876
		foreach ( $modules as $module ) {
2877
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2878
				$active[] = $module;
2879
				self::update_active_modules( $active );
2880
				continue;
2881
			}
2882
2883
			if ( $send_state_messages && in_array( $module, $active ) ) {
2884
				$module_info = Jetpack::get_module( $module );
2885 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2886
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2887
					if ( $active_state = Jetpack::state( $state ) ) {
2888
						$active_state = explode( ',', $active_state );
2889
					} else {
2890
						$active_state = array();
2891
					}
2892
					$active_state[] = $module;
2893
					Jetpack::state( $state, implode( ',', $active_state ) );
2894
				}
2895
				continue;
2896
			}
2897
2898
			$file = Jetpack::get_module_path( $module );
2899
			if ( ! file_exists( $file ) ) {
2900
				continue;
2901
			}
2902
2903
			// we'll override this later if the plugin can be included without fatal error
2904
			if ( $redirect ) {
2905
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2906
			}
2907
2908
			if ( $send_state_messages ) {
2909
				Jetpack::state( 'error', 'module_activation_failed' );
2910
				Jetpack::state( 'module', $module );
2911
			}
2912
2913
			ob_start();
2914
			require_once $file;
2915
2916
			$active[] = $module;
2917
2918 View Code Duplication
			if ( $send_state_messages ) {
2919
2920
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2921
				if ( $active_state = Jetpack::state( $state ) ) {
2922
					$active_state = explode( ',', $active_state );
2923
				} else {
2924
					$active_state = array();
2925
				}
2926
				$active_state[] = $module;
2927
				Jetpack::state( $state, implode( ',', $active_state ) );
2928
			}
2929
2930
			Jetpack::update_active_modules( $active );
2931
2932
			ob_end_clean();
2933
		}
2934
2935
		if ( $send_state_messages ) {
2936
			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...
2937
			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...
2938
		}
2939
2940
		Jetpack::catch_errors( false );
2941
		/**
2942
		 * Fires when default modules are activated.
2943
		 *
2944
		 * @since 1.9.0
2945
		 *
2946
		 * @param string $min_version Minimum version number required to use modules.
2947
		 * @param string $max_version Maximum version number required to use modules.
2948
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2949
		 */
2950
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2951
	}
2952
2953
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2954
		/**
2955
		 * Fires before a module is activated.
2956
		 *
2957
		 * @since 2.6.0
2958
		 *
2959
		 * @param string $module Module slug.
2960
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2961
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2962
		 */
2963
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2964
2965
		$jetpack = Jetpack::init();
2966
2967
		if ( ! strlen( $module ) )
2968
			return false;
2969
2970
		if ( ! Jetpack::is_module( $module ) )
2971
			return false;
2972
2973
		// If it's already active, then don't do it again
2974
		$active = Jetpack::get_active_modules();
2975
		foreach ( $active as $act ) {
2976
			if ( $act == $module )
2977
				return true;
2978
		}
2979
2980
		$module_data = Jetpack::get_module( $module );
2981
2982
		if ( ! Jetpack::is_active() ) {
2983
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2984
				return false;
2985
2986
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2987
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2988
				return false;
2989
		}
2990
2991
		// Check and see if the old plugin is active
2992
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2993
			// Deactivate the old plugin
2994
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2995
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2996
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2997
				Jetpack::state( 'deactivated_plugins', $module );
2998
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2999
				exit;
3000
			}
3001
		}
3002
3003
		// Protect won't work with mis-configured IPs
3004
		if ( 'protect' === $module ) {
3005
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3006
			if ( ! jetpack_protect_get_ip() ) {
3007
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3008
				return false;
3009
			}
3010
		}
3011
3012
		if ( ! Jetpack_Plan::supports( $module ) ) {
3013
			return false;
3014
		}
3015
3016
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3017
		Jetpack::state( 'module', $module );
3018
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3019
3020
		Jetpack::catch_errors( true );
3021
		ob_start();
3022
		require Jetpack::get_module_path( $module );
3023
		/** This action is documented in class.jetpack.php */
3024
		do_action( 'jetpack_activate_module', $module );
3025
		$active[] = $module;
3026
		Jetpack::update_active_modules( $active );
3027
3028
		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...
3029
		ob_end_clean();
3030
		Jetpack::catch_errors( false );
3031
3032
		if ( $redirect ) {
3033
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3034
		}
3035
		if ( $exit ) {
3036
			exit;
3037
		}
3038
		return true;
3039
	}
3040
3041
	function activate_module_actions( $module ) {
3042
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3043
	}
3044
3045
	public static function deactivate_module( $module ) {
3046
		/**
3047
		 * Fires when a module is deactivated.
3048
		 *
3049
		 * @since 1.9.0
3050
		 *
3051
		 * @param string $module Module slug.
3052
		 */
3053
		do_action( 'jetpack_pre_deactivate_module', $module );
3054
3055
		$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...
3056
3057
		$active = Jetpack::get_active_modules();
3058
		$new    = array_filter( array_diff( $active, (array) $module ) );
3059
3060
		return self::update_active_modules( $new );
3061
	}
3062
3063
	public static function enable_module_configurable( $module ) {
3064
		$module = Jetpack::get_module_slug( $module );
3065
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3066
	}
3067
3068
	/**
3069
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3070
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3071
	 *
3072
	 * @param string $module Module slug
3073
	 * @return string $url module configuration URL
3074
	 */
3075
	public static function module_configuration_url( $module ) {
3076
		$module = Jetpack::get_module_slug( $module );
3077
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3078
		/**
3079
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3080
		 *
3081
		 * @since 6.9.0
3082
		 *
3083
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3084
		 */
3085
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3086
3087
		return $url;
3088
	}
3089
3090
/* Installation */
3091
	public static function bail_on_activation( $message, $deactivate = true ) {
3092
?>
3093
<!doctype html>
3094
<html>
3095
<head>
3096
<meta charset="<?php bloginfo( 'charset' ); ?>">
3097
<style>
3098
* {
3099
	text-align: center;
3100
	margin: 0;
3101
	padding: 0;
3102
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3103
}
3104
p {
3105
	margin-top: 1em;
3106
	font-size: 18px;
3107
}
3108
</style>
3109
<body>
3110
<p><?php echo esc_html( $message ); ?></p>
3111
</body>
3112
</html>
3113
<?php
3114
		if ( $deactivate ) {
3115
			$plugins = get_option( 'active_plugins' );
3116
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3117
			$update  = false;
3118
			foreach ( $plugins as $i => $plugin ) {
3119
				if ( $plugin === $jetpack ) {
3120
					$plugins[$i] = false;
3121
					$update = true;
3122
				}
3123
			}
3124
3125
			if ( $update ) {
3126
				update_option( 'active_plugins', array_filter( $plugins ) );
3127
			}
3128
		}
3129
		exit;
3130
	}
3131
3132
	/**
3133
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3134
	 * @static
3135
	 */
3136
	public static function plugin_activation( $network_wide ) {
3137
		Jetpack_Options::update_option( 'activated', 1 );
3138
3139
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3140
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3141
		}
3142
3143
		if ( $network_wide )
3144
			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...
3145
3146
		// For firing one-off events (notices) immediately after activation
3147
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3148
3149
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3150
3151
		Jetpack::plugin_initialize();
3152
	}
3153
3154
	public static function get_activation_source( $referer_url ) {
3155
3156
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3157
			return array( 'wp-cli', null );
3158
		}
3159
3160
		$referer = parse_url( $referer_url );
3161
3162
		$source_type = 'unknown';
3163
		$source_query = null;
3164
3165
		if ( ! is_array( $referer ) ) {
3166
			return array( $source_type, $source_query );
3167
		}
3168
3169
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3170
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3171
3172
		if ( isset( $referer['query'] ) ) {
3173
			parse_str( $referer['query'], $query_parts );
3174
		} else {
3175
			$query_parts = array();
3176
		}
3177
3178
		if ( $plugins_path === $referer['path'] ) {
3179
			$source_type = 'list';
3180
		} elseif ( $plugins_install_path === $referer['path'] ) {
3181
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3182
			switch( $tab ) {
3183
				case 'popular':
3184
					$source_type = 'popular';
3185
					break;
3186
				case 'recommended':
3187
					$source_type = 'recommended';
3188
					break;
3189
				case 'favorites':
3190
					$source_type = 'favorites';
3191
					break;
3192
				case 'search':
3193
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3194
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3195
					break;
3196
				default:
3197
					$source_type = 'featured';
3198
			}
3199
		}
3200
3201
		return array( $source_type, $source_query );
3202
	}
3203
3204
	/**
3205
	 * Runs before bumping version numbers up to a new version
3206
	 * @param  string $version    Version:timestamp
3207
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3208
	 * @return null              [description]
3209
	 */
3210
	public static function do_version_bump( $version, $old_version ) {
3211
		if ( ! $old_version ) { // For new sites
3212
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3213
		}
3214
	}
3215
3216
	/**
3217
	 * Sets the internal version number and activation state.
3218
	 * @static
3219
	 */
3220
	public static function plugin_initialize() {
3221
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3222
			Jetpack_Options::update_option( 'activated', 2 );
3223
		}
3224
3225 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3226
			$version = $old_version = JETPACK__VERSION . ':' . time();
3227
			/** This action is documented in class.jetpack.php */
3228
			do_action( 'updating_jetpack_version', $version, false );
3229
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3230
		}
3231
3232
		Jetpack::load_modules();
3233
3234
		Jetpack_Options::delete_option( 'do_activate' );
3235
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3236
	}
3237
3238
	/**
3239
	 * Removes all connection options
3240
	 * @static
3241
	 */
3242
	public static function plugin_deactivation( ) {
3243
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3244
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3245
			Jetpack_Network::init()->deactivate();
3246
		} else {
3247
			Jetpack::disconnect( false );
3248
			//Jetpack_Heartbeat::init()->deactivate();
3249
		}
3250
	}
3251
3252
	/**
3253
	 * Disconnects from the Jetpack servers.
3254
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3255
	 * @static
3256
	 */
3257
	public static function disconnect( $update_activated_state = true ) {
3258
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3259
		Jetpack::clean_nonces( true );
3260
3261
		// If the site is in an IDC because sync is not allowed,
3262
		// let's make sure to not disconnect the production site.
3263
		if ( ! self::validate_sync_error_idc_option() ) {
3264
			Tracking::record_user_event( 'disconnect_site', array() );
3265
			Jetpack::load_xml_rpc_client();
3266
			$xml = new Jetpack_IXR_Client();
3267
			$xml->query( 'jetpack.deregister' );
3268
		}
3269
3270
		Jetpack_Options::delete_option(
3271
			array(
3272
				'blog_token',
3273
				'user_token',
3274
				'user_tokens',
3275
				'master_user',
3276
				'time_diff',
3277
				'fallback_no_verify_ssl_certs',
3278
			)
3279
		);
3280
3281
		Jetpack_IDC::clear_all_idc_options();
3282
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3283
3284
		if ( $update_activated_state ) {
3285
			Jetpack_Options::update_option( 'activated', 4 );
3286
		}
3287
3288
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3289
			// Check then record unique disconnection if site has never been disconnected previously
3290
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3291
				$jetpack_unique_connection['disconnected'] = 1;
3292
			} else {
3293
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3294
					//track unique disconnect
3295
					$jetpack = Jetpack::init();
3296
3297
					$jetpack->stat( 'connections', 'unique-disconnect' );
3298
					$jetpack->do_stats( 'server_side' );
3299
				}
3300
				// increment number of times disconnected
3301
				$jetpack_unique_connection['disconnected'] += 1;
3302
			}
3303
3304
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3305
		}
3306
3307
		// Delete cached connected user data
3308
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3309
		delete_transient( $transient_key );
3310
3311
		// Delete all the sync related data. Since it could be taking up space.
3312
		Jetpack_Sync_Sender::get_instance()->uninstall();
3313
3314
		// Disable the Heartbeat cron
3315
		Jetpack_Heartbeat::init()->deactivate();
3316
	}
3317
3318
	/**
3319
	 * Unlinks the current user from the linked WordPress.com user
3320
	 */
3321
	public static function unlink_user( $user_id = null ) {
3322
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3323
			return false;
3324
3325
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3326
3327
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3328
			return false;
3329
3330
		if ( ! isset( $tokens[ $user_id ] ) )
3331
			return false;
3332
3333
		Jetpack::load_xml_rpc_client();
3334
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3335
		$xml->query( 'jetpack.unlink_user', $user_id );
3336
3337
		unset( $tokens[ $user_id ] );
3338
3339
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3340
3341
		/**
3342
		 * Fires after the current user has been unlinked from WordPress.com.
3343
		 *
3344
		 * @since 4.1.0
3345
		 *
3346
		 * @param int $user_id The current user's ID.
3347
		 */
3348
		do_action( 'jetpack_unlinked_user', $user_id );
3349
3350
		return true;
3351
	}
3352
3353
	/**
3354
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3355
	 */
3356
	public static function try_registration() {
3357
		// The user has agreed to the TOS at some point by now.
3358
		Jetpack_Options::update_option( 'tos_agreed', true );
3359
3360
		// Let's get some testing in beta versions and such.
3361
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3362
			// Before attempting to connect, let's make sure that the domains are viable.
3363
			$domains_to_check = array_unique( array(
3364
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3365
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3366
			) );
3367
			foreach ( $domains_to_check as $domain ) {
3368
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3367 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

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

Consider the follow example

<?php

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

    return false;
}

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

Loading history...
3369
				if ( is_wp_error( $result ) ) {
3370
					return $result;
3371
				}
3372
			}
3373
		}
3374
3375
		$result = Jetpack::register();
3376
3377
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3378
		if ( ! $result || is_wp_error( $result ) ) {
3379
			return $result;
3380
		} else {
3381
			return true;
3382
		}
3383
	}
3384
3385
	/**
3386
	 * Tracking an internal event log. Try not to put too much chaff in here.
3387
	 *
3388
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3389
	 */
3390
	public static function log( $code, $data = null ) {
3391
		// only grab the latest 200 entries
3392
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3393
3394
		// Append our event to the log
3395
		$log_entry = array(
3396
			'time'    => time(),
3397
			'user_id' => get_current_user_id(),
3398
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3399
			'code'    => $code,
3400
		);
3401
		// Don't bother storing it unless we've got some.
3402
		if ( ! is_null( $data ) ) {
3403
			$log_entry['data'] = $data;
3404
		}
3405
		$log[] = $log_entry;
3406
3407
		// Try add_option first, to make sure it's not autoloaded.
3408
		// @todo: Add an add_option method to Jetpack_Options
3409
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3410
			Jetpack_Options::update_option( 'log', $log );
3411
		}
3412
3413
		/**
3414
		 * Fires when Jetpack logs an internal event.
3415
		 *
3416
		 * @since 3.0.0
3417
		 *
3418
		 * @param array $log_entry {
3419
		 *	Array of details about the log entry.
3420
		 *
3421
		 *	@param string time Time of the event.
3422
		 *	@param int user_id ID of the user who trigerred the event.
3423
		 *	@param int blog_id Jetpack Blog ID.
3424
		 *	@param string code Unique name for the event.
3425
		 *	@param string data Data about the event.
3426
		 * }
3427
		 */
3428
		do_action( 'jetpack_log_entry', $log_entry );
3429
	}
3430
3431
	/**
3432
	 * Get the internal event log.
3433
	 *
3434
	 * @param $event (string) - only return the specific log events
3435
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3436
	 *
3437
	 * @return array of log events || WP_Error for invalid params
3438
	 */
3439
	public static function get_log( $event = false, $num = false ) {
3440
		if ( $event && ! is_string( $event ) ) {
3441
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3442
		}
3443
3444
		if ( $num && ! is_numeric( $num ) ) {
3445
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3446
		}
3447
3448
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3449
3450
		// If nothing set - act as it did before, otherwise let's start customizing the output
3451
		if ( ! $num && ! $event ) {
3452
			return $entire_log;
3453
		} else {
3454
			$entire_log = array_reverse( $entire_log );
3455
		}
3456
3457
		$custom_log_output = array();
3458
3459
		if ( $event ) {
3460
			foreach ( $entire_log as $log_event ) {
3461
				if ( $event == $log_event[ 'code' ] ) {
3462
					$custom_log_output[] = $log_event;
3463
				}
3464
			}
3465
		} else {
3466
			$custom_log_output = $entire_log;
3467
		}
3468
3469
		if ( $num ) {
3470
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3471
		}
3472
3473
		return $custom_log_output;
3474
	}
3475
3476
	/**
3477
	 * Log modification of important settings.
3478
	 */
3479
	public static function log_settings_change( $option, $old_value, $value ) {
3480
		switch( $option ) {
3481
			case 'jetpack_sync_non_public_post_stati':
3482
				self::log( $option, $value );
3483
				break;
3484
		}
3485
	}
3486
3487
	/**
3488
	 * Return stat data for WPCOM sync
3489
	 */
3490
	public static function get_stat_data( $encode = true, $extended = true ) {
3491
		$data = Jetpack_Heartbeat::generate_stats_array();
3492
3493
		if ( $extended ) {
3494
			$additional_data = self::get_additional_stat_data();
3495
			$data = array_merge( $data, $additional_data );
3496
		}
3497
3498
		if ( $encode ) {
3499
			return json_encode( $data );
3500
		}
3501
3502
		return $data;
3503
	}
3504
3505
	/**
3506
	 * Get additional stat data to sync to WPCOM
3507
	 */
3508
	public static function get_additional_stat_data( $prefix = '' ) {
3509
		$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...
3510
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3511
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3512
		$return["{$prefix}site-count"]     = 0;
3513
3514
		if ( function_exists( 'get_blog_count' ) ) {
3515
			$return["{$prefix}site-count"] = get_blog_count();
3516
		}
3517
		return $return;
3518
	}
3519
3520
	private static function get_site_user_count() {
3521
		global $wpdb;
3522
3523
		if ( function_exists( 'wp_is_large_network' ) ) {
3524
			if ( wp_is_large_network( 'users' ) ) {
3525
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3526
			}
3527
		}
3528 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3529
			// It wasn't there, so regenerate the data and save the transient
3530
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3531
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3532
		}
3533
		return $user_count;
3534
	}
3535
3536
	/* Admin Pages */
3537
3538
	function admin_init() {
3539
		// If the plugin is not connected, display a connect message.
3540
		if (
3541
			// the plugin was auto-activated and needs its candy
3542
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3543
		||
3544
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3545
			! Jetpack_Options::get_option( 'activated' )
3546
		) {
3547
			Jetpack::plugin_initialize();
3548
		}
3549
3550
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3551
			Jetpack_Connection_Banner::init();
3552
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3553
			// Upgrade: 1.1 -> 1.1.1
3554
			// Check and see if host can verify the Jetpack servers' SSL certificate
3555
			$args = array();
3556
			Jetpack_Client::_wp_remote_request(
3557
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3558
				$args,
3559
				true
3560
			);
3561
		}
3562
3563
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3564
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3565
		}
3566
3567
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3568
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3569
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3570
3571
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3572
			// Artificially throw errors in certain whitelisted cases during plugin activation
3573
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3574
		}
3575
3576
		// Add custom column in wp-admin/users.php to show whether user is linked.
3577
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3578
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3579
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3580
	}
3581
3582
	function admin_body_class( $admin_body_class = '' ) {
3583
		$classes = explode( ' ', trim( $admin_body_class ) );
3584
3585
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3586
3587
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3588
		return " $admin_body_class ";
3589
	}
3590
3591
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3592
		return $admin_body_class . ' jetpack-pagestyles ';
3593
	}
3594
3595
	/**
3596
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3597
	 * This function artificially throws errors for such cases (whitelisted).
3598
	 *
3599
	 * @param string $plugin The activated plugin.
3600
	 */
3601
	function throw_error_on_activate_plugin( $plugin ) {
3602
		$active_modules = Jetpack::get_active_modules();
3603
3604
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3605
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3606
			$throw = false;
3607
3608
			// Try and make sure it really was the stats plugin
3609
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3610
				if ( 'stats.php' == basename( $plugin ) ) {
3611
					$throw = true;
3612
				}
3613
			} else {
3614
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3615
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3616
					$throw = true;
3617
				}
3618
			}
3619
3620
			if ( $throw ) {
3621
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3622
			}
3623
		}
3624
	}
3625
3626
	function intercept_plugin_error_scrape_init() {
3627
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3628
	}
3629
3630
	function intercept_plugin_error_scrape( $action, $result ) {
3631
		if ( ! $result ) {
3632
			return;
3633
		}
3634
3635
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3636
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3637
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3638
			}
3639
		}
3640
	}
3641
3642
	function add_remote_request_handlers() {
3643
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3644
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3645
	}
3646
3647
	function remote_request_handlers() {
3648
		$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...
3649
3650
		switch ( current_filter() ) {
3651
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3652
			$response = $this->upload_handler();
3653
			break;
3654
3655
		case 'wp_ajax_nopriv_jetpack_update_file' :
3656
			$response = $this->upload_handler( true );
3657
			break;
3658
		default :
3659
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3660
			break;
3661
		}
3662
3663
		if ( ! $response ) {
3664
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3665
		}
3666
3667
		if ( is_wp_error( $response ) ) {
3668
			$status_code       = $response->get_error_data();
3669
			$error             = $response->get_error_code();
3670
			$error_description = $response->get_error_message();
3671
3672
			if ( ! is_int( $status_code ) ) {
3673
				$status_code = 400;
3674
			}
3675
3676
			status_header( $status_code );
3677
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3678
		}
3679
3680
		status_header( 200 );
3681
		if ( true === $response ) {
3682
			exit;
3683
		}
3684
3685
		die( json_encode( (object) $response ) );
3686
	}
3687
3688
	/**
3689
	 * Uploads a file gotten from the global $_FILES.
3690
	 * If `$update_media_item` is true and `post_id` is defined
3691
	 * the attachment file of the media item (gotten through of the post_id)
3692
	 * will be updated instead of add a new one.
3693
	 *
3694
	 * @param  boolean $update_media_item - update media attachment
3695
	 * @return array - An array describing the uploadind files process
3696
	 */
3697
	function upload_handler( $update_media_item = false ) {
3698
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3699
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3700
		}
3701
3702
		$user = wp_authenticate( '', '' );
3703
		if ( ! $user || is_wp_error( $user ) ) {
3704
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3705
		}
3706
3707
		wp_set_current_user( $user->ID );
3708
3709
		if ( ! current_user_can( 'upload_files' ) ) {
3710
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3711
		}
3712
3713
		if ( empty( $_FILES ) ) {
3714
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3715
		}
3716
3717
		foreach ( array_keys( $_FILES ) as $files_key ) {
3718
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3719
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3720
			}
3721
		}
3722
3723
		$media_keys = array_keys( $_FILES['media'] );
3724
3725
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
3726
		if ( ! $token || is_wp_error( $token ) ) {
3727
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3728
		}
3729
3730
		$uploaded_files = array();
3731
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3732
		unset( $GLOBALS['post'] );
3733
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3734
			$file = array();
3735
			foreach ( $media_keys as $media_key ) {
3736
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3737
			}
3738
3739
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3740
3741
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3742
			if ( $hmac_provided !== $hmac_file ) {
3743
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3744
				continue;
3745
			}
3746
3747
			$_FILES['.jetpack.upload.'] = $file;
3748
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3749
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3750
				$post_id = 0;
3751
			}
3752
3753
			if ( $update_media_item ) {
3754
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3755
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3756
				}
3757
3758
				$media_array = $_FILES['media'];
3759
3760
				$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...
3761
				$file_array['type'] = $media_array['type'][0];
3762
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3763
				$file_array['error'] = $media_array['error'][0];
3764
				$file_array['size'] = $media_array['size'][0];
3765
3766
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3767
3768
				if ( is_wp_error( $edited_media_item ) ) {
3769
					return $edited_media_item;
3770
				}
3771
3772
				$response = (object) array(
3773
					'id'   => (string) $post_id,
3774
					'file' => (string) $edited_media_item->post_title,
3775
					'url'  => (string) wp_get_attachment_url( $post_id ),
3776
					'type' => (string) $edited_media_item->post_mime_type,
3777
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3778
				);
3779
3780
				return (array) array( $response );
3781
			}
3782
3783
			$attachment_id = media_handle_upload(
3784
				'.jetpack.upload.',
3785
				$post_id,
3786
				array(),
3787
				array(
3788
					'action' => 'jetpack_upload_file',
3789
				)
3790
			);
3791
3792
			if ( ! $attachment_id ) {
3793
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3794
			} elseif ( is_wp_error( $attachment_id ) ) {
3795
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3796
			} else {
3797
				$attachment = get_post( $attachment_id );
3798
				$uploaded_files[$index] = (object) array(
3799
					'id'   => (string) $attachment_id,
3800
					'file' => $attachment->post_title,
3801
					'url'  => wp_get_attachment_url( $attachment_id ),
3802
					'type' => $attachment->post_mime_type,
3803
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3804
				);
3805
				// Zip files uploads are not supported unless they are done for installation purposed
3806
				// lets delete them in case something goes wrong in this whole process
3807
				if ( 'application/zip' === $attachment->post_mime_type ) {
3808
					// Schedule a cleanup for 2 hours from now in case of failed install.
3809
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3810
				}
3811
			}
3812
		}
3813
		if ( ! is_null( $global_post ) ) {
3814
			$GLOBALS['post'] = $global_post;
3815
		}
3816
3817
		return $uploaded_files;
3818
	}
3819
3820
	/**
3821
	 * Add help to the Jetpack page
3822
	 *
3823
	 * @since Jetpack (1.2.3)
3824
	 * @return false if not the Jetpack page
3825
	 */
3826
	function admin_help() {
3827
		$current_screen = get_current_screen();
3828
3829
		// Overview
3830
		$current_screen->add_help_tab(
3831
			array(
3832
				'id'		=> 'home',
3833
				'title'		=> __( 'Home', 'jetpack' ),
3834
				'content'	=>
3835
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3836
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3837
					'<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>',
3838
			)
3839
		);
3840
3841
		// Screen Content
3842
		if ( current_user_can( 'manage_options' ) ) {
3843
			$current_screen->add_help_tab(
3844
				array(
3845
					'id'		=> 'settings',
3846
					'title'		=> __( 'Settings', 'jetpack' ),
3847
					'content'	=>
3848
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3849
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3850
						'<ol>' .
3851
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3852
							'<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>' .
3853
						'</ol>' .
3854
						'<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>'
3855
				)
3856
			);
3857
		}
3858
3859
		// Help Sidebar
3860
		$current_screen->set_help_sidebar(
3861
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3862
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3863
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3864
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3865
		);
3866
	}
3867
3868
	function admin_menu_css() {
3869
		wp_enqueue_style( 'jetpack-icons' );
3870
	}
3871
3872
	function admin_menu_order() {
3873
		return true;
3874
	}
3875
3876 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3877
		$jp_menu_order = array();
3878
3879
		foreach ( $menu_order as $index => $item ) {
3880
			if ( $item != 'jetpack' ) {
3881
				$jp_menu_order[] = $item;
3882
			}
3883
3884
			if ( $index == 0 ) {
3885
				$jp_menu_order[] = 'jetpack';
3886
			}
3887
		}
3888
3889
		return $jp_menu_order;
3890
	}
3891
3892
	function admin_banner_styles() {
3893
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3894
3895
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3896
			wp_register_style(
3897
				'jetpack-dops-style',
3898
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3899
				array(),
3900
				JETPACK__VERSION
3901
			);
3902
		}
3903
3904
		wp_enqueue_style(
3905
			'jetpack',
3906
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3907
			array( 'jetpack-dops-style' ),
3908
			 JETPACK__VERSION . '-20121016'
3909
		);
3910
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3911
		wp_style_add_data( 'jetpack', 'suffix', $min );
3912
	}
3913
3914
	function plugin_action_links( $actions ) {
3915
3916
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3917
3918
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3919
			return array_merge(
3920
				$jetpack_home,
3921
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3922
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3923
				$actions
3924
				);
3925
			}
3926
3927
		return array_merge( $jetpack_home, $actions );
3928
	}
3929
3930
	/*
3931
	 * Registration flow:
3932
	 * 1 - ::admin_page_load() action=register
3933
	 * 2 - ::try_registration()
3934
	 * 3 - ::register()
3935
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3936
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3937
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3938
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3939
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3940
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3941
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3942
	 *       jetpack_id, jetpack_secret, jetpack_public
3943
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3944
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3945
	 * 5 - user logs in with WP.com account
3946
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3947
	 *		- Jetpack_Client_Server::authorize()
3948
	 *		- Jetpack_Client_Server::get_token()
3949
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3950
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3951
	 *			- which responds with access_token, token_type, scope
3952
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3953
	 *		- Jetpack::activate_default_modules()
3954
	 *     		- Deactivates deprecated plugins
3955
	 *     		- Activates all default modules
3956
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3957
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3958
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3959
	 *     Done!
3960
	 */
3961
3962
	/**
3963
	 * Handles the page load events for the Jetpack admin page
3964
	 */
3965
	function admin_page_load() {
3966
		$error = false;
3967
3968
		// Make sure we have the right body class to hook stylings for subpages off of.
3969
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3970
3971
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3972
			// Should only be used in intermediate redirects to preserve state across redirects
3973
			Jetpack::restate();
3974
		}
3975
3976
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3977
			// @todo: Add validation against a known whitelist
3978
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3979
			// User clicked in the iframe to link their accounts
3980
			if ( ! Jetpack::is_user_connected() ) {
3981
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3982
3983
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3984
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3985
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3986
3987
				if ( isset( $_GET['notes_iframe'] ) )
3988
					$connect_url .= '&notes_iframe';
3989
				wp_redirect( $connect_url );
3990
				exit;
3991
			} else {
3992
				if ( ! isset( $_GET['calypso_env'] ) ) {
3993
					Jetpack::state( 'message', 'already_authorized' );
3994
					wp_safe_redirect( Jetpack::admin_url() );
3995
					exit;
3996
				} else {
3997
					$connect_url = $this->build_connect_url( true, false, $from );
3998
					$connect_url .= '&already_authorized=true';
3999
					wp_redirect( $connect_url );
4000
					exit;
4001
				}
4002
			}
4003
		}
4004
4005
4006
		if ( isset( $_GET['action'] ) ) {
4007
			switch ( $_GET['action'] ) {
4008
			case 'authorize':
4009
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4010
					Jetpack::state( 'message', 'already_authorized' );
4011
					wp_safe_redirect( Jetpack::admin_url() );
4012
					exit;
4013
				}
4014
				Jetpack::log( 'authorize' );
4015
				$client_server = new Jetpack_Client_Server;
4016
				$client_server->client_authorize();
4017
				exit;
4018
			case 'register' :
4019
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4020
					$error = 'cheatin';
4021
					break;
4022
				}
4023
				check_admin_referer( 'jetpack-register' );
4024
				Jetpack::log( 'register' );
4025
				Jetpack::maybe_set_version_option();
4026
				$registered = Jetpack::try_registration();
4027
				if ( is_wp_error( $registered ) ) {
4028
					$error = $registered->get_error_code();
4029
					Jetpack::state( 'error', $error );
4030
					Jetpack::state( 'error', $registered->get_error_message() );
4031
					Tracking::record_user_event( 'jpc_register_fail', array(
4032
						'error_code' => $error,
4033
						'error_message' => $registered->get_error_message()
4034
					) );
4035
					break;
4036
				}
4037
4038
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4039
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4040
4041
				Tracking::record_user_event( 'jpc_register_success', array(
4042
					'from' => $from
4043
				) );
4044
4045
				$url = $this->build_connect_url( true, $redirect, $from );
4046
4047
				if ( ! empty( $_GET['onboarding'] ) ) {
4048
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4049
				}
4050
4051
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4052
					$url = add_query_arg( 'auth_approved', 'true', $url );
4053
				}
4054
4055
				wp_redirect( $url );
4056
				exit;
4057
			case 'activate' :
4058
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4059
					$error = 'cheatin';
4060
					break;
4061
				}
4062
4063
				$module = stripslashes( $_GET['module'] );
4064
				check_admin_referer( "jetpack_activate-$module" );
4065
				Jetpack::log( 'activate', $module );
4066
				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...
4067
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4068
				}
4069
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4070
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4071
				exit;
4072
			case 'activate_default_modules' :
4073
				check_admin_referer( 'activate_default_modules' );
4074
				Jetpack::log( 'activate_default_modules' );
4075
				Jetpack::restate();
4076
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4077
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4078
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4079
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4080
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4081
				exit;
4082
			case 'disconnect' :
4083
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4084
					$error = 'cheatin';
4085
					break;
4086
				}
4087
4088
				check_admin_referer( 'jetpack-disconnect' );
4089
				Jetpack::log( 'disconnect' );
4090
				Jetpack::disconnect();
4091
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4092
				exit;
4093
			case 'reconnect' :
4094
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4095
					$error = 'cheatin';
4096
					break;
4097
				}
4098
4099
				check_admin_referer( 'jetpack-reconnect' );
4100
				Jetpack::log( 'reconnect' );
4101
				$this->disconnect();
4102
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4103
				exit;
4104 View Code Duplication
			case 'deactivate' :
4105
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4106
					$error = 'cheatin';
4107
					break;
4108
				}
4109
4110
				$modules = stripslashes( $_GET['module'] );
4111
				check_admin_referer( "jetpack_deactivate-$modules" );
4112
				foreach ( explode( ',', $modules ) as $module ) {
4113
					Jetpack::log( 'deactivate', $module );
4114
					Jetpack::deactivate_module( $module );
4115
					Jetpack::state( 'message', 'module_deactivated' );
4116
				}
4117
				Jetpack::state( 'module', $modules );
4118
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4119
				exit;
4120
			case 'unlink' :
4121
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4122
				check_admin_referer( 'jetpack-unlink' );
4123
				Jetpack::log( 'unlink' );
4124
				$this->unlink_user();
4125
				Jetpack::state( 'message', 'unlinked' );
4126
				if ( 'sub-unlink' == $redirect ) {
4127
					wp_safe_redirect( admin_url() );
4128
				} else {
4129
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4130
				}
4131
				exit;
4132
			case 'onboard' :
4133
				if ( ! current_user_can( 'manage_options' ) ) {
4134
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4135
				} else {
4136
					Jetpack::create_onboarding_token();
4137
					$url = $this->build_connect_url( true );
4138
4139
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4140
						$url = add_query_arg( 'onboarding', $token, $url );
4141
					}
4142
4143
					$calypso_env = $this->get_calypso_env();
4144
					if ( ! empty( $calypso_env ) ) {
4145
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4146
					}
4147
4148
					wp_redirect( $url );
4149
					exit;
4150
				}
4151
				exit;
4152
			default:
4153
				/**
4154
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4155
				 *
4156
				 * @since 2.6.0
4157
				 *
4158
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4159
				 */
4160
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4161
			}
4162
		}
4163
4164
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4165
			self::activate_new_modules( true );
4166
		}
4167
4168
		$message_code = Jetpack::state( 'message' );
4169
		if ( Jetpack::state( 'optin-manage' ) ) {
4170
			$activated_manage = $message_code;
4171
			$message_code = 'jetpack-manage';
4172
		}
4173
4174
		switch ( $message_code ) {
4175
		case 'jetpack-manage':
4176
			$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>';
4177
			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...
4178
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4179
			}
4180
			break;
4181
4182
		}
4183
4184
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4185
4186
		if ( ! empty( $deactivated_plugins ) ) {
4187
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4188
			$deactivated_titles  = array();
4189
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4190
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4191
					continue;
4192
				}
4193
4194
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4195
			}
4196
4197
			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...
4198
				if ( $this->message ) {
4199
					$this->message .= "<br /><br />\n";
4200
				}
4201
4202
				$this->message .= wp_sprintf(
4203
					_n(
4204
						'Jetpack contains the most recent version of the old %l plugin.',
4205
						'Jetpack contains the most recent versions of the old %l plugins.',
4206
						count( $deactivated_titles ),
4207
						'jetpack'
4208
					),
4209
					$deactivated_titles
4210
				);
4211
4212
				$this->message .= "<br />\n";
4213
4214
				$this->message .= _n(
4215
					'The old version has been deactivated and can be removed from your site.',
4216
					'The old versions have been deactivated and can be removed from your site.',
4217
					count( $deactivated_titles ),
4218
					'jetpack'
4219
				);
4220
			}
4221
		}
4222
4223
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4224
4225
		if ( $this->message || $this->error || $this->privacy_checks ) {
4226
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4227
		}
4228
4229
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4230
	}
4231
4232
	function admin_notices() {
4233
4234
		if ( $this->error ) {
4235
?>
4236
<div id="message" class="jetpack-message jetpack-err">
4237
	<div class="squeezer">
4238
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4239
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4240
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4241
<?php	endif; ?>
4242
	</div>
4243
</div>
4244
<?php
4245
		}
4246
4247
		if ( $this->message ) {
4248
?>
4249
<div id="message" class="jetpack-message">
4250
	<div class="squeezer">
4251
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4252
	</div>
4253
</div>
4254
<?php
4255
		}
4256
4257
		if ( $this->privacy_checks ) :
4258
			$module_names = $module_slugs = array();
4259
4260
			$privacy_checks = explode( ',', $this->privacy_checks );
4261
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4262
			foreach ( $privacy_checks as $module_slug ) {
4263
				$module = Jetpack::get_module( $module_slug );
4264
				if ( ! $module ) {
4265
					continue;
4266
				}
4267
4268
				$module_slugs[] = $module_slug;
4269
				$module_names[] = "<strong>{$module['name']}</strong>";
4270
			}
4271
4272
			$module_slugs = join( ',', $module_slugs );
4273
?>
4274
<div id="message" class="jetpack-message jetpack-err">
4275
	<div class="squeezer">
4276
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4277
		<p><?php
4278
			echo wp_kses(
4279
				wptexturize(
4280
					wp_sprintf(
4281
						_nx(
4282
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4283
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4284
							count( $privacy_checks ),
4285
							'%l = list of Jetpack module/feature names',
4286
							'jetpack'
4287
						),
4288
						$module_names
4289
					)
4290
				),
4291
				array( 'strong' => true )
4292
			);
4293
4294
			echo "\n<br />\n";
4295
4296
			echo wp_kses(
4297
				sprintf(
4298
					_nx(
4299
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4300
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4301
						count( $privacy_checks ),
4302
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4303
						'jetpack'
4304
					),
4305
					wp_nonce_url(
4306
						Jetpack::admin_url(
4307
							array(
4308
								'page'   => 'jetpack',
4309
								'action' => 'deactivate',
4310
								'module' => urlencode( $module_slugs ),
4311
							)
4312
						),
4313
						"jetpack_deactivate-$module_slugs"
4314
					),
4315
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4316
				),
4317
				array( 'a' => array( 'href' => true, 'title' => true ) )
4318
			);
4319
		?></p>
4320
	</div>
4321
</div>
4322
<?php endif;
4323
	}
4324
4325
	/**
4326
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4327
	 */
4328
	function stat( $group, $detail ) {
4329
		if ( ! isset( $this->stats[ $group ] ) )
4330
			$this->stats[ $group ] = array();
4331
		$this->stats[ $group ][] = $detail;
4332
	}
4333
4334
	/**
4335
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4336
	 */
4337
	function do_stats( $method = '' ) {
4338
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4339
			foreach ( $this->stats as $group => $stats ) {
4340
				if ( is_array( $stats ) && count( $stats ) ) {
4341
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4342
					if ( 'server_side' === $method ) {
4343
						self::do_server_side_stat( $args );
4344
					} else {
4345
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4346
					}
4347
				}
4348
				unset( $this->stats[ $group ] );
4349
			}
4350
		}
4351
	}
4352
4353
	/**
4354
	 * Runs stats code for a one-off, server-side.
4355
	 *
4356
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4357
	 *
4358
	 * @return bool If it worked.
4359
	 */
4360
	static function do_server_side_stat( $args ) {
4361
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4362
		if ( is_wp_error( $response ) )
4363
			return false;
4364
4365
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4366
			return false;
4367
4368
		return true;
4369
	}
4370
4371
	/**
4372
	 * Builds the stats url.
4373
	 *
4374
	 * @param $args array|string The arguments to append to the URL.
4375
	 *
4376
	 * @return string The URL to be pinged.
4377
	 */
4378
	static function build_stats_url( $args ) {
4379
		$defaults = array(
4380
			'v'    => 'wpcom2',
4381
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4382
		);
4383
		$args     = wp_parse_args( $args, $defaults );
4384
		/**
4385
		 * Filter the URL used as the Stats tracking pixel.
4386
		 *
4387
		 * @since 2.3.2
4388
		 *
4389
		 * @param string $url Base URL used as the Stats tracking pixel.
4390
		 */
4391
		$base_url = apply_filters(
4392
			'jetpack_stats_base_url',
4393
			'https://pixel.wp.com/g.gif'
4394
		);
4395
		$url      = add_query_arg( $args, $base_url );
4396
		return $url;
4397
	}
4398
4399
	static function translate_current_user_to_role() {
4400
		foreach ( self::$capability_translations as $role => $cap ) {
4401
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4402
				return $role;
4403
			}
4404
		}
4405
4406
		return false;
4407
	}
4408
4409
	static function translate_user_to_role( $user ) {
4410
		foreach ( self::$capability_translations as $role => $cap ) {
4411
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4412
				return $role;
4413
			}
4414
		}
4415
4416
		return false;
4417
    }
4418
4419
	static function translate_role_to_cap( $role ) {
4420
		if ( ! isset( self::$capability_translations[$role] ) ) {
4421
			return false;
4422
		}
4423
4424
		return self::$capability_translations[$role];
4425
	}
4426
4427
	static function sign_role( $role, $user_id = null ) {
4428
		if ( empty( $user_id ) ) {
4429
			$user_id = (int) get_current_user_id();
4430
		}
4431
4432
		if ( ! $user_id  ) {
4433
			return false;
4434
		}
4435
4436
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
4437
		if ( ! $token || is_wp_error( $token ) ) {
4438
			return false;
4439
		}
4440
4441
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4442
	}
4443
4444
4445
	/**
4446
	 * Builds a URL to the Jetpack connection auth page
4447
	 *
4448
	 * @since 3.9.5
4449
	 *
4450
	 * @param bool $raw If true, URL will not be escaped.
4451
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4452
	 *                              If string, will be a custom redirect.
4453
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4454
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4455
	 *
4456
	 * @return string Connect URL
4457
	 */
4458
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4459
		$site_id = Jetpack_Options::get_option( 'id' );
4460
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

Loading history...
5224 View Code Duplication
		if ( ! $token ) {
5225
			$this->xmlrpc_verification = new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
5226
			return $this->xmlrpc_verification;
5227
		}
5228
5229
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5230
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5231
			$post_data   = $_POST;
5232
			$file_hashes = array();
5233
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5234
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5235
					continue;
5236
				}
5237
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5238
				$file_hashes[$post_data_key] = $post_data_value;
5239
			}
5240
5241
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5242
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5243
				$post_data[$post_data_key] = $post_data_value;
5244
			}
5245
5246
			ksort( $post_data );
5247
5248
			$body = http_build_query( stripslashes_deep( $post_data ) );
5249
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5250
			$body = file_get_contents( 'php://input' );
5251
		} else {
5252
			$body = null;
5253
		}
5254
5255
		$signature = $jetpack_signature->sign_current_request(
5256
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5257
		);
5258
5259
		$signature_details['url'] = $signature->current_request_url;
5260
5261
		if ( ! $signature ) {
5262
			$this->xmlrpc_verification = new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
5263
			return $this->xmlrpc_verification;
5264
		} else if ( is_wp_error( $signature ) ) {
5265
			$this->xmlrpc_verification = $signature;
5266
			return $signature;
5267 View Code Duplication
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5268
			$this->xmlrpc_verification = new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
5269
			return $this->xmlrpc_verification;
5270
		}
5271
5272
		$timestamp = (int) $_GET['timestamp'];
5273
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5274
5275
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5276
			$this->xmlrpc_verification = new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
5277
			return $this->xmlrpc_verification;
5278
		}
5279
5280
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5281
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5282
			if ( ! empty( $_GET['onboarding'] ) ) {
5283
				$jpo = $_GET;
5284
			} else {
5285
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5286
			}
5287
5288
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5289
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5290
5291
			if (
5292
				isset( $jpo_user ) && isset( $jpo_token ) &&
5293
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5294
				isset( $_GET['rest_route'] ) &&
5295
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5296
			) {
5297
				$jpUser = get_user_by( 'email', $jpo_user );
5298
				if ( is_a( $jpUser, 'WP_User' ) ) {
5299
					wp_set_current_user( $jpUser->ID );
5300
					$user_can = is_multisite()
5301
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5302
						: current_user_can( 'manage_options' );
5303
					if ( $user_can ) {
5304
						$token_type = 'user';
5305
						$token->external_user_id = $jpUser->ID;
5306
					}
5307
				}
5308
			}
5309
		}
5310
5311
		$this->xmlrpc_verification = array(
5312
			'type'      => $token_type,
5313
			'token_key' => $token_key,
5314
			'user_id'   => $token->external_user_id,
5315
		);
5316
5317
		return $this->xmlrpc_verification;
5318
	}
5319
5320
	/**
5321
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5322
	 */
5323
	function authenticate_jetpack( $user, $username, $password ) {
5324
		if ( is_a( $user, 'WP_User' ) ) {
5325
			return $user;
5326
		}
5327
5328
		$token_details = $this->verify_xml_rpc_signature();
5329
5330
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5331
			return $user;
5332
		}
5333
5334
		if ( 'user' !== $token_details['type'] ) {
5335
			return $user;
5336
		}
5337
5338
		if ( ! $token_details['user_id'] ) {
5339
			return $user;
5340
		}
5341
5342
		nocache_headers();
5343
5344
		return new WP_User( $token_details['user_id'] );
5345
	}
5346
5347
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5348
	// Uses the existing XMLRPC request signing implementation.
5349
	function wp_rest_authenticate( $user ) {
5350
		if ( ! empty( $user ) ) {
5351
			// Another authentication method is in effect.
5352
			return $user;
5353
		}
5354
5355
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5356
			// Nothing to do for this authentication method.
5357
			return null;
5358
		}
5359
5360
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5361
			// Nothing to do for this authentication method.
5362
			return null;
5363
		}
5364
5365
		// Ensure that we always have the request body available.  At this
5366
		// point, the WP REST API code to determine the request body has not
5367
		// run yet.  That code may try to read from 'php://input' later, but
5368
		// this can only be done once per request in PHP versions prior to 5.6.
5369
		// So we will go ahead and perform this read now if needed, and save
5370
		// the request body where both the Jetpack signature verification code
5371
		// and the WP REST API code can see it.
5372
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5373
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5374
		}
5375
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5376
5377
		// Only support specific request parameters that have been tested and
5378
		// are known to work with signature verification.  A different method
5379
		// can be passed to the WP REST API via the '?_method=' parameter if
5380
		// needed.
5381
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5382
			$this->rest_authentication_status = new WP_Error(
5383
				'rest_invalid_request',
5384
				__( 'This request method is not supported.', 'jetpack' ),
5385
				array( 'status' => 400 )
5386
			);
5387
			return null;
5388
		}
5389
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5390
			$this->rest_authentication_status = new WP_Error(
5391
				'rest_invalid_request',
5392
				__( 'This request method does not support body parameters.', 'jetpack' ),
5393
				array( 'status' => 400 )
5394
			);
5395
			return null;
5396
		}
5397
5398
		$verified = $this->verify_xml_rpc_signature();
5399
5400
		if ( is_wp_error( $verified ) ) {
5401
			$this->rest_authentication_status = $verified;
5402
			return null;
5403
		}
5404
5405
		if (
5406
			$verified &&
5407
			isset( $verified['type'] ) &&
5408
			'user' === $verified['type'] &&
5409
			! empty( $verified['user_id'] )
5410
		) {
5411
			// Authentication successful.
5412
			$this->rest_authentication_status = true;
5413
			return $verified['user_id'];
5414
		}
5415
5416
		// Something else went wrong.  Probably a signature error.
5417
		$this->rest_authentication_status = new WP_Error(
5418
			'rest_invalid_signature',
5419
			__( 'The request is not signed correctly.', 'jetpack' ),
5420
			array( 'status' => 400 )
5421
		);
5422
		return null;
5423
	}
5424
5425
	protected function send_signature_error_header( $error ) {
5426
		$error_data = $error->get_error_data();
5427
		if ( ! isset( $error_data['signature_details'] ) ) {
5428
			return;
5429
		}
5430
5431
		header( sprintf(
5432
			'X-Jetpack-Signature-Error: %s',
5433
			base64_encode( json_encode( $error_data['signature_details'] ) )
5434
		) );
5435
	}
5436
5437
	/**
5438
	 * Report authentication status to the WP REST API.
5439
	 *
5440
	 * @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...
5441
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5442
	 */
5443
	public function wp_rest_authentication_errors( $value ) {
5444
		if ( $value !== null ) {
5445
			return $value;
5446
		}
5447
5448
		if ( is_wp_error( $this->rest_authentication_status ) ) {
5449
			$error_data = $this->rest_authentication_status->get_error_data();
5450
			if ( ! isset( $error_data['signature_details'] ) ) {
5451
				return $this->rest_authentication_status;
5452
			}
5453
5454
			$this->send_signature_error_header( $this->rest_authentication_status );
5455
5456
			unset( $error_data['signature_details'] );
5457
5458
			return new WP_Error(
5459
				$this->rest_authentication_status->get_error_code(),
5460
				$this->rest_authentication_status->get_error_message(),
5461
				$error_data
5462
			);
5463
5464
		}
5465
		return $this->rest_authentication_status;
5466
	}
5467
5468
	function add_nonce( $timestamp, $nonce ) {
5469
		global $wpdb;
5470
		static $nonces_used_this_request = array();
5471
5472
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5473
			return $nonces_used_this_request["$timestamp:$nonce"];
5474
		}
5475
5476
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5477
		$timestamp = (int) $timestamp;
5478
		$nonce     = esc_sql( $nonce );
5479
5480
		// Raw query so we can avoid races: add_option will also update
5481
		$show_errors = $wpdb->show_errors( false );
5482
5483
		$old_nonce = $wpdb->get_row(
5484
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5485
		);
5486
5487
		if ( is_null( $old_nonce ) ) {
5488
			$return = $wpdb->query(
5489
				$wpdb->prepare(
5490
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5491
					"jetpack_nonce_{$timestamp}_{$nonce}",
5492
					time(),
5493
					'no'
5494
				)
5495
			);
5496
		} else {
5497
			$return = false;
5498
		}
5499
5500
		$wpdb->show_errors( $show_errors );
5501
5502
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5503
5504
		return $return;
5505
	}
5506
5507
	/**
5508
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5509
	 * Capture it here so we can verify the signature later.
5510
	 */
5511
	function xmlrpc_methods( $methods ) {
5512
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5513
		return $methods;
5514
	}
5515
5516
	function public_xmlrpc_methods( $methods ) {
5517
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5518
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5519
		}
5520
		return $methods;
5521
	}
5522
5523
	function jetpack_getOptions( $args ) {
5524
		global $wp_xmlrpc_server;
5525
5526
		$wp_xmlrpc_server->escape( $args );
5527
5528
		$username	= $args[1];
5529
		$password	= $args[2];
5530
5531
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5532
			return $wp_xmlrpc_server->error;
5533
		}
5534
5535
		$options = array();
5536
		$user_data = $this->get_connected_user_data();
5537
		if ( is_array( $user_data ) ) {
5538
			$options['jetpack_user_id'] = array(
5539
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5540
				'readonly'      => true,
5541
				'value'         => $user_data['ID'],
5542
			);
5543
			$options['jetpack_user_login'] = array(
5544
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5545
				'readonly'      => true,
5546
				'value'         => $user_data['login'],
5547
			);
5548
			$options['jetpack_user_email'] = array(
5549
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5550
				'readonly'      => true,
5551
				'value'         => $user_data['email'],
5552
			);
5553
			$options['jetpack_user_site_count'] = array(
5554
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5555
				'readonly'      => true,
5556
				'value'         => $user_data['site_count'],
5557
			);
5558
		}
5559
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5560
		$args = stripslashes_deep( $args );
5561
		return $wp_xmlrpc_server->wp_getOptions( $args );
5562
	}
5563
5564
	function xmlrpc_options( $options ) {
5565
		$jetpack_client_id = false;
5566
		if ( self::is_active() ) {
5567
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5568
		}
5569
		$options['jetpack_version'] = array(
5570
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5571
				'readonly'      => true,
5572
				'value'         => JETPACK__VERSION,
5573
		);
5574
5575
		$options['jetpack_client_id'] = array(
5576
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5577
				'readonly'      => true,
5578
				'value'         => $jetpack_client_id,
5579
		);
5580
		return $options;
5581
	}
5582
5583
	public static function clean_nonces( $all = false ) {
5584
		global $wpdb;
5585
5586
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5587
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5588
5589
		if ( true !== $all ) {
5590
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5591
			$sql_args[] = time() - 3600;
5592
		}
5593
5594
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5595
5596
		$sql = $wpdb->prepare( $sql, $sql_args );
5597
5598
		for ( $i = 0; $i < 1000; $i++ ) {
5599
			if ( ! $wpdb->query( $sql ) ) {
5600
				break;
5601
			}
5602
		}
5603
	}
5604
5605
	/**
5606
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5607
	 * SET: state( $key, $value );
5608
	 * GET: $value = state( $key );
5609
	 *
5610
	 * @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...
5611
	 * @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...
5612
	 * @param bool $restate private
5613
	 */
5614
	public static function state( $key = null, $value = null, $restate = false ) {
5615
		static $state = array();
5616
		static $path, $domain;
5617
		if ( ! isset( $path ) ) {
5618
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5619
			$admin_url = Jetpack::admin_url();
5620
			$bits      = wp_parse_url( $admin_url );
5621
5622
			if ( is_array( $bits ) ) {
5623
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5624
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5625
			} else {
5626
				$path = $domain = null;
5627
			}
5628
		}
5629
5630
		// Extract state from cookies and delete cookies
5631
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5632
			$yum = $_COOKIE[ 'jetpackState' ];
5633
			unset( $_COOKIE[ 'jetpackState' ] );
5634
			foreach ( $yum as $k => $v ) {
5635
				if ( strlen( $v ) )
5636
					$state[ $k ] = $v;
5637
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5638
			}
5639
		}
5640
5641
		if ( $restate ) {
5642
			foreach ( $state as $k => $v ) {
5643
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5644
			}
5645
			return;
5646
		}
5647
5648
		// Get a state variable
5649
		if ( isset( $key ) && ! isset( $value ) ) {
5650
			if ( array_key_exists( $key, $state ) )
5651
				return $state[ $key ];
5652
			return null;
5653
		}
5654
5655
		// Set a state variable
5656
		if ( isset ( $key ) && isset( $value ) ) {
5657
			if( is_array( $value ) && isset( $value[0] ) ) {
5658
				$value = $value[0];
5659
			}
5660
			$state[ $key ] = $value;
5661
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5662
		}
5663
	}
5664
5665
	public static function restate() {
5666
		Jetpack::state( null, null, true );
5667
	}
5668
5669
	public static function check_privacy( $file ) {
5670
		static $is_site_publicly_accessible = null;
5671
5672
		if ( is_null( $is_site_publicly_accessible ) ) {
5673
			$is_site_publicly_accessible = false;
5674
5675
			Jetpack::load_xml_rpc_client();
5676
			$rpc = new Jetpack_IXR_Client();
5677
5678
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5679
			if ( $success ) {
5680
				$response = $rpc->getResponse();
5681
				if ( $response ) {
5682
					$is_site_publicly_accessible = true;
5683
				}
5684
			}
5685
5686
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5687
		}
5688
5689
		if ( $is_site_publicly_accessible ) {
5690
			return;
5691
		}
5692
5693
		$module_slug = self::get_module_slug( $file );
5694
5695
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5696
		if ( ! $privacy_checks ) {
5697
			$privacy_checks = $module_slug;
5698
		} else {
5699
			$privacy_checks .= ",$module_slug";
5700
		}
5701
5702
		Jetpack::state( 'privacy_checks', $privacy_checks );
5703
	}
5704
5705
	/**
5706
	 * Helper method for multicall XMLRPC.
5707
	 */
5708
	public static function xmlrpc_async_call() {
5709
		global $blog_id;
5710
		static $clients = array();
5711
5712
		$client_blog_id = is_multisite() ? $blog_id : 0;
5713
5714
		if ( ! isset( $clients[$client_blog_id] ) ) {
5715
			Jetpack::load_xml_rpc_client();
5716
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5717
			if ( function_exists( 'ignore_user_abort' ) ) {
5718
				ignore_user_abort( true );
5719
			}
5720
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5721
		}
5722
5723
		$args = func_get_args();
5724
5725
		if ( ! empty( $args[0] ) ) {
5726
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5727
		} elseif ( is_multisite() ) {
5728
			foreach ( $clients as $client_blog_id => $client ) {
5729
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5730
					continue;
5731
				}
5732
5733
				$switch_success = switch_to_blog( $client_blog_id, true );
5734
				if ( ! $switch_success ) {
5735
					continue;
5736
				}
5737
5738
				flush();
5739
				$client->query();
5740
5741
				restore_current_blog();
5742
			}
5743
		} else {
5744
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5745
				flush();
5746
				$clients[0]->query();
5747
			}
5748
		}
5749
	}
5750
5751
	public static function staticize_subdomain( $url ) {
5752
5753
		// Extract hostname from URL
5754
		$host = parse_url( $url, PHP_URL_HOST );
5755
5756
		// Explode hostname on '.'
5757
		$exploded_host = explode( '.', $host );
5758
5759
		// Retrieve the name and TLD
5760
		if ( count( $exploded_host ) > 1 ) {
5761
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5762
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5763
			// Rebuild domain excluding subdomains
5764
			$domain = $name . '.' . $tld;
5765
		} else {
5766
			$domain = $host;
5767
		}
5768
		// Array of Automattic domains
5769
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5770
5771
		// Return $url if not an Automattic domain
5772
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5773
			return $url;
5774
		}
5775
5776
		if ( is_ssl() ) {
5777
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5778
		}
5779
5780
		srand( crc32( basename( $url ) ) );
5781
		$static_counter = rand( 0, 2 );
5782
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5783
5784
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5785
	}
5786
5787
/* JSON API Authorization */
5788
5789
	/**
5790
	 * Handles the login action for Authorizing the JSON API
5791
	 */
5792
	function login_form_json_api_authorization() {
5793
		$this->verify_json_api_authorization_request();
5794
5795
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5796
5797
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5798
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5799
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5800
	}
5801
5802
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5803
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5804
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5805
			return $url;
5806
		}
5807
5808
		$parsed_url = parse_url( $url );
5809
		$url = strtok( $url, '?' );
5810
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5811
		if ( ! empty( $parsed_url['query'] ) )
5812
			$url .= "&{$parsed_url['query']}";
5813
5814
		return $url;
5815
	}
5816
5817
	// Make sure the POSTed request is handled by the same action
5818
	function preserve_action_in_login_form_for_json_api_authorization() {
5819
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5820
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5821
	}
5822
5823
	// If someone logs in to approve API access, store the Access Code in usermeta
5824
	function store_json_api_authorization_token( $user_login, $user ) {
5825
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5826
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5827
		$token = wp_generate_password( 32, false );
5828
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5829
	}
5830
5831
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5832
	function allow_wpcom_public_api_domain( $domains ) {
5833
		$domains[] = 'public-api.wordpress.com';
5834
		return $domains;
5835
	}
5836
5837
	static function is_redirect_encoded( $redirect_url ) {
5838
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5839
	}
5840
5841
	// Add all wordpress.com environments to the safe redirect whitelist
5842
	function allow_wpcom_environments( $domains ) {
5843
		$domains[] = 'wordpress.com';
5844
		$domains[] = 'wpcalypso.wordpress.com';
5845
		$domains[] = 'horizon.wordpress.com';
5846
		$domains[] = 'calypso.localhost';
5847
		return $domains;
5848
	}
5849
5850
	// Add the Access Code details to the public-api.wordpress.com redirect
5851
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5852
		return add_query_arg(
5853
			urlencode_deep(
5854
				array(
5855
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5856
					'jetpack-user-id' => (int) $user->ID,
5857
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5858
				)
5859
			),
5860
			$redirect_to
5861
		);
5862
	}
5863
5864
5865
	/**
5866
	 * Verifies the request by checking the signature
5867
	 *
5868
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5869
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5870
	 *
5871
	 * @param null|array $environment
5872
	 */
5873
	function verify_json_api_authorization_request( $environment = null ) {
5874
		$environment = is_null( $environment )
5875
			? $_REQUEST
5876
			: $environment;
5877
5878
		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...
5879
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

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

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

Loading history...
5880
		if ( ! $token || empty( $token->secret ) ) {
5881
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5882
		}
5883
5884
		$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' );
5885
5886
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5887
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5888
			Tracking::record_user_event( 'error_double_encode' );
5889
5890
			$die_error = sprintf(
5891
				/* translators: %s is a URL */
5892
				__( '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' ),
5893
				'https://jetpack.com/support/double-encoding/'
5894
			);
5895
		}
5896
5897
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5898
5899
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5900
			$signature = $jetpack_signature->sign_request(
5901
				$environment['token'],
5902
				$environment['timestamp'],
5903
				$environment['nonce'],
5904
				'',
5905
				'GET',
5906
				$environment['jetpack_json_api_original_query'],
5907
				null,
5908
				true
5909
			);
5910
		} else {
5911
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5912
		}
5913
5914
		if ( ! $signature ) {
5915
			wp_die( $die_error );
5916
		} else if ( is_wp_error( $signature ) ) {
5917
			wp_die( $die_error );
5918
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5919
			if ( is_ssl() ) {
5920
				// 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
5921
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5922
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5923
					wp_die( $die_error );
5924
				}
5925
			} else {
5926
				wp_die( $die_error );
5927
			}
5928
		}
5929
5930
		$timestamp = (int) $environment['timestamp'];
5931
		$nonce     = stripslashes( (string) $environment['nonce'] );
5932
5933
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5934
			// De-nonce the nonce, at least for 5 minutes.
5935
			// 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)
5936
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5937
			if ( $old_nonce_time < time() - 300 ) {
5938
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5939
			}
5940
		}
5941
5942
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5943
		$data_filters = array(
5944
			'state'        => 'opaque',
5945
			'client_id'    => 'int',
5946
			'client_title' => 'string',
5947
			'client_image' => 'url',
5948
		);
5949
5950
		foreach ( $data_filters as $key => $sanitation ) {
5951
			if ( ! isset( $data->$key ) ) {
5952
				wp_die( $die_error );
5953
			}
5954
5955
			switch ( $sanitation ) {
5956
			case 'int' :
5957
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5958
				break;
5959
			case 'opaque' :
5960
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5961
				break;
5962
			case 'string' :
5963
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5964
				break;
5965
			case 'url' :
5966
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5967
				break;
5968
			}
5969
		}
5970
5971
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5972
			wp_die( $die_error );
5973
		}
5974
	}
5975
5976
	function login_message_json_api_authorization( $message ) {
5977
		return '<p class="message">' . sprintf(
5978
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5979
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5980
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5981
	}
5982
5983
	/**
5984
	 * Get $content_width, but with a <s>twist</s> filter.
5985
	 */
5986
	public static function get_content_width() {
5987
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5988
			? $GLOBALS['content_width']
5989
			: false;
5990
		/**
5991
		 * Filter the Content Width value.
5992
		 *
5993
		 * @since 2.2.3
5994
		 *
5995
		 * @param string $content_width Content Width value.
5996
		 */
5997
		return apply_filters( 'jetpack_content_width', $content_width );
5998
	}
5999
6000
	/**
6001
	 * Pings the WordPress.com Mirror Site for the specified options.
6002
	 *
6003
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6004
	 *
6005
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6006
	 */
6007
	public function get_cloud_site_options( $option_names ) {
6008
		$option_names = array_filter( (array) $option_names, 'is_string' );
6009
6010
		Jetpack::load_xml_rpc_client();
6011
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6012
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6013
		if ( $xml->isError() ) {
6014
			return array(
6015
				'error_code' => $xml->getErrorCode(),
6016
				'error_msg'  => $xml->getErrorMessage(),
6017
			);
6018
		}
6019
		$cloud_site_options = $xml->getResponse();
6020
6021
		return $cloud_site_options;
6022
	}
6023
6024
	/**
6025
	 * Checks if the site is currently in an identity crisis.
6026
	 *
6027
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6028
	 */
6029
	public static function check_identity_crisis() {
6030
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6031
			return false;
6032
		}
6033
6034
		return Jetpack_Options::get_option( 'sync_error_idc' );
6035
	}
6036
6037
	/**
6038
	 * Checks whether the home and siteurl specifically are whitelisted
6039
	 * Written so that we don't have re-check $key and $value params every time
6040
	 * we want to check if this site is whitelisted, for example in footer.php
6041
	 *
6042
	 * @since  3.8.0
6043
	 * @return bool True = already whitelisted False = not whitelisted
6044
	 */
6045
	public static function is_staging_site() {
6046
		$is_staging = false;
6047
6048
		$known_staging = array(
6049
			'urls' => array(
6050
				'#\.staging\.wpengine\.com$#i', // WP Engine
6051
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6052
				),
6053
			'constants' => array(
6054
				'IS_WPE_SNAPSHOT',      // WP Engine
6055
				'KINSTA_DEV_ENV',       // Kinsta.com
6056
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6057
				'JETPACK_STAGING_MODE', // Generic
6058
				)
6059
			);
6060
		/**
6061
		 * Filters the flags of known staging sites.
6062
		 *
6063
		 * @since 3.9.0
6064
		 *
6065
		 * @param array $known_staging {
6066
		 *     An array of arrays that each are used to check if the current site is staging.
6067
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6068
		 *     @type array $constants PHP constants of known staging/developement environments.
6069
		 *  }
6070
		 */
6071
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6072
6073
		if ( isset( $known_staging['urls'] ) ) {
6074
			foreach ( $known_staging['urls'] as $url ){
6075
				if ( preg_match( $url, site_url() ) ) {
6076
					$is_staging = true;
6077
					break;
6078
				}
6079
			}
6080
		}
6081
6082
		if ( isset( $known_staging['constants'] ) ) {
6083
			foreach ( $known_staging['constants'] as $constant ) {
6084
				if ( defined( $constant ) && constant( $constant ) ) {
6085
					$is_staging = true;
6086
				}
6087
			}
6088
		}
6089
6090
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6091
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6092
			$is_staging = true;
6093
		}
6094
6095
		/**
6096
		 * Filters is_staging_site check.
6097
		 *
6098
		 * @since 3.9.0
6099
		 *
6100
		 * @param bool $is_staging If the current site is a staging site.
6101
		 */
6102
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6103
	}
6104
6105
	/**
6106
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6107
	 *
6108
	 * @since 4.4.0
6109
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6110
	 *
6111
	 * @return bool
6112
	 */
6113
	public static function validate_sync_error_idc_option() {
6114
		$is_valid = false;
6115
6116
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6117
		if ( false === $idc_allowed ) {
6118
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6119
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6120
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6121
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6122
				$transient_duration = HOUR_IN_SECONDS;
6123
			} else {
6124
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6125
				$idc_allowed = '1';
6126
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6127
			}
6128
6129
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6130
		}
6131
6132
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6133
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6134
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6135
			$local_options = self::get_sync_error_idc_option();
6136
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6137
				$is_valid = true;
6138
			}
6139
		}
6140
6141
		/**
6142
		 * Filters whether the sync_error_idc option is valid.
6143
		 *
6144
		 * @since 4.4.0
6145
		 *
6146
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6147
		 */
6148
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6149
6150
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6151
			// Since the option exists, and did not validate, delete it
6152
			Jetpack_Options::delete_option( 'sync_error_idc' );
6153
		}
6154
6155
		return $is_valid;
6156
	}
6157
6158
	/**
6159
	 * Normalizes a url by doing three things:
6160
	 *  - Strips protocol
6161
	 *  - Strips www
6162
	 *  - Adds a trailing slash
6163
	 *
6164
	 * @since 4.4.0
6165
	 * @param string $url
6166
	 * @return WP_Error|string
6167
	 */
6168
	public static function normalize_url_protocol_agnostic( $url ) {
6169
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6170
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6171
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6172
		}
6173
6174
		// Strip www and protocols
6175
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6176
		return $url;
6177
	}
6178
6179
	/**
6180
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6181
	 *
6182
	 * @since 4.4.0
6183
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6184
	 *
6185
	 * @param array $response
6186
	 * @return array Array of the local urls, wpcom urls, and error code
6187
	 */
6188
	public static function get_sync_error_idc_option( $response = array() ) {
6189
		// Since the local options will hit the database directly, store the values
6190
		// in a transient to allow for autoloading and caching on subsequent views.
6191
		$local_options = get_transient( 'jetpack_idc_local' );
6192
		if ( false === $local_options ) {
6193
			$local_options = array(
6194
				'home'    => Jetpack_Sync_Functions::home_url(),
6195
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6196
			);
6197
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6198
		}
6199
6200
		$options = array_merge( $local_options, $response );
6201
6202
		$returned_values = array();
6203
		foreach( $options as $key => $option ) {
6204
			if ( 'error_code' === $key ) {
6205
				$returned_values[ $key ] = $option;
6206
				continue;
6207
			}
6208
6209
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6210
				continue;
6211
			}
6212
6213
			$returned_values[ $key ] = $normalized_url;
6214
		}
6215
6216
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6217
6218
		return $returned_values;
6219
	}
6220
6221
	/**
6222
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6223
	 * If set to true, the site will be put into staging mode.
6224
	 *
6225
	 * @since 4.3.2
6226
	 * @return bool
6227
	 */
6228
	public static function sync_idc_optin() {
6229
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6230
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6231
		} else {
6232
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6233
		}
6234
6235
		/**
6236
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6237
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6238
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6239
		 *
6240
		 * @since 4.3.2
6241
		 *
6242
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6243
		 */
6244
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6245
	}
6246
6247
	/**
6248
	 * Maybe Use a .min.css stylesheet, maybe not.
6249
	 *
6250
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6251
	 */
6252
	public static function maybe_min_asset( $url, $path, $plugin ) {
6253
		// Short out on things trying to find actual paths.
6254
		if ( ! $path || empty( $plugin ) ) {
6255
			return $url;
6256
		}
6257
6258
		$path = ltrim( $path, '/' );
6259
6260
		// Strip out the abspath.
6261
		$base = dirname( plugin_basename( $plugin ) );
6262
6263
		// Short out on non-Jetpack assets.
6264
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6265
			return $url;
6266
		}
6267
6268
		// File name parsing.
6269
		$file              = "{$base}/{$path}";
6270
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6271
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6272
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6273
		$extension         = array_shift( $file_name_parts_r );
6274
6275
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6276
			// Already pointing at the minified version.
6277
			if ( 'min' === $file_name_parts_r[0] ) {
6278
				return $url;
6279
			}
6280
6281
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6282
			if ( file_exists( $min_full_path ) ) {
6283
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6284
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6285
				if ( 'css' === $extension ) {
6286
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6287
					self::$min_assets[ $key ] = $path;
6288
				}
6289
			}
6290
		}
6291
6292
		return $url;
6293
	}
6294
6295
	/**
6296
	 * If the asset is minified, let's flag .min as the suffix.
6297
	 *
6298
	 * Attached to `style_loader_src` filter.
6299
	 *
6300
	 * @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...
6301
	 * @param string $handle The registered handle of the script in question.
6302
	 * @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...
6303
	 */
6304
	public static function set_suffix_on_min( $src, $handle ) {
6305
		if ( false === strpos( $src, '.min.css' ) ) {
6306
			return $src;
6307
		}
6308
6309
		if ( ! empty( self::$min_assets ) ) {
6310
			foreach ( self::$min_assets as $file => $path ) {
6311
				if ( false !== strpos( $src, $file ) ) {
6312
					wp_style_add_data( $handle, 'suffix', '.min' );
6313
					return $src;
6314
				}
6315
			}
6316
		}
6317
6318
		return $src;
6319
	}
6320
6321
	/**
6322
	 * Maybe inlines a stylesheet.
6323
	 *
6324
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6325
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6326
	 *
6327
	 * Attached to `style_loader_tag` filter.
6328
	 *
6329
	 * @param string $tag The tag that would link to the external asset.
6330
	 * @param string $handle The registered handle of the script in question.
6331
	 *
6332
	 * @return string
6333
	 */
6334
	public static function maybe_inline_style( $tag, $handle ) {
6335
		global $wp_styles;
6336
		$item = $wp_styles->registered[ $handle ];
6337
6338
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6339
			return $tag;
6340
		}
6341
6342
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6343
			$href = $matches[1];
6344
			// Strip off query string
6345
			if ( $pos = strpos( $href, '?' ) ) {
6346
				$href = substr( $href, 0, $pos );
6347
			}
6348
			// Strip off fragment
6349
			if ( $pos = strpos( $href, '#' ) ) {
6350
				$href = substr( $href, 0, $pos );
6351
			}
6352
		} else {
6353
			return $tag;
6354
		}
6355
6356
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6357
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6358
			return $tag;
6359
		}
6360
6361
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6362
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6363
			// And this isn't the pass that actually deals with the RTL version...
6364
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6365
				// Short out, as the RTL version will deal with it in a moment.
6366
				return $tag;
6367
			}
6368
		}
6369
6370
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6371
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6372
		if ( $css ) {
6373
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6374
			if ( empty( $item->extra['after'] ) ) {
6375
				wp_add_inline_style( $handle, $css );
6376
			} else {
6377
				array_unshift( $item->extra['after'], $css );
6378
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6379
			}
6380
		}
6381
6382
		return $tag;
6383
	}
6384
6385
	/**
6386
	 * Loads a view file from the views
6387
	 *
6388
	 * Data passed in with the $data parameter will be available in the
6389
	 * template file as $data['value']
6390
	 *
6391
	 * @param string $template - Template file to load
6392
	 * @param array $data - Any data to pass along to the template
6393
	 * @return boolean - If template file was found
6394
	 **/
6395
	public function load_view( $template, $data = array() ) {
6396
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6397
6398
		if( file_exists( $views_dir . $template ) ) {
6399
			require_once( $views_dir . $template );
6400
			return true;
6401
		}
6402
6403
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6404
		return false;
6405
	}
6406
6407
	/**
6408
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6409
	 */
6410
	public function deprecated_hooks() {
6411
		global $wp_filter;
6412
6413
		/*
6414
		 * Format:
6415
		 * deprecated_filter_name => replacement_name
6416
		 *
6417
		 * If there is no replacement, use null for replacement_name
6418
		 */
6419
		$deprecated_list = array(
6420
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6421
			'wpl_sharing_2014_1'                                     => null,
6422
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6423
			'jetpack_identity_crisis_options_to_check'               => null,
6424
			'update_option_jetpack_single_user_site'                 => null,
6425
			'audio_player_default_colors'                            => null,
6426
			'add_option_jetpack_featured_images_enabled'             => null,
6427
			'add_option_jetpack_update_details'                      => null,
6428
			'add_option_jetpack_updates'                             => null,
6429
			'add_option_jetpack_network_name'                        => null,
6430
			'add_option_jetpack_network_allow_new_registrations'     => null,
6431
			'add_option_jetpack_network_add_new_users'               => null,
6432
			'add_option_jetpack_network_site_upload_space'           => null,
6433
			'add_option_jetpack_network_upload_file_types'           => null,
6434
			'add_option_jetpack_network_enable_administration_menus' => null,
6435
			'add_option_jetpack_is_multi_site'                       => null,
6436
			'add_option_jetpack_is_main_network'                     => null,
6437
			'add_option_jetpack_main_network_site'                   => null,
6438
			'jetpack_sync_all_registered_options'                    => null,
6439
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6440
			'jetpack_is_post_mailable'                               => null,
6441
			'jetpack_seo_site_host'                                  => null,
6442
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6443
			'jetpack_holiday_snow_option_name'                       => null,
6444
			'jetpack_holiday_chance_of_snow'                         => null,
6445
			'jetpack_holiday_snow_js_url'                            => null,
6446
			'jetpack_is_holiday_snow_season'                         => null,
6447
			'jetpack_holiday_snow_option_updated'                    => null,
6448
			'jetpack_holiday_snowing'                                => null,
6449
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6450
			'jetpack_cache_plans'                                    => null,
6451
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6452
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6453
			'jetpack_enable_site_verification'                       => null,
6454
			'can_display_jetpack_manage_notice'                      => null,
6455
			// Removed in Jetpack 7.3.0
6456
			'atd_load_scripts'                                       => null,
6457
			'atd_http_post_timeout'                                  => null,
6458
			'atd_http_post_error'                                    => null,
6459
			'atd_service_domain'                                     => null,
6460
		);
6461
6462
		// This is a silly loop depth. Better way?
6463
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6464
			if ( has_action( $hook ) ) {
6465
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6466
					foreach( $values AS $hooked ) {
6467
						if ( is_callable( $hooked['function'] ) ) {
6468
							$function_name = 'an anonymous function';
6469
						} else {
6470
							$function_name = $hooked['function'];
6471
						}
6472
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6473
					}
6474
				}
6475
			}
6476
		}
6477
	}
6478
6479
	/**
6480
	 * Converts any url in a stylesheet, to the correct absolute url.
6481
	 *
6482
	 * Considerations:
6483
	 *  - Normal, relative URLs     `feh.png`
6484
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6485
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6486
	 *  - Absolute URLs             `http://domain.com/feh.png`
6487
	 *  - Domain root relative URLs `/feh.png`
6488
	 *
6489
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6490
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6491
	 *
6492
	 * @return mixed|string
6493
	 */
6494
	public static function absolutize_css_urls( $css, $css_file_url ) {
6495
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6496
		$css_dir = dirname( $css_file_url );
6497
		$p       = parse_url( $css_dir );
6498
		$domain  = sprintf(
6499
					'%1$s//%2$s%3$s%4$s',
6500
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6501
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6502
					$p['host'],
6503
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6504
				);
6505
6506
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6507
			$find = $replace = array();
6508
			foreach ( $matches as $match ) {
6509
				$url = trim( $match['path'], "'\" \t" );
6510
6511
				// If this is a data url, we don't want to mess with it.
6512
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6513
					continue;
6514
				}
6515
6516
				// If this is an absolute or protocol-agnostic url,
6517
				// we don't want to mess with it.
6518
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6519
					continue;
6520
				}
6521
6522
				switch ( substr( $url, 0, 1 ) ) {
6523
					case '/':
6524
						$absolute = $domain . $url;
6525
						break;
6526
					default:
6527
						$absolute = $css_dir . '/' . $url;
6528
				}
6529
6530
				$find[]    = $match[0];
6531
				$replace[] = sprintf( 'url("%s")', $absolute );
6532
			}
6533
			$css = str_replace( $find, $replace, $css );
6534
		}
6535
6536
		return $css;
6537
	}
6538
6539
	/**
6540
	 * This methods removes all of the registered css files on the front end
6541
	 * from Jetpack in favor of using a single file. In effect "imploding"
6542
	 * all the files into one file.
6543
	 *
6544
	 * Pros:
6545
	 * - Uses only ONE css asset connection instead of 15
6546
	 * - Saves a minimum of 56k
6547
	 * - Reduces server load
6548
	 * - Reduces time to first painted byte
6549
	 *
6550
	 * Cons:
6551
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6552
	 *		should not cause any issues with themes.
6553
	 * - Plugins/themes dequeuing styles no longer do anything. See
6554
	 *		jetpack_implode_frontend_css filter for a workaround
6555
	 *
6556
	 * For some situations developers may wish to disable css imploding and
6557
	 * instead operate in legacy mode where each file loads seperately and
6558
	 * can be edited individually or dequeued. This can be accomplished with
6559
	 * the following line:
6560
	 *
6561
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6562
	 *
6563
	 * @since 3.2
6564
	 **/
6565
	public function implode_frontend_css( $travis_test = false ) {
6566
		$do_implode = true;
6567
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6568
			$do_implode = false;
6569
		}
6570
6571
		// Do not implode CSS when the page loads via the AMP plugin.
6572
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6573
			$do_implode = false;
6574
		}
6575
6576
		/**
6577
		 * Allow CSS to be concatenated into a single jetpack.css file.
6578
		 *
6579
		 * @since 3.2.0
6580
		 *
6581
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6582
		 */
6583
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6584
6585
		// Do not use the imploded file when default behavior was altered through the filter
6586
		if ( ! $do_implode ) {
6587
			return;
6588
		}
6589
6590
		// We do not want to use the imploded file in dev mode, or if not connected
6591
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6592
			if ( ! $travis_test ) {
6593
				return;
6594
			}
6595
		}
6596
6597
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6598
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6599
			return;
6600
		}
6601
6602
		/*
6603
		 * Now we assume Jetpack is connected and able to serve the single
6604
		 * file.
6605
		 *
6606
		 * In the future there will be a check here to serve the file locally
6607
		 * or potentially from the Jetpack CDN
6608
		 *
6609
		 * For now:
6610
		 * - Enqueue a single imploded css file
6611
		 * - Zero out the style_loader_tag for the bundled ones
6612
		 * - Be happy, drink scotch
6613
		 */
6614
6615
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6616
6617
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6618
6619
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6620
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6621
	}
6622
6623
	function concat_remove_style_loader_tag( $tag, $handle ) {
6624
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6625
			$tag = '';
6626
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6627
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6628
			}
6629
		}
6630
6631
		return $tag;
6632
	}
6633
6634
	/*
6635
	 * Check the heartbeat data
6636
	 *
6637
	 * Organizes the heartbeat data by severity.  For example, if the site
6638
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6639
	 *
6640
	 * Data will be added to "caution" array, if it either:
6641
	 *  - Out of date Jetpack version
6642
	 *  - Out of date WP version
6643
	 *  - Out of date PHP version
6644
	 *
6645
	 * $return array $filtered_data
6646
	 */
6647
	public static function jetpack_check_heartbeat_data() {
6648
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6649
6650
		$good    = array();
6651
		$caution = array();
6652
		$bad     = array();
6653
6654
		foreach ( $raw_data as $stat => $value ) {
6655
6656
			// Check jetpack version
6657
			if ( 'version' == $stat ) {
6658
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6659
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6660
					continue;
6661
				}
6662
			}
6663
6664
			// Check WP version
6665
			if ( 'wp-version' == $stat ) {
6666
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6667
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6668
					continue;
6669
				}
6670
			}
6671
6672
			// Check PHP version
6673
			if ( 'php-version' == $stat ) {
6674
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6675
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6676
					continue;
6677
				}
6678
			}
6679
6680
			// Check ID crisis
6681
			if ( 'identitycrisis' == $stat ) {
6682
				if ( 'yes' == $value ) {
6683
					$bad[ $stat ] = $value;
6684
					continue;
6685
				}
6686
			}
6687
6688
			// The rest are good :)
6689
			$good[ $stat ] = $value;
6690
		}
6691
6692
		$filtered_data = array(
6693
			'good'    => $good,
6694
			'caution' => $caution,
6695
			'bad'     => $bad
6696
		);
6697
6698
		return $filtered_data;
6699
	}
6700
6701
6702
	/*
6703
	 * This method is used to organize all options that can be reset
6704
	 * without disconnecting Jetpack.
6705
	 *
6706
	 * It is used in class.jetpack-cli.php to reset options
6707
	 *
6708
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6709
	 *
6710
	 * @return array of options to delete.
6711
	 */
6712
	public static function get_jetpack_options_for_reset() {
6713
		return Jetpack_Options::get_options_for_reset();
6714
	}
6715
6716
	/*
6717
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6718
	 * so we can bring them directly to their site in calypso.
6719
	 *
6720
	 * @param string | url
6721
	 * @return string | url without the guff
6722
	 */
6723
	public static function build_raw_urls( $url ) {
6724
		$strip_http = '/.*?:\/\//i';
6725
		$url = preg_replace( $strip_http, '', $url  );
6726
		$url = str_replace( '/', '::', $url );
6727
		return $url;
6728
	}
6729
6730
	/**
6731
	 * Stores and prints out domains to prefetch for page speed optimization.
6732
	 *
6733
	 * @param mixed $new_urls
6734
	 */
6735
	public static function dns_prefetch( $new_urls = null ) {
6736
		static $prefetch_urls = array();
6737
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6738
			echo "\r\n";
6739
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6740
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6741
			}
6742
		} elseif ( ! empty( $new_urls ) ) {
6743
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6744
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6745
			}
6746
			foreach ( (array) $new_urls as $this_new_url ) {
6747
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6748
			}
6749
			$prefetch_urls = array_unique( $prefetch_urls );
6750
		}
6751
	}
6752
6753
	public function wp_dashboard_setup() {
6754
		if ( self::is_active() ) {
6755
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6756
		}
6757
6758
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6759
			$jetpack_logo = new Jetpack_Logo();
6760
			$widget_title = sprintf(
6761
				wp_kses(
6762
					/* translators: Placeholder is a Jetpack logo. */
6763
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6764
					array( 'span' => array() )
6765
				),
6766
				$jetpack_logo->get_jp_emblem( true )
6767
			);
6768
6769
			wp_add_dashboard_widget(
6770
				'jetpack_summary_widget',
6771
				$widget_title,
6772
				array( __CLASS__, 'dashboard_widget' )
6773
			);
6774
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6775
6776
			// If we're inactive and not in development mode, sort our box to the top.
6777
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6778
				global $wp_meta_boxes;
6779
6780
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6781
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6782
6783
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6784
			}
6785
		}
6786
	}
6787
6788
	/**
6789
	 * @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...
6790
	 * @return mixed
6791
	 */
6792
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6793
		if ( ! is_array( $sorted ) ) {
6794
			return $sorted;
6795
		}
6796
6797
		foreach ( $sorted as $box_context => $ids ) {
6798
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6799
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6800
				continue;
6801
			}
6802
6803
			$ids_array = explode( ',', $ids );
6804
			$key = array_search( 'dashboard_stats', $ids_array );
6805
6806
			if ( false !== $key ) {
6807
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6808
				$ids_array[ $key ] = 'jetpack_summary_widget';
6809
				$sorted[ $box_context ] = implode( ',', $ids_array );
6810
				// We've found it, stop searching, and just return.
6811
				break;
6812
			}
6813
		}
6814
6815
		return $sorted;
6816
	}
6817
6818
	public static function dashboard_widget() {
6819
		/**
6820
		 * Fires when the dashboard is loaded.
6821
		 *
6822
		 * @since 3.4.0
6823
		 */
6824
		do_action( 'jetpack_dashboard_widget' );
6825
	}
6826
6827
	public static function dashboard_widget_footer() {
6828
		?>
6829
		<footer>
6830
6831
		<div class="protect">
6832
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6833
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6834
				<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>
6835
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6836
				<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' ); ?>">
6837
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6838
				</a>
6839
			<?php else : ?>
6840
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6841
			<?php endif; ?>
6842
		</div>
6843
6844
		<div class="akismet">
6845
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6846
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6847
				<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>
6848
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6849
				<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">
6850
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6851
				</a>
6852
			<?php else : ?>
6853
				<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>
6854
			<?php endif; ?>
6855
		</div>
6856
6857
		</footer>
6858
		<?php
6859
	}
6860
6861
	/*
6862
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6863
	 */
6864
	function jetpack_icon_user_connected( $columns ) {
6865
		$columns['user_jetpack'] = '';
6866
		return $columns;
6867
	}
6868
6869
	/*
6870
	 * Show Jetpack icon if the user is linked.
6871
	 */
6872
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6873
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6874
			$jetpack_logo = new Jetpack_Logo();
6875
			$emblem_html = sprintf(
6876
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6877
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6878
				$jetpack_logo->get_jp_emblem()
6879
			);
6880
			return $emblem_html;
6881
		}
6882
6883
		return $val;
6884
	}
6885
6886
	/*
6887
	 * Style the Jetpack user column
6888
	 */
6889
	function jetpack_user_col_style() {
6890
		global $current_screen;
6891
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6892
			<style>
6893
				.fixed .column-user_jetpack {
6894
					width: 21px;
6895
				}
6896
				.jp-emblem-user-admin svg {
6897
					width: 20px;
6898
					height: 20px;
6899
				}
6900
				.jp-emblem-user-admin path {
6901
					fill: #00BE28;
6902
				}
6903
			</style>
6904
		<?php }
6905
	}
6906
6907
	/**
6908
	 * Checks if Akismet is active and working.
6909
	 *
6910
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6911
	 * that implied usage of methods present since more recent version.
6912
	 * See https://github.com/Automattic/jetpack/pull/9585
6913
	 *
6914
	 * @since  5.1.0
6915
	 *
6916
	 * @return bool True = Akismet available. False = Aksimet not available.
6917
	 */
6918
	public static function is_akismet_active() {
6919
		static $status = null;
6920
6921
		if ( ! is_null( $status ) ) {
6922
			return $status;
6923
		}
6924
6925
		// Check if a modern version of Akismet is active.
6926
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6927
			$status = false;
6928
			return $status;
6929
		}
6930
6931
		// Make sure there is a key known to Akismet at all before verifying key.
6932
		$akismet_key = Akismet::get_api_key();
6933
		if ( ! $akismet_key ) {
6934
			$status = false;
6935
			return $status;
6936
		}
6937
6938
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6939
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6940
6941
		// 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.
6942
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6943
		// We cache the result of the Akismet key verification for ten minutes.
6944
		if ( ! $akismet_key_state || $recheck ) {
6945
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6946
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6947
		}
6948
6949
		$status = 'valid' === $akismet_key_state;
6950
6951
		return $status;
6952
	}
6953
6954
	/**
6955
	 * Checks if one or more function names is in debug_backtrace
6956
	 *
6957
	 * @param $names Mixed string name of function or array of string names of functions
6958
	 *
6959
	 * @return bool
6960
	 */
6961
	public static function is_function_in_backtrace( $names ) {
6962
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6963
		if ( ! is_array( $names ) ) {
6964
			$names = array( $names );
6965
		}
6966
		$names_as_keys = array_flip( $names );
6967
6968
		//Do check in constant O(1) time for PHP5.5+
6969
		if ( function_exists( 'array_column' ) ) {
6970
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6971
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6972
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6973
			return ! empty ( $intersection );
6974
		}
6975
6976
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6977
		foreach ( $backtrace as $call ) {
6978
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6979
				return true;
6980
			}
6981
		}
6982
		return false;
6983
	}
6984
6985
	/**
6986
	 * Given a minified path, and a non-minified path, will return
6987
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6988
	 *
6989
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6990
	 * root Jetpack directory.
6991
	 *
6992
	 * @since 5.6.0
6993
	 *
6994
	 * @param string $min_path
6995
	 * @param string $non_min_path
6996
	 * @return string The URL to the file
6997
	 */
6998
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6999
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
7000
			? $non_min_path
7001
			: $min_path;
7002
7003
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7004
	}
7005
7006
	/**
7007
	 * Checks for whether Jetpack Backup & Scan is enabled.
7008
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7009
	 * @return bool|int|mixed
7010
	 */
7011
	public static function is_rewind_enabled() {
7012
		if ( ! Jetpack::is_active() ) {
7013
			return false;
7014
		}
7015
7016
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7017
		if ( false === $rewind_enabled ) {
7018
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7019
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7020
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7021
				&& ! empty( $rewind_data['state'] )
7022
				&& 'active' === $rewind_data['state'] )
7023
				? 1
7024
				: 0;
7025
7026
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7027
		}
7028
		return $rewind_enabled;
7029
	}
7030
7031
	/**
7032
	 * Return Calypso environment value; used for developing Jetpack and pairing
7033
	 * it with different Calypso enrionments, such as localhost.
7034
	 *
7035
	 * @since 7.4.0
7036
	 *
7037
	 * @return string Calypso environment
7038
	 */
7039
	public static function get_calypso_env() {
7040
		if ( isset( $_GET['calypso_env'] ) ) {
7041
			return sanitize_key( $_GET['calypso_env'] );
7042
		}
7043
7044
		if ( getenv( 'CALYPSO_ENV' ) ) {
7045
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7046
		}
7047
7048
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7049
			return sanitize_key( CALYPSO_ENV );
7050
		}
7051
7052
		return '';
7053
	}
7054
7055
	/**
7056
	 * Checks whether or not TOS has been agreed upon.
7057
	 * Will return true if a user has clicked to register, or is already connected.
7058
	 */
7059
	public static function jetpack_tos_agreed() {
7060
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7061
	}
7062
7063
	/**
7064
	 * Handles activating default modules as well general cleanup for the new connection.
7065
	 *
7066
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7067
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7068
	 * @param boolean $send_state_messages          Whether to send state messages.
7069
	 * @return void
7070
	 */
7071
	public static function handle_post_authorization_actions(
7072
		$activate_sso = false,
7073
		$redirect_on_activation_error = false,
7074
		$send_state_messages = true
7075
	) {
7076
		$other_modules = $activate_sso
7077
			? array( 'sso' )
7078
			: array();
7079
7080
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7081
			Jetpack::delete_active_modules();
7082
7083
			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...
7084
		} else {
7085
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7086
		}
7087
7088
		// Since this is a fresh connection, be sure to clear out IDC options
7089
		Jetpack_IDC::clear_all_idc_options();
7090
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7091
7092
		// Start nonce cleaner
7093
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7094
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7095
7096
		if ( $send_state_messages ) {
7097
			Jetpack::state( 'message', 'authorized' );
7098
		}
7099
	}
7100
7101
	/**
7102
	 * Returns a boolean for whether backups UI should be displayed or not.
7103
	 *
7104
	 * @return bool Should backups UI be displayed?
7105
	 */
7106
	public static function show_backups_ui() {
7107
		/**
7108
		 * Whether UI for backups should be displayed.
7109
		 *
7110
		 * @since 6.5.0
7111
		 *
7112
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7113
		 */
7114
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7115
	}
7116
7117
	/*
7118
	 * Deprecated manage functions
7119
	 */
7120
	function prepare_manage_jetpack_notice() {
7121
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7122
	}
7123
	function manage_activate_screen() {
7124
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7125
	}
7126
	function admin_jetpack_manage_notice() {
7127
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7128
	}
7129
	function opt_out_jetpack_manage_url() {
7130
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7131
	}
7132
	function opt_in_jetpack_manage_url() {
7133
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7134
	}
7135
	function opt_in_jetpack_manage_notice() {
7136
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7137
	}
7138
	function can_display_jetpack_manage_notice() {
7139
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7140
	}
7141
7142
	/**
7143
	 * Clean leftoveruser meta.
7144
	 *
7145
	 * Delete Jetpack-related user meta when it is no longer needed.
7146
	 *
7147
	 * @since 7.3.0
7148
	 *
7149
	 * @param int $user_id User ID being updated.
7150
	 */
7151
	public static function user_meta_cleanup( $user_id ) {
7152
		$meta_keys = array(
7153
			// AtD removed from Jetpack 7.3
7154
			'AtD_options',
7155
			'AtD_check_when',
7156
			'AtD_guess_lang',
7157
			'AtD_ignored_phrases',
7158
		);
7159
7160
		foreach ( $meta_keys as $meta_key ) {
7161
			if ( get_user_meta( $user_id, $meta_key ) ) {
7162
				delete_user_meta( $user_id, $meta_key );
7163
			}
7164
		}
7165
	}
7166
7167
	function is_active_and_not_development_mode( $maybe ) {
7168
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7169
			return false;
7170
		}
7171
		return true;
7172
	}
7173
}
7174