Completed
Push — update/always-show-jumpstart-e... ( f3b73c )
by
unknown
09:59
created

Jetpack::jumpstart_has_updated_module_option()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

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

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

Loading history...
1289
	 */
1290
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1291
		if ( 'administrator' == $role
1292
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1293
			|| is_null( $old_roles )
1294
		) {
1295
			delete_transient( 'jetpack_other_linked_admins' );
1296
		}
1297
	}
1298
1299
	/**
1300
	 * Checks to see if there are any other users available to become primary
1301
	 * Users must both:
1302
	 * - Be linked to wpcom
1303
	 * - Be an admin
1304
	 *
1305
	 * @return mixed False if no other users are linked, Int if there are.
1306
	 */
1307
	static function get_other_linked_admins() {
1308
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1309
1310
		if ( false === $other_linked_users ) {
1311
			$admins = get_users( array( 'role' => 'administrator' ) );
1312
			if ( count( $admins ) > 1 ) {
1313
				$available = array();
1314
				foreach ( $admins as $admin ) {
1315
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1316
						$available[] = $admin->ID;
1317
					}
1318
				}
1319
1320
				$count_connected_admins = count( $available );
1321
				if ( count( $available ) > 1 ) {
1322
					$other_linked_users = $count_connected_admins;
1323
				} else {
1324
					$other_linked_users = 0;
1325
				}
1326
			} else {
1327
				$other_linked_users = 0;
1328
			}
1329
1330
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1331
		}
1332
1333
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1334
	}
1335
1336
	/**
1337
	 * Return whether we are dealing with a multi network setup or not.
1338
	 * The reason we are type casting this is because we want to avoid the situation where
1339
	 * the result is false since when is_main_network_option return false it cases
1340
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1341
	 * database which could be set to anything as opposed to what this function returns.
1342
	 * @param  bool  $option
1343
	 *
1344
	 * @return boolean
1345
	 */
1346
	public function is_main_network_option( $option ) {
1347
		// return '1' or ''
1348
		return (string) (bool) Jetpack::is_multi_network();
1349
	}
1350
1351
	/**
1352
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1353
	 *
1354
	 * @param  string  $option
1355
	 * @return boolean
1356
	 */
1357
	public function is_multisite( $option ) {
1358
		return (string) (bool) is_multisite();
1359
	}
1360
1361
	/**
1362
	 * Implemented since there is no core is multi network function
1363
	 * Right now there is no way to tell if we which network is the dominant network on the system
1364
	 *
1365
	 * @since  3.3
1366
	 * @return boolean
1367
	 */
1368
	public static function is_multi_network() {
1369
		global  $wpdb;
1370
1371
		// if we don't have a multi site setup no need to do any more
1372
		if ( ! is_multisite() ) {
1373
			return false;
1374
		}
1375
1376
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1377
		if ( $num_sites > 1 ) {
1378
			return true;
1379
		} else {
1380
			return false;
1381
		}
1382
	}
1383
1384
	/**
1385
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1386
	 * @return null
1387
	 */
1388
	function update_jetpack_main_network_site_option() {
1389
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1390
	}
1391
	/**
1392
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1393
	 *
1394
	 */
1395
	function update_jetpack_network_settings() {
1396
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1397
		// Only sync this info for the main network site.
1398
	}
1399
1400
	/**
1401
	 * Get back if the current site is single user site.
1402
	 *
1403
	 * @return bool
1404
	 */
1405
	public static function is_single_user_site() {
1406
		global $wpdb;
1407
1408 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1409
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1410
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1411
		}
1412
		return 1 === (int) $some_users;
1413
	}
1414
1415
	/**
1416
	 * Returns true if the site has file write access false otherwise.
1417
	 * @return string ( '1' | '0' )
1418
	 **/
1419
	public static function file_system_write_access() {
1420
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1421
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1422
		}
1423
1424
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1425
1426
		$filesystem_method = get_filesystem_method();
1427
		if ( $filesystem_method === 'direct' ) {
1428
			return 1;
1429
		}
1430
1431
		ob_start();
1432
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1433
		ob_end_clean();
1434
		if ( $filesystem_credentials_are_stored ) {
1435
			return 1;
1436
		}
1437
		return 0;
1438
	}
1439
1440
	/**
1441
	 * Finds out if a site is using a version control system.
1442
	 * @return string ( '1' | '0' )
1443
	 **/
1444
	public static function is_version_controlled() {
1445
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1446
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1447
	}
1448
1449
	/**
1450
	 * Determines whether the current theme supports featured images or not.
1451
	 * @return string ( '1' | '0' )
1452
	 */
1453
	public static function featured_images_enabled() {
1454
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1455
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1456
	}
1457
1458
	/**
1459
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1460
	 *
1461
	 * @deprecated 4.7 use get_avatar_url instead.
1462
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1463
	 * @param int $size Size of the avatar image
1464
	 * @param string $default URL to a default image to use if no avatar is available
1465
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1466
	 *
1467
	 * @return array
1468
	 */
1469
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1470
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1471
		return get_avatar_url( $id_or_email, array(
1472
			'size' => $size,
1473
			'default' => $default,
1474
			'force_default' => $force_display,
1475
		) );
1476
	}
1477
1478
	/**
1479
	 * jetpack_updates is saved in the following schema:
1480
	 *
1481
	 * array (
1482
	 *      'plugins'                       => (int) Number of plugin updates available.
1483
	 *      'themes'                        => (int) Number of theme updates available.
1484
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1485
	 *      'translations'                  => (int) Number of translation updates available.
1486
	 *      'total'                         => (int) Total of all available updates.
1487
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1488
	 * )
1489
	 * @return array
1490
	 */
1491
	public static function get_updates() {
1492
		$update_data = wp_get_update_data();
1493
1494
		// Stores the individual update counts as well as the total count.
1495
		if ( isset( $update_data['counts'] ) ) {
1496
			$updates = $update_data['counts'];
1497
		}
1498
1499
		// If we need to update WordPress core, let's find the latest version number.
1500 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1501
			$cur = get_preferred_from_update_core();
1502
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1503
				$updates['wp_update_version'] = $cur->current;
1504
			}
1505
		}
1506
		return isset( $updates ) ? $updates : array();
1507
	}
1508
1509
	public static function get_update_details() {
1510
		$update_details = array(
1511
			'update_core' => get_site_transient( 'update_core' ),
1512
			'update_plugins' => get_site_transient( 'update_plugins' ),
1513
			'update_themes' => get_site_transient( 'update_themes' ),
1514
		);
1515
		return $update_details;
1516
	}
1517
1518
	public static function refresh_update_data() {
1519
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1520
1521
	}
1522
1523
	public static function refresh_theme_data() {
1524
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1525
	}
1526
1527
	/**
1528
	 * Is Jetpack active?
1529
	 */
1530
	public static function is_active() {
1531
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1532
	}
1533
1534
	/**
1535
	 * Make an API call to WordPress.com for plan status
1536
	 *
1537
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1538
	 *
1539
	 * @return bool True if plan is updated, false if no update
1540
	 */
1541
	public static function refresh_active_plan_from_wpcom() {
1542
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1543
		return Jetpack_Plan::refresh_from_wpcom();
1544
	}
1545
1546
	/**
1547
	 * Get the plan that this Jetpack site is currently using
1548
	 *
1549
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1550
	 * @return array Active Jetpack plan details.
1551
	 */
1552
	public static function get_active_plan() {
1553
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1554
		return Jetpack_Plan::get();
1555
	}
1556
1557
	/**
1558
	 * Determine whether the active plan supports a particular feature
1559
	 *
1560
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1561
	 * @return bool True if plan supports feature, false if not.
1562
	 */
1563
	public static function active_plan_supports( $feature ) {
1564
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1565
		return Jetpack_Plan::supports( $feature );
1566
	}
1567
1568
	/**
1569
	 * Is Jetpack in development (offline) mode?
1570
	 */
1571
	public static function is_development_mode() {
1572
		$development_mode = false;
1573
1574
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1575
			$development_mode = JETPACK_DEV_DEBUG;
1576
		} elseif ( $site_url = site_url() ) {
1577
			$development_mode = false === strpos( $site_url, '.' );
1578
		}
1579
1580
		/**
1581
		 * Filters Jetpack's development mode.
1582
		 *
1583
		 * @see https://jetpack.com/support/development-mode/
1584
		 *
1585
		 * @since 2.2.1
1586
		 *
1587
		 * @param bool $development_mode Is Jetpack's development mode active.
1588
		 */
1589
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1590
		return $development_mode;
1591
	}
1592
1593
	/**
1594
	 * Whether the site is currently onboarding or not.
1595
	 * A site is considered as being onboarded if it currently has an onboarding token.
1596
	 *
1597
	 * @since 5.8
1598
	 *
1599
	 * @access public
1600
	 * @static
1601
	 *
1602
	 * @return bool True if the site is currently onboarding, false otherwise
1603
	 */
1604
	public static function is_onboarding() {
1605
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1606
	}
1607
1608
	/**
1609
	 * Determines reason for Jetpack development mode.
1610
	 */
1611
	public static function development_mode_trigger_text() {
1612
		if ( ! Jetpack::is_development_mode() ) {
1613
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1614
		}
1615
1616
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1617
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1618
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1619
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1620
		} else {
1621
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1622
		}
1623
1624
		return $notice;
1625
1626
	}
1627
	/**
1628
	* Get Jetpack development mode notice text and notice class.
1629
	*
1630
	* Mirrors the checks made in Jetpack::is_development_mode
1631
	*
1632
	*/
1633
	public static function show_development_mode_notice() {
1634 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1635
			$notice = sprintf(
1636
			/* translators: %s is a URL */
1637
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1638
				'https://jetpack.com/support/development-mode/'
1639
			);
1640
1641
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1642
1643
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1644
		}
1645
1646
		// Throw up a notice if using a development version and as for feedback.
1647
		if ( Jetpack::is_development_version() ) {
1648
			/* translators: %s is a URL */
1649
			$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/' );
1650
1651
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1652
		}
1653
		// Throw up a notice if using staging mode
1654
		if ( Jetpack::is_staging_site() ) {
1655
			/* translators: %s is a URL */
1656
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1657
1658
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1659
		}
1660
	}
1661
1662
	/**
1663
	 * Whether Jetpack's version maps to a public release, or a development version.
1664
	 */
1665
	public static function is_development_version() {
1666
		/**
1667
		 * Allows filtering whether this is a development version of Jetpack.
1668
		 *
1669
		 * This filter is especially useful for tests.
1670
		 *
1671
		 * @since 4.3.0
1672
		 *
1673
		 * @param bool $development_version Is this a develoment version of Jetpack?
1674
		 */
1675
		return (bool) apply_filters(
1676
			'jetpack_development_version',
1677
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1678
		);
1679
	}
1680
1681
	/**
1682
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1683
	 */
1684
	public static function is_user_connected( $user_id = false ) {
1685
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1686
		if ( ! $user_id ) {
1687
			return false;
1688
		}
1689
1690
		return (bool) Jetpack_Data::get_access_token( $user_id );
1691
	}
1692
1693
	/**
1694
	 * Get the wpcom user data of the current|specified connected user.
1695
	 */
1696
	public static function get_connected_user_data( $user_id = null ) {
1697
		if ( ! $user_id ) {
1698
			$user_id = get_current_user_id();
1699
		}
1700
1701
		$transient_key = "jetpack_connected_user_data_$user_id";
1702
1703
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1704
			return $cached_user_data;
1705
		}
1706
1707
		Jetpack::load_xml_rpc_client();
1708
		$xml = new Jetpack_IXR_Client( array(
1709
			'user_id' => $user_id,
1710
		) );
1711
		$xml->query( 'wpcom.getUser' );
1712
		if ( ! $xml->isError() ) {
1713
			$user_data = $xml->getResponse();
1714
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1715
			return $user_data;
1716
		}
1717
1718
		return false;
1719
	}
1720
1721
	/**
1722
	 * Get the wpcom email of the current|specified connected user.
1723
	 */
1724 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1725
		if ( ! $user_id ) {
1726
			$user_id = get_current_user_id();
1727
		}
1728
		Jetpack::load_xml_rpc_client();
1729
		$xml = new Jetpack_IXR_Client( array(
1730
			'user_id' => $user_id,
1731
		) );
1732
		$xml->query( 'wpcom.getUserEmail' );
1733
		if ( ! $xml->isError() ) {
1734
			return $xml->getResponse();
1735
		}
1736
		return false;
1737
	}
1738
1739
	/**
1740
	 * Get the wpcom email of the master user.
1741
	 */
1742
	public static function get_master_user_email() {
1743
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1744
		if ( $master_user_id ) {
1745
			return self::get_connected_user_email( $master_user_id );
1746
		}
1747
		return '';
1748
	}
1749
1750
	function current_user_is_connection_owner() {
1751
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1752
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1753
	}
1754
1755
	/**
1756
	 * Gets current user IP address.
1757
	 *
1758
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1759
	 *
1760
	 * @return string                  Current user IP address.
1761
	 */
1762
	public static function current_user_ip( $check_all_headers = false ) {
1763
		if ( $check_all_headers ) {
1764
			foreach ( array(
1765
				'HTTP_CF_CONNECTING_IP',
1766
				'HTTP_CLIENT_IP',
1767
				'HTTP_X_FORWARDED_FOR',
1768
				'HTTP_X_FORWARDED',
1769
				'HTTP_X_CLUSTER_CLIENT_IP',
1770
				'HTTP_FORWARDED_FOR',
1771
				'HTTP_FORWARDED',
1772
				'HTTP_VIA',
1773
			) as $key ) {
1774
				if ( ! empty( $_SERVER[ $key ] ) ) {
1775
					return $_SERVER[ $key ];
1776
				}
1777
			}
1778
		}
1779
1780
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1781
	}
1782
1783
	/**
1784
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1785
	 */
1786
	function extra_oembed_providers() {
1787
		// Cloudup: https://dev.cloudup.com/#oembed
1788
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1789
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1790
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1791
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1792
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1793
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1794
	}
1795
1796
	/**
1797
	 * Synchronize connected user role changes
1798
	 */
1799
	function user_role_change( $user_id ) {
1800
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1801
		Jetpack_Sync_Users::user_role_change( $user_id );
1802
	}
1803
1804
	/**
1805
	 * Loads the currently active modules.
1806
	 */
1807
	public static function load_modules() {
1808
		if (
1809
			! self::is_active()
1810
			&& ! self::is_development_mode()
1811
			&& ! self::is_onboarding()
1812
			&& (
1813
				! is_multisite()
1814
				|| ! get_site_option( 'jetpack_protect_active' )
1815
			)
1816
		) {
1817
			return;
1818
		}
1819
1820
		$version = Jetpack_Options::get_option( 'version' );
1821 View Code Duplication
		if ( ! $version ) {
1822
			$version = $old_version = JETPACK__VERSION . ':' . time();
1823
			/** This action is documented in class.jetpack.php */
1824
			do_action( 'updating_jetpack_version', $version, false );
1825
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1826
		}
1827
		list( $version ) = explode( ':', $version );
1828
1829
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1830
1831
		$modules_data = array();
1832
1833
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1834
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1835
			$updated_modules = array();
1836
			foreach ( $modules as $module ) {
1837
				$modules_data[ $module ] = Jetpack::get_module( $module );
1838
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1839
					continue;
1840
				}
1841
1842
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1843
					continue;
1844
				}
1845
1846
				$updated_modules[] = $module;
1847
			}
1848
1849
			$modules = array_diff( $modules, $updated_modules );
1850
		}
1851
1852
		$is_development_mode = Jetpack::is_development_mode();
1853
1854
		foreach ( $modules as $index => $module ) {
1855
			// If we're in dev mode, disable modules requiring a connection
1856
			if ( $is_development_mode ) {
1857
				// Prime the pump if we need to
1858
				if ( empty( $modules_data[ $module ] ) ) {
1859
					$modules_data[ $module ] = Jetpack::get_module( $module );
1860
				}
1861
				// If the module requires a connection, but we're in local mode, don't include it.
1862
				if ( $modules_data[ $module ]['requires_connection'] ) {
1863
					continue;
1864
				}
1865
			}
1866
1867
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1868
				continue;
1869
			}
1870
1871
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1872
				unset( $modules[ $index ] );
1873
				self::update_active_modules( array_values( $modules ) );
1874
				continue;
1875
			}
1876
1877
			/**
1878
			 * Fires when a specific module is loaded.
1879
			 * The dynamic part of the hook, $module, is the module slug.
1880
			 *
1881
			 * @since 1.1.0
1882
			 */
1883
			do_action( 'jetpack_module_loaded_' . $module );
1884
		}
1885
1886
		/**
1887
		 * Fires when all the modules are loaded.
1888
		 *
1889
		 * @since 1.1.0
1890
		 */
1891
		do_action( 'jetpack_modules_loaded' );
1892
1893
		// 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.
1894
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1895
	}
1896
1897
	/**
1898
	 * Check if Jetpack's REST API compat file should be included
1899
	 * @action plugins_loaded
1900
	 * @return null
1901
	 */
1902
	public function check_rest_api_compat() {
1903
		/**
1904
		 * Filters the list of REST API compat files to be included.
1905
		 *
1906
		 * @since 2.2.5
1907
		 *
1908
		 * @param array $args Array of REST API compat files to include.
1909
		 */
1910
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1911
1912
		if ( function_exists( 'bbpress' ) )
1913
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1914
1915
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1916
			require_once $_jetpack_rest_api_compat_include;
1917
	}
1918
1919
	/**
1920
	 * Gets all plugins currently active in values, regardless of whether they're
1921
	 * traditionally activated or network activated.
1922
	 *
1923
	 * @todo Store the result in core's object cache maybe?
1924
	 */
1925
	public static function get_active_plugins() {
1926
		$active_plugins = (array) get_option( 'active_plugins', array() );
1927
1928
		if ( is_multisite() ) {
1929
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1930
			// whereas active_plugins stores them in the values.
1931
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1932
			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...
1933
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1934
			}
1935
		}
1936
1937
		sort( $active_plugins );
1938
1939
		return array_unique( $active_plugins );
1940
	}
1941
1942
	/**
1943
	 * Gets and parses additional plugin data to send with the heartbeat data
1944
	 *
1945
	 * @since 3.8.1
1946
	 *
1947
	 * @return array Array of plugin data
1948
	 */
1949
	public static function get_parsed_plugin_data() {
1950
		if ( ! function_exists( 'get_plugins' ) ) {
1951
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1952
		}
1953
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1954
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1955
		$active_plugins = Jetpack::get_active_plugins();
1956
1957
		$plugins = array();
1958
		foreach ( $all_plugins as $path => $plugin_data ) {
1959
			$plugins[ $path ] = array(
1960
					'is_active' => in_array( $path, $active_plugins ),
1961
					'file'      => $path,
1962
					'name'      => $plugin_data['Name'],
1963
					'version'   => $plugin_data['Version'],
1964
					'author'    => $plugin_data['Author'],
1965
			);
1966
		}
1967
1968
		return $plugins;
1969
	}
1970
1971
	/**
1972
	 * Gets and parses theme data to send with the heartbeat data
1973
	 *
1974
	 * @since 3.8.1
1975
	 *
1976
	 * @return array Array of theme data
1977
	 */
1978
	public static function get_parsed_theme_data() {
1979
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1980
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1981
1982
		$themes = array();
1983
		foreach ( $all_themes as $slug => $theme_data ) {
1984
			$theme_headers = array();
1985
			foreach ( $header_keys as $header_key ) {
1986
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1987
			}
1988
1989
			$themes[ $slug ] = array(
1990
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1991
					'slug' => $slug,
1992
					'theme_root' => $theme_data->get_theme_root_uri(),
1993
					'parent' => $theme_data->parent(),
1994
					'headers' => $theme_headers
1995
			);
1996
		}
1997
1998
		return $themes;
1999
	}
2000
2001
	/**
2002
	 * Checks whether a specific plugin is active.
2003
	 *
2004
	 * We don't want to store these in a static variable, in case
2005
	 * there are switch_to_blog() calls involved.
2006
	 */
2007
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2008
		return in_array( $plugin, self::get_active_plugins() );
2009
	}
2010
2011
	/**
2012
	 * Check if Jetpack's Open Graph tags should be used.
2013
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2014
	 *
2015
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2016
	 * @action plugins_loaded
2017
	 * @return null
2018
	 */
2019
	public function check_open_graph() {
2020
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2021
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2022
		}
2023
2024
		$active_plugins = self::get_active_plugins();
2025
2026
		if ( ! empty( $active_plugins ) ) {
2027
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2028
				if ( in_array( $plugin, $active_plugins ) ) {
2029
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2030
					break;
2031
				}
2032
			}
2033
		}
2034
2035
		/**
2036
		 * Allow the addition of Open Graph Meta Tags to all pages.
2037
		 *
2038
		 * @since 2.0.3
2039
		 *
2040
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2041
		 */
2042
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2043
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2044
		}
2045
	}
2046
2047
	/**
2048
	 * Check if Jetpack's Twitter tags should be used.
2049
	 * If certain plugins are active, Jetpack's twitter 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_twitter_tags() {
2056
2057
		$active_plugins = self::get_active_plugins();
2058
2059
		if ( ! empty( $active_plugins ) ) {
2060
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2061
				if ( in_array( $plugin, $active_plugins ) ) {
2062
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2063
					break;
2064
				}
2065
			}
2066
		}
2067
2068
		/**
2069
		 * Allow Twitter Card Meta tags to be disabled.
2070
		 *
2071
		 * @since 2.6.0
2072
		 *
2073
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2074
		 */
2075
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2076
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2077
		}
2078
	}
2079
2080
	/**
2081
	 * Allows plugins to submit security reports.
2082
 	 *
2083
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2084
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2085
	 * @param array   $args         See definitions above
2086
	 */
2087
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2088
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2089
	}
2090
2091
/* Jetpack Options API */
2092
2093
	public static function get_option_names( $type = 'compact' ) {
2094
		return Jetpack_Options::get_option_names( $type );
2095
	}
2096
2097
	/**
2098
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2099
 	 *
2100
	 * @param string $name    Option name
2101
	 * @param mixed  $default (optional)
2102
	 */
2103
	public static function get_option( $name, $default = false ) {
2104
		return Jetpack_Options::get_option( $name, $default );
2105
	}
2106
2107
	/**
2108
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2109
 	 *
2110
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2111
	 * @param string $name  Option name
2112
	 * @param mixed  $value Option value
2113
	 */
2114
	public static function update_option( $name, $value ) {
2115
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2116
		return Jetpack_Options::update_option( $name, $value );
2117
	}
2118
2119
	/**
2120
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2121
 	 *
2122
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2123
	 * @param array $array array( option name => option value, ... )
2124
	 */
2125
	public static function update_options( $array ) {
2126
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2127
		return Jetpack_Options::update_options( $array );
2128
	}
2129
2130
	/**
2131
	 * Deletes the given option.  May be passed multiple option names as an array.
2132
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2133
	 *
2134
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2135
	 * @param string|array $names
2136
	 */
2137
	public static function delete_option( $names ) {
2138
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2139
		return Jetpack_Options::delete_option( $names );
2140
	}
2141
2142
	/**
2143
	 * Enters a user token into the user_tokens option
2144
	 *
2145
	 * @param int $user_id
2146
	 * @param string $token
2147
	 * return bool
2148
	 */
2149
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2150
		// not designed for concurrent updates
2151
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2152
		if ( ! is_array( $user_tokens ) )
2153
			$user_tokens = array();
2154
		$user_tokens[$user_id] = $token;
2155
		if ( $is_master_user ) {
2156
			$master_user = $user_id;
2157
			$options     = compact( 'user_tokens', 'master_user' );
2158
		} else {
2159
			$options = compact( 'user_tokens' );
2160
		}
2161
		return Jetpack_Options::update_options( $options );
2162
	}
2163
2164
	/**
2165
	 * Returns an array of all PHP files in the specified absolute path.
2166
	 * Equivalent to glob( "$absolute_path/*.php" ).
2167
	 *
2168
	 * @param string $absolute_path The absolute path of the directory to search.
2169
	 * @return array Array of absolute paths to the PHP files.
2170
	 */
2171
	public static function glob_php( $absolute_path ) {
2172
		if ( function_exists( 'glob' ) ) {
2173
			return glob( "$absolute_path/*.php" );
2174
		}
2175
2176
		$absolute_path = untrailingslashit( $absolute_path );
2177
		$files = array();
2178
		if ( ! $dir = @opendir( $absolute_path ) ) {
2179
			return $files;
2180
		}
2181
2182
		while ( false !== $file = readdir( $dir ) ) {
2183
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2184
				continue;
2185
			}
2186
2187
			$file = "$absolute_path/$file";
2188
2189
			if ( ! is_file( $file ) ) {
2190
				continue;
2191
			}
2192
2193
			$files[] = $file;
2194
		}
2195
2196
		closedir( $dir );
2197
2198
		return $files;
2199
	}
2200
2201
	public static function activate_new_modules( $redirect = false ) {
2202
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2203
			return;
2204
		}
2205
2206
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2207 View Code Duplication
		if ( ! $jetpack_old_version ) {
2208
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2209
			/** This action is documented in class.jetpack.php */
2210
			do_action( 'updating_jetpack_version', $version, false );
2211
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2212
		}
2213
2214
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2215
2216
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2217
			return;
2218
		}
2219
2220
		$active_modules     = Jetpack::get_active_modules();
2221
		$reactivate_modules = array();
2222
		foreach ( $active_modules as $active_module ) {
2223
			$module = Jetpack::get_module( $active_module );
2224
			if ( ! isset( $module['changed'] ) ) {
2225
				continue;
2226
			}
2227
2228
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2229
				continue;
2230
			}
2231
2232
			$reactivate_modules[] = $active_module;
2233
			Jetpack::deactivate_module( $active_module );
2234
		}
2235
2236
		$new_version = JETPACK__VERSION . ':' . time();
2237
		/** This action is documented in class.jetpack.php */
2238
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2239
		Jetpack_Options::update_options(
2240
			array(
2241
				'version'     => $new_version,
2242
				'old_version' => $jetpack_old_version,
2243
			)
2244
		);
2245
2246
		Jetpack::state( 'message', 'modules_activated' );
2247
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2985
		ob_end_clean();
2986
		Jetpack::catch_errors( false );
2987
2988
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2989 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2990
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2991
2992
			//Jump start is being dismissed send data to MC Stats
2993
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2994
2995
			$jetpack->do_stats( 'server_side' );
2996
		}
2997
2998
		if ( $redirect ) {
2999
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3000
		}
3001
		if ( $exit ) {
3002
			exit;
3003
		}
3004
		return true;
3005
	}
3006
3007
	function activate_module_actions( $module ) {
3008
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3009
	}
3010
3011
	public static function deactivate_module( $module ) {
3012
		/**
3013
		 * Fires when a module is deactivated.
3014
		 *
3015
		 * @since 1.9.0
3016
		 *
3017
		 * @param string $module Module slug.
3018
		 */
3019
		do_action( 'jetpack_pre_deactivate_module', $module );
3020
3021
		$jetpack = Jetpack::init();
3022
3023
		$active = Jetpack::get_active_modules();
3024
		$new    = array_filter( array_diff( $active, (array) $module ) );
3025
3026
		// A flag for Jump Start so it's not shown again.
3027 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
3028
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
3029
3030
			//Jump start is being dismissed send data to MC Stats
3031
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
3032
3033
			$jetpack->do_stats( 'server_side' );
3034
		}
3035
3036
		return self::update_active_modules( $new );
3037
	}
3038
3039
	public static function enable_module_configurable( $module ) {
3040
		$module = Jetpack::get_module_slug( $module );
3041
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3042
	}
3043
3044
	/**
3045
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3046
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3047
	 *
3048
	 * @param string $module Module slug
3049
	 * @return string $url module configuration URL
3050
	 */
3051
	public static function module_configuration_url( $module ) {
3052
		$module = Jetpack::get_module_slug( $module );
3053
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3054
		/**
3055
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3056
		 *
3057
		 * @since 6.9.0
3058
		 *
3059
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3060
		 */
3061
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3062
3063
		return $url;
3064
	}
3065
3066
/* Installation */
3067
	public static function bail_on_activation( $message, $deactivate = true ) {
3068
?>
3069
<!doctype html>
3070
<html>
3071
<head>
3072
<meta charset="<?php bloginfo( 'charset' ); ?>">
3073
<style>
3074
* {
3075
	text-align: center;
3076
	margin: 0;
3077
	padding: 0;
3078
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3079
}
3080
p {
3081
	margin-top: 1em;
3082
	font-size: 18px;
3083
}
3084
</style>
3085
<body>
3086
<p><?php echo esc_html( $message ); ?></p>
3087
</body>
3088
</html>
3089
<?php
3090
		if ( $deactivate ) {
3091
			$plugins = get_option( 'active_plugins' );
3092
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3093
			$update  = false;
3094
			foreach ( $plugins as $i => $plugin ) {
3095
				if ( $plugin === $jetpack ) {
3096
					$plugins[$i] = false;
3097
					$update = true;
3098
				}
3099
			}
3100
3101
			if ( $update ) {
3102
				update_option( 'active_plugins', array_filter( $plugins ) );
3103
			}
3104
		}
3105
		exit;
3106
	}
3107
3108
	/**
3109
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3110
	 * @static
3111
	 */
3112
	public static function plugin_activation( $network_wide ) {
3113
		Jetpack_Options::update_option( 'activated', 1 );
3114
3115
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3116
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3117
		}
3118
3119
		if ( $network_wide )
3120
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3121
3122
		// For firing one-off events (notices) immediately after activation
3123
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3124
3125
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3126
3127
		Jetpack::plugin_initialize();
3128
	}
3129
3130
	public static function get_activation_source( $referer_url ) {
3131
3132
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3133
			return array( 'wp-cli', null );
3134
		}
3135
3136
		$referer = parse_url( $referer_url );
3137
3138
		$source_type = 'unknown';
3139
		$source_query = null;
3140
3141
		if ( ! is_array( $referer ) ) {
3142
			return array( $source_type, $source_query );
3143
		}
3144
3145
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3146
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3147
3148
		if ( isset( $referer['query'] ) ) {
3149
			parse_str( $referer['query'], $query_parts );
3150
		} else {
3151
			$query_parts = array();
3152
		}
3153
3154
		if ( $plugins_path === $referer['path'] ) {
3155
			$source_type = 'list';
3156
		} elseif ( $plugins_install_path === $referer['path'] ) {
3157
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3158
			switch( $tab ) {
3159
				case 'popular':
3160
					$source_type = 'popular';
3161
					break;
3162
				case 'recommended':
3163
					$source_type = 'recommended';
3164
					break;
3165
				case 'favorites':
3166
					$source_type = 'favorites';
3167
					break;
3168
				case 'search':
3169
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3170
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3171
					break;
3172
				default:
3173
					$source_type = 'featured';
3174
			}
3175
		}
3176
3177
		return array( $source_type, $source_query );
3178
	}
3179
3180
	/**
3181
	 * Runs before bumping version numbers up to a new version
3182
	 * @param  string $version    Version:timestamp
3183
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3184
	 * @return null              [description]
3185
	 */
3186
	public static function do_version_bump( $version, $old_version ) {
3187
		if ( ! $old_version ) { // For new sites
3188
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3189
		}
3190
	}
3191
3192
	/**
3193
	 * Sets the internal version number and activation state.
3194
	 * @static
3195
	 */
3196
	public static function plugin_initialize() {
3197
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3198
			Jetpack_Options::update_option( 'activated', 2 );
3199
		}
3200
3201 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3202
			$version = $old_version = JETPACK__VERSION . ':' . time();
3203
			/** This action is documented in class.jetpack.php */
3204
			do_action( 'updating_jetpack_version', $version, false );
3205
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3206
		}
3207
3208
		Jetpack::load_modules();
3209
3210
		Jetpack_Options::delete_option( 'do_activate' );
3211
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3212
	}
3213
3214
	/**
3215
	 * Removes all connection options
3216
	 * @static
3217
	 */
3218
	public static function plugin_deactivation( ) {
3219
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3220
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3221
			Jetpack_Network::init()->deactivate();
3222
		} else {
3223
			Jetpack::disconnect( false );
3224
			//Jetpack_Heartbeat::init()->deactivate();
3225
		}
3226
	}
3227
3228
	/**
3229
	 * Disconnects from the Jetpack servers.
3230
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3231
	 * @static
3232
	 */
3233
	public static function disconnect( $update_activated_state = true ) {
3234
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3235
		Jetpack::clean_nonces( true );
3236
3237
		// If the site is in an IDC because sync is not allowed,
3238
		// let's make sure to not disconnect the production site.
3239
		if ( ! self::validate_sync_error_idc_option() ) {
3240
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3241
			Jetpack::load_xml_rpc_client();
3242
			$xml = new Jetpack_IXR_Client();
3243
			$xml->query( 'jetpack.deregister' );
3244
		}
3245
3246
		Jetpack_Options::delete_option(
3247
			array(
3248
				'blog_token',
3249
				'user_token',
3250
				'user_tokens',
3251
				'master_user',
3252
				'time_diff',
3253
				'fallback_no_verify_ssl_certs',
3254
			)
3255
		);
3256
3257
		Jetpack_IDC::clear_all_idc_options();
3258
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3259
3260
		if ( $update_activated_state ) {
3261
			Jetpack_Options::update_option( 'activated', 4 );
3262
		}
3263
3264
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3265
			// Check then record unique disconnection if site has never been disconnected previously
3266
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3267
				$jetpack_unique_connection['disconnected'] = 1;
3268
			} else {
3269
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3270
					//track unique disconnect
3271
					$jetpack = Jetpack::init();
3272
3273
					$jetpack->stat( 'connections', 'unique-disconnect' );
3274
					$jetpack->do_stats( 'server_side' );
3275
				}
3276
				// increment number of times disconnected
3277
				$jetpack_unique_connection['disconnected'] += 1;
3278
			}
3279
3280
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3281
		}
3282
3283
		// Delete cached connected user data
3284
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3285
		delete_transient( $transient_key );
3286
3287
		// Delete all the sync related data. Since it could be taking up space.
3288
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3289
		Jetpack_Sync_Sender::get_instance()->uninstall();
3290
3291
		// Disable the Heartbeat cron
3292
		Jetpack_Heartbeat::init()->deactivate();
3293
	}
3294
3295
	/**
3296
	 * Unlinks the current user from the linked WordPress.com user
3297
	 */
3298
	public static function unlink_user( $user_id = null ) {
3299
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3300
			return false;
3301
3302
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3303
3304
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3305
			return false;
3306
3307
		if ( ! isset( $tokens[ $user_id ] ) )
3308
			return false;
3309
3310
		Jetpack::load_xml_rpc_client();
3311
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3312
		$xml->query( 'jetpack.unlink_user', $user_id );
3313
3314
		unset( $tokens[ $user_id ] );
3315
3316
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3317
3318
		/**
3319
		 * Fires after the current user has been unlinked from WordPress.com.
3320
		 *
3321
		 * @since 4.1.0
3322
		 *
3323
		 * @param int $user_id The current user's ID.
3324
		 */
3325
		do_action( 'jetpack_unlinked_user', $user_id );
3326
3327
		return true;
3328
	}
3329
3330
	/**
3331
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3332
	 */
3333
	public static function try_registration() {
3334
		// The user has agreed to the TOS at some point by now.
3335
		Jetpack_Options::update_option( 'tos_agreed', true );
3336
3337
		// Let's get some testing in beta versions and such.
3338
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3339
			// Before attempting to connect, let's make sure that the domains are viable.
3340
			$domains_to_check = array_unique( array(
3341
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3342
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3343
			) );
3344
			foreach ( $domains_to_check as $domain ) {
3345
				$result = Jetpack_Data::is_usable_domain( $domain );
3346
				if ( is_wp_error( $result ) ) {
3347
					return $result;
3348
				}
3349
			}
3350
		}
3351
3352
		$result = Jetpack::register();
3353
3354
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3355
		if ( ! $result || is_wp_error( $result ) ) {
3356
			return $result;
3357
		} else {
3358
			return true;
3359
		}
3360
	}
3361
3362
	/**
3363
	 * Tracking an internal event log. Try not to put too much chaff in here.
3364
	 *
3365
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3366
	 */
3367
	public static function log( $code, $data = null ) {
3368
		// only grab the latest 200 entries
3369
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3370
3371
		// Append our event to the log
3372
		$log_entry = array(
3373
			'time'    => time(),
3374
			'user_id' => get_current_user_id(),
3375
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3376
			'code'    => $code,
3377
		);
3378
		// Don't bother storing it unless we've got some.
3379
		if ( ! is_null( $data ) ) {
3380
			$log_entry['data'] = $data;
3381
		}
3382
		$log[] = $log_entry;
3383
3384
		// Try add_option first, to make sure it's not autoloaded.
3385
		// @todo: Add an add_option method to Jetpack_Options
3386
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3387
			Jetpack_Options::update_option( 'log', $log );
3388
		}
3389
3390
		/**
3391
		 * Fires when Jetpack logs an internal event.
3392
		 *
3393
		 * @since 3.0.0
3394
		 *
3395
		 * @param array $log_entry {
3396
		 *	Array of details about the log entry.
3397
		 *
3398
		 *	@param string time Time of the event.
3399
		 *	@param int user_id ID of the user who trigerred the event.
3400
		 *	@param int blog_id Jetpack Blog ID.
3401
		 *	@param string code Unique name for the event.
3402
		 *	@param string data Data about the event.
3403
		 * }
3404
		 */
3405
		do_action( 'jetpack_log_entry', $log_entry );
3406
	}
3407
3408
	/**
3409
	 * Get the internal event log.
3410
	 *
3411
	 * @param $event (string) - only return the specific log events
3412
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3413
	 *
3414
	 * @return array of log events || WP_Error for invalid params
3415
	 */
3416
	public static function get_log( $event = false, $num = false ) {
3417
		if ( $event && ! is_string( $event ) ) {
3418
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3419
		}
3420
3421
		if ( $num && ! is_numeric( $num ) ) {
3422
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3423
		}
3424
3425
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3426
3427
		// If nothing set - act as it did before, otherwise let's start customizing the output
3428
		if ( ! $num && ! $event ) {
3429
			return $entire_log;
3430
		} else {
3431
			$entire_log = array_reverse( $entire_log );
3432
		}
3433
3434
		$custom_log_output = array();
3435
3436
		if ( $event ) {
3437
			foreach ( $entire_log as $log_event ) {
3438
				if ( $event == $log_event[ 'code' ] ) {
3439
					$custom_log_output[] = $log_event;
3440
				}
3441
			}
3442
		} else {
3443
			$custom_log_output = $entire_log;
3444
		}
3445
3446
		if ( $num ) {
3447
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3448
		}
3449
3450
		return $custom_log_output;
3451
	}
3452
3453
	/**
3454
	 * Log modification of important settings.
3455
	 */
3456
	public static function log_settings_change( $option, $old_value, $value ) {
3457
		switch( $option ) {
3458
			case 'jetpack_sync_non_public_post_stati':
3459
				self::log( $option, $value );
3460
				break;
3461
		}
3462
	}
3463
3464
	/**
3465
	 * Return stat data for WPCOM sync
3466
	 */
3467
	public static function get_stat_data( $encode = true, $extended = true ) {
3468
		$data = Jetpack_Heartbeat::generate_stats_array();
3469
3470
		if ( $extended ) {
3471
			$additional_data = self::get_additional_stat_data();
3472
			$data = array_merge( $data, $additional_data );
3473
		}
3474
3475
		if ( $encode ) {
3476
			return json_encode( $data );
3477
		}
3478
3479
		return $data;
3480
	}
3481
3482
	/**
3483
	 * Get additional stat data to sync to WPCOM
3484
	 */
3485
	public static function get_additional_stat_data( $prefix = '' ) {
3486
		$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...
3487
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3488
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3489
		$return["{$prefix}site-count"]     = 0;
3490
3491
		if ( function_exists( 'get_blog_count' ) ) {
3492
			$return["{$prefix}site-count"] = get_blog_count();
3493
		}
3494
		return $return;
3495
	}
3496
3497
	private static function get_site_user_count() {
3498
		global $wpdb;
3499
3500
		if ( function_exists( 'wp_is_large_network' ) ) {
3501
			if ( wp_is_large_network( 'users' ) ) {
3502
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3503
			}
3504
		}
3505 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3506
			// It wasn't there, so regenerate the data and save the transient
3507
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3508
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3509
		}
3510
		return $user_count;
3511
	}
3512
3513
	/* Admin Pages */
3514
3515
	function admin_init() {
3516
		// If the plugin is not connected, display a connect message.
3517
		if (
3518
			// the plugin was auto-activated and needs its candy
3519
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3520
		||
3521
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3522
			! Jetpack_Options::get_option( 'activated' )
3523
		) {
3524
			Jetpack::plugin_initialize();
3525
		}
3526
3527
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3528
			Jetpack_Connection_Banner::init();
3529
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3530
			// Upgrade: 1.1 -> 1.1.1
3531
			// Check and see if host can verify the Jetpack servers' SSL certificate
3532
			$args = array();
3533
			Jetpack_Client::_wp_remote_request(
3534
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3535
				$args,
3536
				true
3537
			);
3538
		}
3539
3540
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3541
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3542
		}
3543
3544
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3545
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3546
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3547
3548
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3549
			// Artificially throw errors in certain whitelisted cases during plugin activation
3550
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3551
		}
3552
3553
		// Add custom column in wp-admin/users.php to show whether user is linked.
3554
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3555
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3556
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3557
	}
3558
3559
	function admin_body_class( $admin_body_class = '' ) {
3560
		$classes = explode( ' ', trim( $admin_body_class ) );
3561
3562
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3563
3564
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3565
		return " $admin_body_class ";
3566
	}
3567
3568
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3569
		return $admin_body_class . ' jetpack-pagestyles ';
3570
	}
3571
3572
	/**
3573
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3574
	 * This function artificially throws errors for such cases (whitelisted).
3575
	 *
3576
	 * @param string $plugin The activated plugin.
3577
	 */
3578
	function throw_error_on_activate_plugin( $plugin ) {
3579
		$active_modules = Jetpack::get_active_modules();
3580
3581
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3582
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3583
			$throw = false;
3584
3585
			// Try and make sure it really was the stats plugin
3586
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3587
				if ( 'stats.php' == basename( $plugin ) ) {
3588
					$throw = true;
3589
				}
3590
			} else {
3591
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3592
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3593
					$throw = true;
3594
				}
3595
			}
3596
3597
			if ( $throw ) {
3598
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3599
			}
3600
		}
3601
	}
3602
3603
	function intercept_plugin_error_scrape_init() {
3604
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3605
	}
3606
3607
	function intercept_plugin_error_scrape( $action, $result ) {
3608
		if ( ! $result ) {
3609
			return;
3610
		}
3611
3612
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3613
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3614
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3615
			}
3616
		}
3617
	}
3618
3619
	function add_remote_request_handlers() {
3620
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3621
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3622
	}
3623
3624
	function remote_request_handlers() {
3625
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

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

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
6732
	 * @return mixed
6733
	 */
6734
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6735
		if ( ! is_array( $sorted ) ) {
6736
			return $sorted;
6737
		}
6738
6739
		foreach ( $sorted as $box_context => $ids ) {
6740
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6741
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6742
				continue;
6743
			}
6744
6745
			$ids_array = explode( ',', $ids );
6746
			$key = array_search( 'dashboard_stats', $ids_array );
6747
6748
			if ( false !== $key ) {
6749
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6750
				$ids_array[ $key ] = 'jetpack_summary_widget';
6751
				$sorted[ $box_context ] = implode( ',', $ids_array );
6752
				// We've found it, stop searching, and just return.
6753
				break;
6754
			}
6755
		}
6756
6757
		return $sorted;
6758
	}
6759
6760
	public static function dashboard_widget() {
6761
		/**
6762
		 * Fires when the dashboard is loaded.
6763
		 *
6764
		 * @since 3.4.0
6765
		 */
6766
		do_action( 'jetpack_dashboard_widget' );
6767
	}
6768
6769
	public static function dashboard_widget_footer() {
6770
		?>
6771
		<footer>
6772
6773
		<div class="protect">
6774
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6775
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6776
				<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>
6777
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6778
				<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' ); ?>">
6779
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6780
				</a>
6781
			<?php else : ?>
6782
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6783
			<?php endif; ?>
6784
		</div>
6785
6786
		<div class="akismet">
6787
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6788
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6789
				<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>
6790
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6791
				<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">
6792
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6793
				</a>
6794
			<?php else : ?>
6795
				<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>
6796
			<?php endif; ?>
6797
		</div>
6798
6799
		</footer>
6800
		<?php
6801
	}
6802
6803
	/**
6804
	 * Return string containing the Jetpack logo.
6805
	 *
6806
	 * @since 3.9.0
6807
	 *
6808
	 * @param bool $logotype Should we use the full logotype (logo + text). Default to false.
6809
	 *
6810
	 * @return string
6811
	 */
6812
	public static function get_jp_emblem( $logotype = false ) {
6813
		$logo = '<path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/>';
6814
		$text = '
6815
<path d="M41.3,26.6c-0.5-0.7-0.9-1.4-1.3-2.1c2.3-1.4,3-2.5,3-4.6V8h-3V6h6v13.4C46,22.8,45,24.8,41.3,26.6z" />
6816
<path d="M65,18.4c0,1.1,0.8,1.3,1.4,1.3c0.5,0,2-0.2,2.6-0.4v2.1c-0.9,0.3-2.5,0.5-3.7,0.5c-1.5,0-3.2-0.5-3.2-3.1V12H60v-2h2.1V7.1 H65V10h4v2h-4V18.4z" />
6817
<path d="M71,10h3v1.3c1.1-0.8,1.9-1.3,3.3-1.3c2.5,0,4.5,1.8,4.5,5.6s-2.2,6.3-5.8,6.3c-0.9,0-1.3-0.1-2-0.3V28h-3V10z M76.5,12.3 c-0.8,0-1.6,0.4-2.5,1.2v5.9c0.6,0.1,0.9,0.2,1.8,0.2c2,0,3.2-1.3,3.2-3.9C79,13.4,78.1,12.3,76.5,12.3z" />
6818
<path d="M93,22h-3v-1.5c-0.9,0.7-1.9,1.5-3.5,1.5c-1.5,0-3.1-1.1-3.1-3.2c0-2.9,2.5-3.4,4.2-3.7l2.4-0.3v-0.3c0-1.5-0.5-2.3-2-2.3 c-0.7,0-2.3,0.5-3.7,1.1L84,11c1.2-0.4,3-1,4.4-1c2.7,0,4.6,1.4,4.6,4.7L93,22z M90,16.4l-2.2,0.4c-0.7,0.1-1.4,0.5-1.4,1.6 c0,0.9,0.5,1.4,1.3,1.4s1.5-0.5,2.3-1V16.4z" />
6819
<path d="M104.5,21.3c-1.1,0.4-2.2,0.6-3.5,0.6c-4.2,0-5.9-2.4-5.9-5.9c0-3.7,2.3-6,6.1-6c1.4,0,2.3,0.2,3.2,0.5V13 c-0.8-0.3-2-0.6-3.2-0.6c-1.7,0-3.2,0.9-3.2,3.6c0,2.9,1.5,3.8,3.3,3.8c0.9,0,1.9-0.2,3.2-0.7V21.3z" />
6820
<path d="M110,15.2c0.2-0.3,0.2-0.8,3.8-5.2h3.7l-4.6,5.7l5,6.3h-3.7l-4.2-5.8V22h-3V6h3V15.2z" />
6821
<path d="M58.5,21.3c-1.5,0.5-2.7,0.6-4.2,0.6c-3.6,0-5.8-1.8-5.8-6c0-3.1,1.9-5.9,5.5-5.9s4.9,2.5,4.9,4.9c0,0.8,0,1.5-0.1,2h-7.3 c0.1,2.5,1.5,2.8,3.6,2.8c1.1,0,2.2-0.3,3.4-0.7C58.5,19,58.5,21.3,58.5,21.3z M56,15c0-1.4-0.5-2.9-2-2.9c-1.4,0-2.3,1.3-2.4,2.9 C51.6,15,56,15,56,15z" />
6822
		';
6823
6824
		return sprintf(
6825
			'<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 %1$s 32">%2$s</svg>',
6826
			( true === $logotype ? '118' : '32' ),
6827
			( true === $logotype ? $logo . $text : $logo )
6828
		);
6829
	}
6830
6831
	/*
6832
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6833
	 */
6834
	function jetpack_icon_user_connected( $columns ) {
6835
		$columns['user_jetpack'] = '';
6836
		return $columns;
6837
	}
6838
6839
	/*
6840
	 * Show Jetpack icon if the user is linked.
6841
	 */
6842
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6843
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6844
			$emblem_html = sprintf(
6845
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6846
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6847
				Jetpack::get_jp_emblem()
6848
			);
6849
			return $emblem_html;
6850
		}
6851
6852
		return $val;
6853
	}
6854
6855
	/*
6856
	 * Style the Jetpack user column
6857
	 */
6858
	function jetpack_user_col_style() {
6859
		global $current_screen;
6860
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6861
			<style>
6862
				.fixed .column-user_jetpack {
6863
					width: 21px;
6864
				}
6865
				.jp-emblem-user-admin svg {
6866
					width: 20px;
6867
					height: 20px;
6868
				}
6869
				.jp-emblem-user-admin path {
6870
					fill: #00BE28;
6871
				}
6872
			</style>
6873
		<?php }
6874
	}
6875
6876
	/**
6877
	 * Checks if Akismet is active and working.
6878
	 *
6879
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6880
	 * that implied usage of methods present since more recent version.
6881
	 * See https://github.com/Automattic/jetpack/pull/9585
6882
	 *
6883
	 * @since  5.1.0
6884
	 *
6885
	 * @return bool True = Akismet available. False = Aksimet not available.
6886
	 */
6887
	public static function is_akismet_active() {
6888
		static $status = null;
6889
6890
		if ( ! is_null( $status ) ) {
6891
			return $status;
6892
		}
6893
6894
		// Check if a modern version of Akismet is active.
6895
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6896
			$status = false;
6897
			return $status;
6898
		}
6899
6900
		// Make sure there is a key known to Akismet at all before verifying key.
6901
		$akismet_key = Akismet::get_api_key();
6902
		if ( ! $akismet_key ) {
6903
			$status = false;
6904
			return $status;
6905
		}
6906
6907
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6908
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6909
6910
		// 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.
6911
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6912
		// We cache the result of the Akismet key verification for ten minutes.
6913
		if ( ! $akismet_key_state || $recheck ) {
6914
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6915
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6916
		}
6917
6918
		$status = 'valid' === $akismet_key_state;
6919
6920
		return $status;
6921
	}
6922
6923
	/**
6924
	 * Checks if one or more function names is in debug_backtrace
6925
	 *
6926
	 * @param $names Mixed string name of function or array of string names of functions
6927
	 *
6928
	 * @return bool
6929
	 */
6930
	public static function is_function_in_backtrace( $names ) {
6931
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6932
		if ( ! is_array( $names ) ) {
6933
			$names = array( $names );
6934
		}
6935
		$names_as_keys = array_flip( $names );
6936
6937
		//Do check in constant O(1) time for PHP5.5+
6938
		if ( function_exists( 'array_column' ) ) {
6939
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6940
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6941
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6942
			return ! empty ( $intersection );
6943
		}
6944
6945
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6946
		foreach ( $backtrace as $call ) {
6947
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6948
				return true;
6949
			}
6950
		}
6951
		return false;
6952
	}
6953
6954
	/**
6955
	 * Given a minified path, and a non-minified path, will return
6956
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6957
	 *
6958
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6959
	 * root Jetpack directory.
6960
	 *
6961
	 * @since 5.6.0
6962
	 *
6963
	 * @param string $min_path
6964
	 * @param string $non_min_path
6965
	 * @return string The URL to the file
6966
	 */
6967
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6968
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
6969
			? $non_min_path
6970
			: $min_path;
6971
6972
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6973
	}
6974
6975
	/**
6976
	 * Checks for whether Jetpack Backup & Scan is enabled.
6977
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6978
	 * @return bool|int|mixed
6979
	 */
6980
	public static function is_rewind_enabled() {
6981
		if ( ! Jetpack::is_active() ) {
6982
			return false;
6983
		}
6984
6985
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6986
		if ( false === $rewind_enabled ) {
6987
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6988
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6989
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6990
				&& ! empty( $rewind_data['state'] )
6991
				&& 'active' === $rewind_data['state'] )
6992
				? 1
6993
				: 0;
6994
6995
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6996
		}
6997
		return $rewind_enabled;
6998
	}
6999
7000
	/**
7001
	 * Checks whether or not TOS has been agreed upon.
7002
	 * Will return true if a user has clicked to register, or is already connected.
7003
	 */
7004
	public static function jetpack_tos_agreed() {
7005
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7006
	}
7007
7008
	/**
7009
	 * Handles activating default modules as well general cleanup for the new connection.
7010
	 *
7011
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7012
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7013
	 * @param boolean $send_state_messages          Whether to send state messages.
7014
	 * @return void
7015
	 */
7016
	public static function handle_post_authorization_actions(
7017
		$activate_sso = false,
7018
		$redirect_on_activation_error = false,
7019
		$send_state_messages = true
7020
	) {
7021
		$other_modules = $activate_sso
7022
			? array( 'sso' )
7023
			: array();
7024
7025
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7026
			Jetpack::delete_active_modules();
7027
7028
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7029
		} else {
7030
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7031
		}
7032
7033
		// Since this is a fresh connection, be sure to clear out IDC options
7034
		Jetpack_IDC::clear_all_idc_options();
7035
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7036
7037
		// Start nonce cleaner
7038
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7039
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7040
7041
		if ( $send_state_messages ) {
7042
			Jetpack::state( 'message', 'authorized' );
7043
		}
7044
	}
7045
7046
	/**
7047
	 * Returns a boolean for whether backups UI should be displayed or not.
7048
	 *
7049
	 * @return bool Should backups UI be displayed?
7050
	 */
7051
	public static function show_backups_ui() {
7052
		/**
7053
		 * Whether UI for backups should be displayed.
7054
		 *
7055
		 * @since 6.5.0
7056
		 *
7057
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7058
		 */
7059
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7060
	}
7061
7062
	/*
7063
	 * Deprecated manage functions
7064
	 */
7065
	function prepare_manage_jetpack_notice() {
7066
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7067
	}
7068
	function manage_activate_screen() {
7069
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7070
	}
7071
	function admin_jetpack_manage_notice() {
7072
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7073
	}
7074
	function opt_out_jetpack_manage_url() {
7075
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7076
	}
7077
	function opt_in_jetpack_manage_url() {
7078
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7079
	}
7080
	function opt_in_jetpack_manage_notice() {
7081
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7082
	}
7083
	function can_display_jetpack_manage_notice() {
7084
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7085
	}
7086
}
7087