Completed
Push — add/general-oembed-load ( e3e0ad )
by Jeremy
112:39 queued 102:22
created

Jetpack::extra_oembed_providers()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 9
rs 9.9666
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
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
634
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
635
636
		// JITM AJAX callback function
637
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
638
639
		// Universal ajax callback for all tracking events triggered via js
640
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
641
642
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
643
644
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
645
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
646
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
647
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
648
649
		/**
650
		 * These actions run checks to load additional files.
651
		 * They check for external files or plugins, so they need to run as late as possible.
652
		 */
653
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
654
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
655
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
656
657
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
658
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
659
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
660
661
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
662
663
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
664
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
665
666
		// A filter to control all just in time messages
667
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
668
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
669
670
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
671
		// We should make sure to only do this for front end links.
672
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
673
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
674
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
675
676
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
677
			//so they point moderation links on emails to Calypso
678
			jetpack_require_lib( 'functions.wp-notify' );
679
		}
680
681
		// Update the Jetpack plan from API on heartbeats
682
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
683
684
		/**
685
		 * This is the hack to concatenate all css files into one.
686
		 * For description and reasoning see the implode_frontend_css method
687
		 *
688
		 * Super late priority so we catch all the registered styles
689
		 */
690
		if( !is_admin() ) {
691
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
692
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
693
		}
694
695
		/**
696
		 * These are sync actions that we need to keep track of for jitms
697
		 */
698
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
699
700
		// Actually push the stats on shutdown.
701
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
702
			add_action( 'shutdown', array( $this, 'push_stats' ) );
703
		}
704
	}
705
706
	/**
707
	 * This is ported over from the manage module, which has been deprecated and baked in here.
708
	 *
709
	 * @param $domains
710
	 */
711
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
712
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
713
	}
714
715
	/**
716
	 * Return $domains, with 'wordpress.com' appended.
717
	 * This is ported over from the manage module, which has been deprecated and baked in here.
718
	 *
719
	 * @param $domains
720
	 * @return array
721
	 */
722
	function allow_wpcom_domain( $domains ) {
723
		if ( empty( $domains ) ) {
724
			$domains = array();
725
		}
726
		$domains[] = 'wordpress.com';
727
		return array_unique( $domains );
728
	}
729
730
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
731
		$post = get_post( $post_id );
732
733
		if ( empty( $post ) ) {
734
			return $default_url;
735
		}
736
737
		$post_type = $post->post_type;
738
739
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
740
		// https://en.support.wordpress.com/custom-post-types/
741
		$allowed_post_types = array(
742
			'post' => 'post',
743
			'page' => 'page',
744
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
745
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
746
		);
747
748
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
749
			return $default_url;
750
		}
751
752
		$path_prefix = $allowed_post_types[ $post_type ];
753
754
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
755
756
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
757
	}
758
759
	function point_edit_comment_links_to_calypso( $url ) {
760
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
761
		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...
762
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
763
			Jetpack::build_raw_urls( get_home_url() ),
764
			$query_args['amp;c']
765
		) );
766
	}
767
768
	function jetpack_track_last_sync_callback( $params ) {
769
		/**
770
		 * Filter to turn off jitm caching
771
		 *
772
		 * @since 5.4.0
773
		 *
774
		 * @param bool false Whether to cache just in time messages
775
		 */
776
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
777
			return $params;
778
		}
779
780
		if ( is_array( $params ) && isset( $params[0] ) ) {
781
			$option = $params[0];
782
			if ( 'active_plugins' === $option ) {
783
				// use the cache if we can, but not terribly important if it gets evicted
784
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
785
			}
786
		}
787
788
		return $params;
789
	}
790
791
	function jetpack_connection_banner_callback() {
792
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
793
794
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
795
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
796
			wp_send_json_success();
797
		}
798
799
		wp_die();
800
	}
801
802
	/**
803
	 * Removes all XML-RPC methods that are not `jetpack.*`.
804
	 * Only used in our alternate XML-RPC endpoint, where we want to
805
	 * ensure that Core and other plugins' methods are not exposed.
806
	 *
807
	 * @param array $methods
808
	 * @return array filtered $methods
809
	 */
810
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
811
		$jetpack_methods = array();
812
813
		foreach ( $methods as $method => $callback ) {
814
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
815
				$jetpack_methods[ $method ] = $callback;
816
			}
817
		}
818
819
		return $jetpack_methods;
820
	}
821
822
	/**
823
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
824
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
825
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
826
	 * which is accessible via a different URI. Most of the below is copied directly
827
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
828
	 */
829
	function alternate_xmlrpc() {
830
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
831
		global $HTTP_RAW_POST_DATA;
832
833
		// Some browser-embedded clients send cookies. We don't want them.
834
		$_COOKIE = array();
835
836
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
837
		// but we can do it ourself.
838
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
839
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
840
		}
841
842
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
843
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
844
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
845
		}
846
847
		// phpcs:enable
848
849
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
850
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
851
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
852
853
		/**
854
		 * Filters the class used for handling XML-RPC requests.
855
		 *
856
		 * @since 3.1.0
857
		 *
858
		 * @param string $class The name of the XML-RPC server class.
859
		 */
860
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
861
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
862
863
		// Fire off the request
864
		nocache_headers();
865
		$wp_xmlrpc_server->serve_request();
866
867
		exit;
868
	}
869
870
	function jetpack_admin_ajax_tracks_callback() {
871
		// Check for nonce
872
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
873
			wp_die( 'Permissions check failed.' );
874
		}
875
876
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
877
			wp_die( 'No valid event name or type.' );
878
		}
879
880
		$tracks_data = array();
881
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
882
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
883
				$tracks_data = $_REQUEST['tracksEventProp'];
884
			} else {
885
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
886
			}
887
		}
888
889
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
890
		wp_send_json_success();
891
		wp_die();
892
	}
893
894
	/**
895
	 * The callback for the JITM ajax requests.
896
	 */
897
	function jetpack_jitm_ajax_callback() {
898
		// Check for nonce
899
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
900
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
901
		}
902
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
903
			$module_slug = $_REQUEST['jitmModule'];
904
			Jetpack::log( 'activate', $module_slug );
905
			Jetpack::activate_module( $module_slug, false, false );
906
			Jetpack::state( 'message', 'no_message' );
907
908
			//A Jetpack module is being activated through a JITM, track it
909
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
910
			$this->do_stats( 'server_side' );
911
912
			wp_send_json_success();
913
		}
914
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
915
			// get the hide_jitm options array
916
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
917
			$module_slug = $_REQUEST['jitmModule'];
918
919
			if( ! $jetpack_hide_jitm ) {
920
				$jetpack_hide_jitm = array(
921
					$module_slug => 'hide'
922
				);
923
			} else {
924
				$jetpack_hide_jitm[$module_slug] = 'hide';
925
			}
926
927
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
928
929
			//jitm is being dismissed forever, track it
930
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
931
			$this->do_stats( 'server_side' );
932
933
			wp_send_json_success();
934
		}
935 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
936
			$module_slug = $_REQUEST['jitmModule'];
937
938
			// User went to WordPress.com, track this
939
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
940
			$this->do_stats( 'server_side' );
941
942
			wp_send_json_success();
943
		}
944 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
945
			$track = $_REQUEST['jitmModule'];
946
947
			// User is viewing JITM, track it.
948
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
949
			$this->do_stats( 'server_side' );
950
951
			wp_send_json_success();
952
		}
953
	}
954
955
	/**
956
	 * If there are any stats that need to be pushed, but haven't been, push them now.
957
	 */
958
	function push_stats() {
959
		if ( ! empty( $this->stats ) ) {
960
			$this->do_stats( 'server_side' );
961
		}
962
	}
963
964
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
965
		switch( $cap ) {
966
			case 'jetpack_connect' :
967
			case 'jetpack_reconnect' :
968
				if ( Jetpack::is_development_mode() ) {
969
					$caps = array( 'do_not_allow' );
970
					break;
971
				}
972
				/**
973
				 * Pass through. If it's not development mode, these should match disconnect.
974
				 * Let users disconnect if it's development mode, just in case things glitch.
975
				 */
976
			case 'jetpack_disconnect' :
977
				/**
978
				 * In multisite, can individual site admins manage their own connection?
979
				 *
980
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
981
				 */
982
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
983
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
984
						/**
985
						 * We need to update the option name -- it's terribly unclear which
986
						 * direction the override goes.
987
						 *
988
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
989
						 */
990
						$caps = array( 'do_not_allow' );
991
						break;
992
					}
993
				}
994
995
				$caps = array( 'manage_options' );
996
				break;
997
			case 'jetpack_manage_modules' :
998
			case 'jetpack_activate_modules' :
999
			case 'jetpack_deactivate_modules' :
1000
				$caps = array( 'manage_options' );
1001
				break;
1002
			case 'jetpack_configure_modules' :
1003
				$caps = array( 'manage_options' );
1004
				break;
1005
			case 'jetpack_manage_autoupdates' :
1006
				$caps = array(
1007
					'manage_options',
1008
					'update_plugins',
1009
				);
1010
				break;
1011
			case 'jetpack_network_admin_page':
1012
			case 'jetpack_network_settings_page':
1013
				$caps = array( 'manage_network_plugins' );
1014
				break;
1015
			case 'jetpack_network_sites_page':
1016
				$caps = array( 'manage_sites' );
1017
				break;
1018
			case 'jetpack_admin_page' :
1019
				if ( Jetpack::is_development_mode() ) {
1020
					$caps = array( 'manage_options' );
1021
					break;
1022
				} else {
1023
					$caps = array( 'read' );
1024
				}
1025
				break;
1026
			case 'jetpack_connect_user' :
1027
				if ( Jetpack::is_development_mode() ) {
1028
					$caps = array( 'do_not_allow' );
1029
					break;
1030
				}
1031
				$caps = array( 'read' );
1032
				break;
1033
		}
1034
		return $caps;
1035
	}
1036
1037
	function require_jetpack_authentication() {
1038
		// Don't let anyone authenticate
1039
		$_COOKIE = array();
1040
		remove_all_filters( 'authenticate' );
1041
		remove_all_actions( 'wp_login_failed' );
1042
1043
		if ( Jetpack::is_active() ) {
1044
			// Allow Jetpack authentication
1045
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1046
		}
1047
	}
1048
1049
	/**
1050
	 * Load language files
1051
	 * @action plugins_loaded
1052
	 */
1053
	public static function plugin_textdomain() {
1054
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1055
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1056
	}
1057
1058
	/**
1059
	 * Register assets for use in various modules and the Jetpack admin page.
1060
	 *
1061
	 * @uses wp_script_is, wp_register_script, plugins_url
1062
	 * @action wp_loaded
1063
	 * @return null
1064
	 */
1065
	public function register_assets() {
1066
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1067
			wp_register_script(
1068
				'spin',
1069
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1070
				false,
1071
				'1.3'
1072
			);
1073
		}
1074
1075
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1076
			wp_register_script(
1077
				'jquery.spin',
1078
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1079
				array( 'jquery', 'spin' ),
1080
				'1.3'
1081
			);
1082
		}
1083
1084 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1085
			wp_register_script(
1086
				'jetpack-gallery-settings',
1087
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1088
				array( 'media-views' ),
1089
				'20121225'
1090
			);
1091
		}
1092
1093
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1094
			wp_register_script(
1095
				'jetpack-twitter-timeline',
1096
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1097
				array( 'jquery' ),
1098
				'4.0.0',
1099
				true
1100
			);
1101
		}
1102
1103
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1104
			wp_register_script(
1105
				'jetpack-facebook-embed',
1106
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1107
				array( 'jquery' ),
1108
				null,
1109
				true
1110
			);
1111
1112
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1113
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1114
			if ( ! is_numeric( $fb_app_id ) ) {
1115
				$fb_app_id = '';
1116
			}
1117
			wp_localize_script(
1118
				'jetpack-facebook-embed',
1119
				'jpfbembed',
1120
				array(
1121
					'appid' => $fb_app_id,
1122
					'locale' => $this->get_locale(),
1123
				)
1124
			);
1125
		}
1126
1127
		/**
1128
		 * As jetpack_register_genericons is by default fired off a hook,
1129
		 * the hook may have already fired by this point.
1130
		 * So, let's just trigger it manually.
1131
		 */
1132
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1133
		jetpack_register_genericons();
1134
1135
		/**
1136
		 * Register the social logos
1137
		 */
1138
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1139
		jetpack_register_social_logos();
1140
1141 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1142
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1143
	}
1144
1145
	/**
1146
	 * Guess locale from language code.
1147
	 *
1148
	 * @param string $lang Language code.
1149
	 * @return string|bool
1150
	 */
1151 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1152
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1153
			return 'en_US';
1154
		}
1155
1156
		if ( ! class_exists( 'GP_Locales' ) ) {
1157
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1158
				return false;
1159
			}
1160
1161
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1162
		}
1163
1164
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1165
			// WP.com: get_locale() returns 'it'
1166
			$locale = GP_Locales::by_slug( $lang );
1167
		} else {
1168
			// Jetpack: get_locale() returns 'it_IT';
1169
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1170
		}
1171
1172
		if ( ! $locale ) {
1173
			return false;
1174
		}
1175
1176
		if ( empty( $locale->facebook_locale ) ) {
1177
			if ( empty( $locale->wp_locale ) ) {
1178
				return false;
1179
			} else {
1180
				// Facebook SDK is smart enough to fall back to en_US if a
1181
				// locale isn't supported. Since supported Facebook locales
1182
				// can fall out of sync, we'll attempt to use the known
1183
				// wp_locale value and rely on said fallback.
1184
				return $locale->wp_locale;
1185
			}
1186
		}
1187
1188
		return $locale->facebook_locale;
1189
	}
1190
1191
	/**
1192
	 * Get the locale.
1193
	 *
1194
	 * @return string|bool
1195
	 */
1196
	function get_locale() {
1197
		$locale = $this->guess_locale_from_lang( get_locale() );
1198
1199
		if ( ! $locale ) {
1200
			$locale = 'en_US';
1201
		}
1202
1203
		return $locale;
1204
	}
1205
1206
	/**
1207
	 * Device Pixels support
1208
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1209
	 */
1210
	function devicepx() {
1211
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1212
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1213
		}
1214
	}
1215
1216
	/**
1217
	 * Return the network_site_url so that .com knows what network this site is a part of.
1218
	 * @param  bool $option
1219
	 * @return string
1220
	 */
1221
	public function jetpack_main_network_site_option( $option ) {
1222
		return network_site_url();
1223
	}
1224
	/**
1225
	 * Network Name.
1226
	 */
1227
	static function network_name( $option = null ) {
1228
		global $current_site;
1229
		return $current_site->site_name;
1230
	}
1231
	/**
1232
	 * Does the network allow new user and site registrations.
1233
	 * @return string
1234
	 */
1235
	static function network_allow_new_registrations( $option = null ) {
1236
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1237
	}
1238
	/**
1239
	 * Does the network allow admins to add new users.
1240
	 * @return boolian
1241
	 */
1242
	static function network_add_new_users( $option = null ) {
1243
		return (bool) get_site_option( 'add_new_users' );
1244
	}
1245
	/**
1246
	 * File upload psace left per site in MB.
1247
	 *  -1 means NO LIMIT.
1248
	 * @return number
1249
	 */
1250
	static function network_site_upload_space( $option = null ) {
1251
		// value in MB
1252
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1253
	}
1254
1255
	/**
1256
	 * Network allowed file types.
1257
	 * @return string
1258
	 */
1259
	static function network_upload_file_types( $option = null ) {
1260
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1261
	}
1262
1263
	/**
1264
	 * Maximum file upload size set by the network.
1265
	 * @return number
1266
	 */
1267
	static function network_max_upload_file_size( $option = null ) {
1268
		// value in KB
1269
		return get_site_option( 'fileupload_maxk', 300 );
1270
	}
1271
1272
	/**
1273
	 * Lets us know if a site allows admins to manage the network.
1274
	 * @return array
1275
	 */
1276
	static function network_enable_administration_menus( $option = null ) {
1277
		return get_site_option( 'menu_items' );
1278
	}
1279
1280
	/**
1281
	 * If a user has been promoted to or demoted from admin, we need to clear the
1282
	 * jetpack_other_linked_admins transient.
1283
	 *
1284
	 * @since 4.3.2
1285
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1286
	 *
1287
	 * @param int    $user_id   The user ID whose role changed.
1288
	 * @param string $role      The new role.
1289
	 * @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...
1290
	 */
1291
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1292
		if ( 'administrator' == $role
1293
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1294
			|| is_null( $old_roles )
1295
		) {
1296
			delete_transient( 'jetpack_other_linked_admins' );
1297
		}
1298
	}
1299
1300
	/**
1301
	 * Checks to see if there are any other users available to become primary
1302
	 * Users must both:
1303
	 * - Be linked to wpcom
1304
	 * - Be an admin
1305
	 *
1306
	 * @return mixed False if no other users are linked, Int if there are.
1307
	 */
1308
	static function get_other_linked_admins() {
1309
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1310
1311
		if ( false === $other_linked_users ) {
1312
			$admins = get_users( array( 'role' => 'administrator' ) );
1313
			if ( count( $admins ) > 1 ) {
1314
				$available = array();
1315
				foreach ( $admins as $admin ) {
1316
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1317
						$available[] = $admin->ID;
1318
					}
1319
				}
1320
1321
				$count_connected_admins = count( $available );
1322
				if ( count( $available ) > 1 ) {
1323
					$other_linked_users = $count_connected_admins;
1324
				} else {
1325
					$other_linked_users = 0;
1326
				}
1327
			} else {
1328
				$other_linked_users = 0;
1329
			}
1330
1331
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1332
		}
1333
1334
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1335
	}
1336
1337
	/**
1338
	 * Return whether we are dealing with a multi network setup or not.
1339
	 * The reason we are type casting this is because we want to avoid the situation where
1340
	 * the result is false since when is_main_network_option return false it cases
1341
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1342
	 * database which could be set to anything as opposed to what this function returns.
1343
	 * @param  bool  $option
1344
	 *
1345
	 * @return boolean
1346
	 */
1347
	public function is_main_network_option( $option ) {
1348
		// return '1' or ''
1349
		return (string) (bool) Jetpack::is_multi_network();
1350
	}
1351
1352
	/**
1353
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1354
	 *
1355
	 * @param  string  $option
1356
	 * @return boolean
1357
	 */
1358
	public function is_multisite( $option ) {
1359
		return (string) (bool) is_multisite();
1360
	}
1361
1362
	/**
1363
	 * Implemented since there is no core is multi network function
1364
	 * Right now there is no way to tell if we which network is the dominant network on the system
1365
	 *
1366
	 * @since  3.3
1367
	 * @return boolean
1368
	 */
1369
	public static function is_multi_network() {
1370
		global  $wpdb;
1371
1372
		// if we don't have a multi site setup no need to do any more
1373
		if ( ! is_multisite() ) {
1374
			return false;
1375
		}
1376
1377
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1378
		if ( $num_sites > 1 ) {
1379
			return true;
1380
		} else {
1381
			return false;
1382
		}
1383
	}
1384
1385
	/**
1386
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1387
	 * @return null
1388
	 */
1389
	function update_jetpack_main_network_site_option() {
1390
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1391
	}
1392
	/**
1393
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1394
	 *
1395
	 */
1396
	function update_jetpack_network_settings() {
1397
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1398
		// Only sync this info for the main network site.
1399
	}
1400
1401
	/**
1402
	 * Get back if the current site is single user site.
1403
	 *
1404
	 * @return bool
1405
	 */
1406
	public static function is_single_user_site() {
1407
		global $wpdb;
1408
1409 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1410
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1411
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1412
		}
1413
		return 1 === (int) $some_users;
1414
	}
1415
1416
	/**
1417
	 * Returns true if the site has file write access false otherwise.
1418
	 * @return string ( '1' | '0' )
1419
	 **/
1420
	public static function file_system_write_access() {
1421
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1422
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1423
		}
1424
1425
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1426
1427
		$filesystem_method = get_filesystem_method();
1428
		if ( $filesystem_method === 'direct' ) {
1429
			return 1;
1430
		}
1431
1432
		ob_start();
1433
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1434
		ob_end_clean();
1435
		if ( $filesystem_credentials_are_stored ) {
1436
			return 1;
1437
		}
1438
		return 0;
1439
	}
1440
1441
	/**
1442
	 * Finds out if a site is using a version control system.
1443
	 * @return string ( '1' | '0' )
1444
	 **/
1445
	public static function is_version_controlled() {
1446
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1447
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1448
	}
1449
1450
	/**
1451
	 * Determines whether the current theme supports featured images or not.
1452
	 * @return string ( '1' | '0' )
1453
	 */
1454
	public static function featured_images_enabled() {
1455
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1456
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1457
	}
1458
1459
	/**
1460
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1461
	 *
1462
	 * @deprecated 4.7 use get_avatar_url instead.
1463
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1464
	 * @param int $size Size of the avatar image
1465
	 * @param string $default URL to a default image to use if no avatar is available
1466
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1467
	 *
1468
	 * @return array
1469
	 */
1470
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1471
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1472
		return get_avatar_url( $id_or_email, array(
1473
			'size' => $size,
1474
			'default' => $default,
1475
			'force_default' => $force_display,
1476
		) );
1477
	}
1478
1479
	/**
1480
	 * jetpack_updates is saved in the following schema:
1481
	 *
1482
	 * array (
1483
	 *      'plugins'                       => (int) Number of plugin updates available.
1484
	 *      'themes'                        => (int) Number of theme updates available.
1485
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1486
	 *      'translations'                  => (int) Number of translation updates available.
1487
	 *      'total'                         => (int) Total of all available updates.
1488
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1489
	 * )
1490
	 * @return array
1491
	 */
1492
	public static function get_updates() {
1493
		$update_data = wp_get_update_data();
1494
1495
		// Stores the individual update counts as well as the total count.
1496
		if ( isset( $update_data['counts'] ) ) {
1497
			$updates = $update_data['counts'];
1498
		}
1499
1500
		// If we need to update WordPress core, let's find the latest version number.
1501 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1502
			$cur = get_preferred_from_update_core();
1503
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1504
				$updates['wp_update_version'] = $cur->current;
1505
			}
1506
		}
1507
		return isset( $updates ) ? $updates : array();
1508
	}
1509
1510
	public static function get_update_details() {
1511
		$update_details = array(
1512
			'update_core' => get_site_transient( 'update_core' ),
1513
			'update_plugins' => get_site_transient( 'update_plugins' ),
1514
			'update_themes' => get_site_transient( 'update_themes' ),
1515
		);
1516
		return $update_details;
1517
	}
1518
1519
	public static function refresh_update_data() {
1520
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1521
1522
	}
1523
1524
	public static function refresh_theme_data() {
1525
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1526
	}
1527
1528
	/**
1529
	 * Is Jetpack active?
1530
	 */
1531
	public static function is_active() {
1532
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1533
	}
1534
1535
	/**
1536
	 * Make an API call to WordPress.com for plan status
1537
	 *
1538
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1539
	 *
1540
	 * @return bool True if plan is updated, false if no update
1541
	 */
1542
	public static function refresh_active_plan_from_wpcom() {
1543
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1544
		return Jetpack_Plan::refresh_from_wpcom();
1545
	}
1546
1547
	/**
1548
	 * Get the plan that this Jetpack site is currently using
1549
	 *
1550
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1551
	 * @return array Active Jetpack plan details.
1552
	 */
1553
	public static function get_active_plan() {
1554
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1555
		return Jetpack_Plan::get();
1556
	}
1557
1558
	/**
1559
	 * Determine whether the active plan supports a particular feature
1560
	 *
1561
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1562
	 * @return bool True if plan supports feature, false if not.
1563
	 */
1564
	public static function active_plan_supports( $feature ) {
1565
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1566
		return Jetpack_Plan::supports( $feature );
1567
	}
1568
1569
	/**
1570
	 * Is Jetpack in development (offline) mode?
1571
	 */
1572
	public static function is_development_mode() {
1573
		$development_mode = false;
1574
1575
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1576
			$development_mode = JETPACK_DEV_DEBUG;
1577
		} elseif ( $site_url = site_url() ) {
1578
			$development_mode = false === strpos( $site_url, '.' );
1579
		}
1580
1581
		/**
1582
		 * Filters Jetpack's development mode.
1583
		 *
1584
		 * @see https://jetpack.com/support/development-mode/
1585
		 *
1586
		 * @since 2.2.1
1587
		 *
1588
		 * @param bool $development_mode Is Jetpack's development mode active.
1589
		 */
1590
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1591
		return $development_mode;
1592
	}
1593
1594
	/**
1595
	 * Whether the site is currently onboarding or not.
1596
	 * A site is considered as being onboarded if it currently has an onboarding token.
1597
	 *
1598
	 * @since 5.8
1599
	 *
1600
	 * @access public
1601
	 * @static
1602
	 *
1603
	 * @return bool True if the site is currently onboarding, false otherwise
1604
	 */
1605
	public static function is_onboarding() {
1606
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1607
	}
1608
1609
	/**
1610
	 * Determines reason for Jetpack development mode.
1611
	 */
1612
	public static function development_mode_trigger_text() {
1613
		if ( ! Jetpack::is_development_mode() ) {
1614
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1615
		}
1616
1617
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1618
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1619
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1620
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1621
		} else {
1622
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1623
		}
1624
1625
		return $notice;
1626
1627
	}
1628
	/**
1629
	* Get Jetpack development mode notice text and notice class.
1630
	*
1631
	* Mirrors the checks made in Jetpack::is_development_mode
1632
	*
1633
	*/
1634
	public static function show_development_mode_notice() {
1635 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1636
			$notice = sprintf(
1637
			/* translators: %s is a URL */
1638
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1639
				'https://jetpack.com/support/development-mode/'
1640
			);
1641
1642
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1643
1644
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1645
		}
1646
1647
		// Throw up a notice if using a development version and as for feedback.
1648
		if ( Jetpack::is_development_version() ) {
1649
			/* translators: %s is a URL */
1650
			$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/' );
1651
1652
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1653
		}
1654
		// Throw up a notice if using staging mode
1655
		if ( Jetpack::is_staging_site() ) {
1656
			/* translators: %s is a URL */
1657
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1658
1659
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1660
		}
1661
	}
1662
1663
	/**
1664
	 * Whether Jetpack's version maps to a public release, or a development version.
1665
	 */
1666
	public static function is_development_version() {
1667
		/**
1668
		 * Allows filtering whether this is a development version of Jetpack.
1669
		 *
1670
		 * This filter is especially useful for tests.
1671
		 *
1672
		 * @since 4.3.0
1673
		 *
1674
		 * @param bool $development_version Is this a develoment version of Jetpack?
1675
		 */
1676
		return (bool) apply_filters(
1677
			'jetpack_development_version',
1678
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1679
		);
1680
	}
1681
1682
	/**
1683
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1684
	 */
1685
	public static function is_user_connected( $user_id = false ) {
1686
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1687
		if ( ! $user_id ) {
1688
			return false;
1689
		}
1690
1691
		return (bool) Jetpack_Data::get_access_token( $user_id );
1692
	}
1693
1694
	/**
1695
	 * Get the wpcom user data of the current|specified connected user.
1696
	 */
1697
	public static function get_connected_user_data( $user_id = null ) {
1698
		if ( ! $user_id ) {
1699
			$user_id = get_current_user_id();
1700
		}
1701
1702
		$transient_key = "jetpack_connected_user_data_$user_id";
1703
1704
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1705
			return $cached_user_data;
1706
		}
1707
1708
		Jetpack::load_xml_rpc_client();
1709
		$xml = new Jetpack_IXR_Client( array(
1710
			'user_id' => $user_id,
1711
		) );
1712
		$xml->query( 'wpcom.getUser' );
1713
		if ( ! $xml->isError() ) {
1714
			$user_data = $xml->getResponse();
1715
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1716
			return $user_data;
1717
		}
1718
1719
		return false;
1720
	}
1721
1722
	/**
1723
	 * Get the wpcom email of the current|specified connected user.
1724
	 */
1725 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1726
		if ( ! $user_id ) {
1727
			$user_id = get_current_user_id();
1728
		}
1729
		Jetpack::load_xml_rpc_client();
1730
		$xml = new Jetpack_IXR_Client( array(
1731
			'user_id' => $user_id,
1732
		) );
1733
		$xml->query( 'wpcom.getUserEmail' );
1734
		if ( ! $xml->isError() ) {
1735
			return $xml->getResponse();
1736
		}
1737
		return false;
1738
	}
1739
1740
	/**
1741
	 * Get the wpcom email of the master user.
1742
	 */
1743
	public static function get_master_user_email() {
1744
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1745
		if ( $master_user_id ) {
1746
			return self::get_connected_user_email( $master_user_id );
1747
		}
1748
		return '';
1749
	}
1750
1751
	function current_user_is_connection_owner() {
1752
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1753
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1754
	}
1755
1756
	/**
1757
	 * Gets current user IP address.
1758
	 *
1759
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1760
	 *
1761
	 * @return string                  Current user IP address.
1762
	 */
1763
	public static function current_user_ip( $check_all_headers = false ) {
1764
		if ( $check_all_headers ) {
1765
			foreach ( array(
1766
				'HTTP_CF_CONNECTING_IP',
1767
				'HTTP_CLIENT_IP',
1768
				'HTTP_X_FORWARDED_FOR',
1769
				'HTTP_X_FORWARDED',
1770
				'HTTP_X_CLUSTER_CLIENT_IP',
1771
				'HTTP_FORWARDED_FOR',
1772
				'HTTP_FORWARDED',
1773
				'HTTP_VIA',
1774
			) as $key ) {
1775
				if ( ! empty( $_SERVER[ $key ] ) ) {
1776
					return $_SERVER[ $key ];
1777
				}
1778
			}
1779
		}
1780
1781
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1782
	}
1783
1784
	/**
1785
	 * Synchronize connected user role changes
1786
	 */
1787
	function user_role_change( $user_id ) {
1788
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1789
		Jetpack_Sync_Users::user_role_change( $user_id );
1790
	}
1791
1792
	/**
1793
	 * Loads the currently active modules.
1794
	 */
1795
	public static function load_modules() {
1796
		if (
1797
			! self::is_active()
1798
			&& ! self::is_development_mode()
1799
			&& ! self::is_onboarding()
1800
			&& (
1801
				! is_multisite()
1802
				|| ! get_site_option( 'jetpack_protect_active' )
1803
			)
1804
		) {
1805
			return;
1806
		}
1807
1808
		$version = Jetpack_Options::get_option( 'version' );
1809 View Code Duplication
		if ( ! $version ) {
1810
			$version = $old_version = JETPACK__VERSION . ':' . time();
1811
			/** This action is documented in class.jetpack.php */
1812
			do_action( 'updating_jetpack_version', $version, false );
1813
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1814
		}
1815
		list( $version ) = explode( ':', $version );
1816
1817
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1818
1819
		$modules_data = array();
1820
1821
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1822
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1823
			$updated_modules = array();
1824
			foreach ( $modules as $module ) {
1825
				$modules_data[ $module ] = Jetpack::get_module( $module );
1826
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1827
					continue;
1828
				}
1829
1830
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1831
					continue;
1832
				}
1833
1834
				$updated_modules[] = $module;
1835
			}
1836
1837
			$modules = array_diff( $modules, $updated_modules );
1838
		}
1839
1840
		$is_development_mode = Jetpack::is_development_mode();
1841
1842
		foreach ( $modules as $index => $module ) {
1843
			// If we're in dev mode, disable modules requiring a connection
1844
			if ( $is_development_mode ) {
1845
				// Prime the pump if we need to
1846
				if ( empty( $modules_data[ $module ] ) ) {
1847
					$modules_data[ $module ] = Jetpack::get_module( $module );
1848
				}
1849
				// If the module requires a connection, but we're in local mode, don't include it.
1850
				if ( $modules_data[ $module ]['requires_connection'] ) {
1851
					continue;
1852
				}
1853
			}
1854
1855
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1856
				continue;
1857
			}
1858
1859
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1860
				unset( $modules[ $index ] );
1861
				self::update_active_modules( array_values( $modules ) );
1862
				continue;
1863
			}
1864
1865
			/**
1866
			 * Fires when a specific module is loaded.
1867
			 * The dynamic part of the hook, $module, is the module slug.
1868
			 *
1869
			 * @since 1.1.0
1870
			 */
1871
			do_action( 'jetpack_module_loaded_' . $module );
1872
		}
1873
1874
		/**
1875
		 * Fires when all the modules are loaded.
1876
		 *
1877
		 * @since 1.1.0
1878
		 */
1879
		do_action( 'jetpack_modules_loaded' );
1880
1881
		// 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.
1882
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1883
	}
1884
1885
	/**
1886
	 * Check if Jetpack's REST API compat file should be included
1887
	 * @action plugins_loaded
1888
	 * @return null
1889
	 */
1890
	public function check_rest_api_compat() {
1891
		/**
1892
		 * Filters the list of REST API compat files to be included.
1893
		 *
1894
		 * @since 2.2.5
1895
		 *
1896
		 * @param array $args Array of REST API compat files to include.
1897
		 */
1898
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1899
1900
		if ( function_exists( 'bbpress' ) )
1901
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1902
1903
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1904
			require_once $_jetpack_rest_api_compat_include;
1905
	}
1906
1907
	/**
1908
	 * Gets all plugins currently active in values, regardless of whether they're
1909
	 * traditionally activated or network activated.
1910
	 *
1911
	 * @todo Store the result in core's object cache maybe?
1912
	 */
1913
	public static function get_active_plugins() {
1914
		$active_plugins = (array) get_option( 'active_plugins', array() );
1915
1916
		if ( is_multisite() ) {
1917
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1918
			// whereas active_plugins stores them in the values.
1919
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1920
			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...
1921
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1922
			}
1923
		}
1924
1925
		sort( $active_plugins );
1926
1927
		return array_unique( $active_plugins );
1928
	}
1929
1930
	/**
1931
	 * Gets and parses additional plugin data to send with the heartbeat data
1932
	 *
1933
	 * @since 3.8.1
1934
	 *
1935
	 * @return array Array of plugin data
1936
	 */
1937
	public static function get_parsed_plugin_data() {
1938
		if ( ! function_exists( 'get_plugins' ) ) {
1939
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1940
		}
1941
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1942
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1943
		$active_plugins = Jetpack::get_active_plugins();
1944
1945
		$plugins = array();
1946
		foreach ( $all_plugins as $path => $plugin_data ) {
1947
			$plugins[ $path ] = array(
1948
					'is_active' => in_array( $path, $active_plugins ),
1949
					'file'      => $path,
1950
					'name'      => $plugin_data['Name'],
1951
					'version'   => $plugin_data['Version'],
1952
					'author'    => $plugin_data['Author'],
1953
			);
1954
		}
1955
1956
		return $plugins;
1957
	}
1958
1959
	/**
1960
	 * Gets and parses theme data to send with the heartbeat data
1961
	 *
1962
	 * @since 3.8.1
1963
	 *
1964
	 * @return array Array of theme data
1965
	 */
1966
	public static function get_parsed_theme_data() {
1967
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1968
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1969
1970
		$themes = array();
1971
		foreach ( $all_themes as $slug => $theme_data ) {
1972
			$theme_headers = array();
1973
			foreach ( $header_keys as $header_key ) {
1974
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1975
			}
1976
1977
			$themes[ $slug ] = array(
1978
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1979
					'slug' => $slug,
1980
					'theme_root' => $theme_data->get_theme_root_uri(),
1981
					'parent' => $theme_data->parent(),
1982
					'headers' => $theme_headers
1983
			);
1984
		}
1985
1986
		return $themes;
1987
	}
1988
1989
	/**
1990
	 * Checks whether a specific plugin is active.
1991
	 *
1992
	 * We don't want to store these in a static variable, in case
1993
	 * there are switch_to_blog() calls involved.
1994
	 */
1995
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1996
		return in_array( $plugin, self::get_active_plugins() );
1997
	}
1998
1999
	/**
2000
	 * Check if Jetpack's Open Graph tags should be used.
2001
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2002
	 *
2003
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2004
	 * @action plugins_loaded
2005
	 * @return null
2006
	 */
2007
	public function check_open_graph() {
2008
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2009
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2010
		}
2011
2012
		$active_plugins = self::get_active_plugins();
2013
2014
		if ( ! empty( $active_plugins ) ) {
2015
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2016
				if ( in_array( $plugin, $active_plugins ) ) {
2017
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2018
					break;
2019
				}
2020
			}
2021
		}
2022
2023
		/**
2024
		 * Allow the addition of Open Graph Meta Tags to all pages.
2025
		 *
2026
		 * @since 2.0.3
2027
		 *
2028
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2029
		 */
2030
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2031
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2032
		}
2033
	}
2034
2035
	/**
2036
	 * Check if Jetpack's Twitter tags should be used.
2037
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2038
	 *
2039
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2040
	 * @action plugins_loaded
2041
	 * @return null
2042
	 */
2043
	public function check_twitter_tags() {
2044
2045
		$active_plugins = self::get_active_plugins();
2046
2047
		if ( ! empty( $active_plugins ) ) {
2048
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2049
				if ( in_array( $plugin, $active_plugins ) ) {
2050
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2051
					break;
2052
				}
2053
			}
2054
		}
2055
2056
		/**
2057
		 * Allow Twitter Card Meta tags to be disabled.
2058
		 *
2059
		 * @since 2.6.0
2060
		 *
2061
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2062
		 */
2063
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2064
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2065
		}
2066
	}
2067
2068
	/**
2069
	 * Allows plugins to submit security reports.
2070
 	 *
2071
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2072
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2073
	 * @param array   $args         See definitions above
2074
	 */
2075
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2076
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2077
	}
2078
2079
/* Jetpack Options API */
2080
2081
	public static function get_option_names( $type = 'compact' ) {
2082
		return Jetpack_Options::get_option_names( $type );
2083
	}
2084
2085
	/**
2086
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2087
 	 *
2088
	 * @param string $name    Option name
2089
	 * @param mixed  $default (optional)
2090
	 */
2091
	public static function get_option( $name, $default = false ) {
2092
		return Jetpack_Options::get_option( $name, $default );
2093
	}
2094
2095
	/**
2096
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2097
 	 *
2098
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2099
	 * @param string $name  Option name
2100
	 * @param mixed  $value Option value
2101
	 */
2102
	public static function update_option( $name, $value ) {
2103
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2104
		return Jetpack_Options::update_option( $name, $value );
2105
	}
2106
2107
	/**
2108
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2109
 	 *
2110
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2111
	 * @param array $array array( option name => option value, ... )
2112
	 */
2113
	public static function update_options( $array ) {
2114
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2115
		return Jetpack_Options::update_options( $array );
2116
	}
2117
2118
	/**
2119
	 * Deletes the given option.  May be passed multiple option names as an array.
2120
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2121
	 *
2122
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2123
	 * @param string|array $names
2124
	 */
2125
	public static function delete_option( $names ) {
2126
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2127
		return Jetpack_Options::delete_option( $names );
2128
	}
2129
2130
	/**
2131
	 * Enters a user token into the user_tokens option
2132
	 *
2133
	 * @param int $user_id
2134
	 * @param string $token
2135
	 * return bool
2136
	 */
2137
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2138
		// not designed for concurrent updates
2139
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2140
		if ( ! is_array( $user_tokens ) )
2141
			$user_tokens = array();
2142
		$user_tokens[$user_id] = $token;
2143
		if ( $is_master_user ) {
2144
			$master_user = $user_id;
2145
			$options     = compact( 'user_tokens', 'master_user' );
2146
		} else {
2147
			$options = compact( 'user_tokens' );
2148
		}
2149
		return Jetpack_Options::update_options( $options );
2150
	}
2151
2152
	/**
2153
	 * Returns an array of all PHP files in the specified absolute path.
2154
	 * Equivalent to glob( "$absolute_path/*.php" ).
2155
	 *
2156
	 * @param string $absolute_path The absolute path of the directory to search.
2157
	 * @return array Array of absolute paths to the PHP files.
2158
	 */
2159
	public static function glob_php( $absolute_path ) {
2160
		if ( function_exists( 'glob' ) ) {
2161
			return glob( "$absolute_path/*.php" );
2162
		}
2163
2164
		$absolute_path = untrailingslashit( $absolute_path );
2165
		$files = array();
2166
		if ( ! $dir = @opendir( $absolute_path ) ) {
2167
			return $files;
2168
		}
2169
2170
		while ( false !== $file = readdir( $dir ) ) {
2171
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2172
				continue;
2173
			}
2174
2175
			$file = "$absolute_path/$file";
2176
2177
			if ( ! is_file( $file ) ) {
2178
				continue;
2179
			}
2180
2181
			$files[] = $file;
2182
		}
2183
2184
		closedir( $dir );
2185
2186
		return $files;
2187
	}
2188
2189
	public static function activate_new_modules( $redirect = false ) {
2190
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2191
			return;
2192
		}
2193
2194
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2195 View Code Duplication
		if ( ! $jetpack_old_version ) {
2196
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2197
			/** This action is documented in class.jetpack.php */
2198
			do_action( 'updating_jetpack_version', $version, false );
2199
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2200
		}
2201
2202
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2203
2204
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2205
			return;
2206
		}
2207
2208
		$active_modules     = Jetpack::get_active_modules();
2209
		$reactivate_modules = array();
2210
		foreach ( $active_modules as $active_module ) {
2211
			$module = Jetpack::get_module( $active_module );
2212
			if ( ! isset( $module['changed'] ) ) {
2213
				continue;
2214
			}
2215
2216
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2217
				continue;
2218
			}
2219
2220
			$reactivate_modules[] = $active_module;
2221
			Jetpack::deactivate_module( $active_module );
2222
		}
2223
2224
		$new_version = JETPACK__VERSION . ':' . time();
2225
		/** This action is documented in class.jetpack.php */
2226
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2227
		Jetpack_Options::update_options(
2228
			array(
2229
				'version'     => $new_version,
2230
				'old_version' => $jetpack_old_version,
2231
			)
2232
		);
2233
2234
		Jetpack::state( 'message', 'modules_activated' );
2235
		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...
2236
2237
		if ( $redirect ) {
2238
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2239
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2240
				$page = $_GET['page'];
2241
			}
2242
2243
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2244
			exit;
2245
		}
2246
	}
2247
2248
	/**
2249
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2250
	 * Make sure to tuck away module "library" files in a sub-directory.
2251
	 */
2252
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2253
		static $modules = null;
2254
2255
		if ( ! isset( $modules ) ) {
2256
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2257
			// Use the cache if we're on the front-end and it's available...
2258
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2259
				$modules = $available_modules_option[ JETPACK__VERSION ];
2260
			} else {
2261
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2262
2263
				$modules = array();
2264
2265
				foreach ( $files as $file ) {
2266
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2267
						continue;
2268
					}
2269
2270
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2271
				}
2272
2273
				Jetpack_Options::update_option( 'available_modules', array(
2274
					JETPACK__VERSION => $modules,
2275
				) );
2276
			}
2277
		}
2278
2279
		/**
2280
		 * Filters the array of modules available to be activated.
2281
		 *
2282
		 * @since 2.4.0
2283
		 *
2284
		 * @param array $modules Array of available modules.
2285
		 * @param string $min_version Minimum version number required to use modules.
2286
		 * @param string $max_version Maximum version number required to use modules.
2287
		 */
2288
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2289
2290
		if ( ! $min_version && ! $max_version ) {
2291
			return array_keys( $mods );
2292
		}
2293
2294
		$r = array();
2295
		foreach ( $mods as $slug => $introduced ) {
2296
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2297
				continue;
2298
			}
2299
2300
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2301
				continue;
2302
			}
2303
2304
			$r[] = $slug;
2305
		}
2306
2307
		return $r;
2308
	}
2309
2310
	/**
2311
	 * Default modules loaded on activation.
2312
	 */
2313
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2314
		$return = array();
2315
2316
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2317
			$module_data = Jetpack::get_module( $module );
2318
2319
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2320
				case 'yes' :
2321
					$return[] = $module;
2322
					break;
2323
				case 'public' :
2324
					if ( Jetpack_Options::get_option( 'public' ) ) {
2325
						$return[] = $module;
2326
					}
2327
					break;
2328
				case 'no' :
2329
				default :
2330
					break;
2331
			}
2332
		}
2333
		/**
2334
		 * Filters the array of default modules.
2335
		 *
2336
		 * @since 2.5.0
2337
		 *
2338
		 * @param array $return Array of default modules.
2339
		 * @param string $min_version Minimum version number required to use modules.
2340
		 * @param string $max_version Maximum version number required to use modules.
2341
		 */
2342
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2343
	}
2344
2345
	/**
2346
	 * Checks activated modules during auto-activation to determine
2347
	 * if any of those modules are being deprecated.  If so, close
2348
	 * them out, and add any replacement modules.
2349
	 *
2350
	 * Runs at priority 99 by default.
2351
	 *
2352
	 * This is run late, so that it can still activate a module if
2353
	 * the new module is a replacement for another that the user
2354
	 * currently has active, even if something at the normal priority
2355
	 * would kibosh everything.
2356
	 *
2357
	 * @since 2.6
2358
	 * @uses jetpack_get_default_modules filter
2359
	 * @param array $modules
2360
	 * @return array
2361
	 */
2362
	function handle_deprecated_modules( $modules ) {
2363
		$deprecated_modules = array(
2364
			'debug'            => null,  // Closed out and moved to the debugger library.
2365
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2366
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2367
		);
2368
2369
		// Don't activate SSO if they never completed activating WPCC.
2370
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2371
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2372
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2373
				$deprecated_modules['wpcc'] = null;
2374
			}
2375
		}
2376
2377
		foreach ( $deprecated_modules as $module => $replacement ) {
2378
			if ( Jetpack::is_module_active( $module ) ) {
2379
				self::deactivate_module( $module );
2380
				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...
2381
					$modules[] = $replacement;
2382
				}
2383
			}
2384
		}
2385
2386
		return array_unique( $modules );
2387
	}
2388
2389
	/**
2390
	 * Checks activated plugins during auto-activation to determine
2391
	 * if any of those plugins are in the list with a corresponding module
2392
	 * that is not compatible with the plugin. The module will not be allowed
2393
	 * to auto-activate.
2394
	 *
2395
	 * @since 2.6
2396
	 * @uses jetpack_get_default_modules filter
2397
	 * @param array $modules
2398
	 * @return array
2399
	 */
2400
	function filter_default_modules( $modules ) {
2401
2402
		$active_plugins = self::get_active_plugins();
2403
2404
		if ( ! empty( $active_plugins ) ) {
2405
2406
			// For each module we'd like to auto-activate...
2407
			foreach ( $modules as $key => $module ) {
2408
				// If there are potential conflicts for it...
2409
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2410
					// For each potential conflict...
2411
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2412
						// If that conflicting plugin is active...
2413
						if ( in_array( $plugin, $active_plugins ) ) {
2414
							// Remove that item from being auto-activated.
2415
							unset( $modules[ $key ] );
2416
						}
2417
					}
2418
				}
2419
			}
2420
		}
2421
2422
		return $modules;
2423
	}
2424
2425
	/**
2426
	 * Extract a module's slug from its full path.
2427
	 */
2428
	public static function get_module_slug( $file ) {
2429
		return str_replace( '.php', '', basename( $file ) );
2430
	}
2431
2432
	/**
2433
	 * Generate a module's path from its slug.
2434
	 */
2435
	public static function get_module_path( $slug ) {
2436
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2437
	}
2438
2439
	/**
2440
	 * Load module data from module file. Headers differ from WordPress
2441
	 * plugin headers to avoid them being identified as standalone
2442
	 * plugins on the WordPress plugins page.
2443
	 */
2444
	public static function get_module( $module ) {
2445
		$headers = array(
2446
			'name'                      => 'Module Name',
2447
			'description'               => 'Module Description',
2448
			'jumpstart_desc'            => 'Jumpstart Description',
2449
			'sort'                      => 'Sort Order',
2450
			'recommendation_order'      => 'Recommendation Order',
2451
			'introduced'                => 'First Introduced',
2452
			'changed'                   => 'Major Changes In',
2453
			'deactivate'                => 'Deactivate',
2454
			'free'                      => 'Free',
2455
			'requires_connection'       => 'Requires Connection',
2456
			'auto_activate'             => 'Auto Activate',
2457
			'module_tags'               => 'Module Tags',
2458
			'feature'                   => 'Feature',
2459
			'additional_search_queries' => 'Additional Search Queries',
2460
			'plan_classes'              => 'Plans',
2461
		);
2462
2463
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2464
2465
		$mod = Jetpack::get_file_data( $file, $headers );
2466
		if ( empty( $mod['name'] ) ) {
2467
			return false;
2468
		}
2469
2470
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2471
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2472
		$mod['deactivate']              = empty( $mod['deactivate'] );
2473
		$mod['free']                    = empty( $mod['free'] );
2474
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2475
2476
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2477
			$mod['auto_activate'] = 'No';
2478
		} else {
2479
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2480
		}
2481
2482
		if ( $mod['module_tags'] ) {
2483
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2484
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2485
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2486
		} else {
2487
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2488
		}
2489
2490 View Code Duplication
		if ( $mod['plan_classes'] ) {
2491
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2492
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2493
		} else {
2494
			$mod['plan_classes'] = array( 'free' );
2495
		}
2496
2497 View Code Duplication
		if ( $mod['feature'] ) {
2498
			$mod['feature'] = explode( ',', $mod['feature'] );
2499
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2500
		} else {
2501
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2502
		}
2503
2504
		/**
2505
		 * Filters the feature array on a module.
2506
		 *
2507
		 * This filter allows you to control where each module is filtered: Recommended,
2508
		 * Jumpstart, and the default "Other" listing.
2509
		 *
2510
		 * @since 3.5.0
2511
		 *
2512
		 * @param array   $mod['feature'] The areas to feature this module:
2513
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2514
		 *     'Recommended' shows on the main Jetpack admin screen.
2515
		 *     'Other' should be the default if no other value is in the array.
2516
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2517
		 * @param array   $mod All the currently assembled module data.
2518
		 */
2519
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2520
2521
		/**
2522
		 * Filter the returned data about a module.
2523
		 *
2524
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2525
		 * so please be careful.
2526
		 *
2527
		 * @since 3.6.0
2528
		 *
2529
		 * @param array   $mod    The details of the requested module.
2530
		 * @param string  $module The slug of the module, e.g. sharedaddy
2531
		 * @param string  $file   The path to the module source file.
2532
		 */
2533
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2534
	}
2535
2536
	/**
2537
	 * Like core's get_file_data implementation, but caches the result.
2538
	 */
2539
	public static function get_file_data( $file, $headers ) {
2540
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2541
		$file_name = basename( $file );
2542
2543
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2544
2545
		$file_data_option = get_transient( $cache_key );
2546
2547
		if ( false === $file_data_option ) {
2548
			$file_data_option = array();
2549
		}
2550
2551
		$key           = md5( $file_name . serialize( $headers ) );
2552
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2553
2554
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2555
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2556
			return $file_data_option[ $key ];
2557
		}
2558
2559
		$data = get_file_data( $file, $headers );
2560
2561
		$file_data_option[ $key ] = $data;
2562
2563
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2564
2565
		return $data;
2566
	}
2567
2568
2569
	/**
2570
	 * Return translated module tag.
2571
	 *
2572
	 * @param string $tag Tag as it appears in each module heading.
2573
	 *
2574
	 * @return mixed
2575
	 */
2576
	public static function translate_module_tag( $tag ) {
2577
		return jetpack_get_module_i18n_tag( $tag );
2578
	}
2579
2580
	/**
2581
	 * Get i18n strings as a JSON-encoded string
2582
	 *
2583
	 * @return string The locale as JSON
2584
	 */
2585
	public static function get_i18n_data_json() {
2586
2587
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2588
		// JSON files with the file they should be included for. This is an md5
2589
		// of '_inc/build/admin.js'.
2590
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2591
2592
		$i18n_json =
2593
				   JETPACK__PLUGIN_DIR
2594
				   . 'languages/json/jetpack-'
2595
				   . get_user_locale()
2596
				   . '-'
2597
				   . $path_md5
2598
				   . '.json';
2599
2600
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2601
			$locale_data = @file_get_contents( $i18n_json );
2602
			if ( $locale_data ) {
2603
				return $locale_data;
2604
			}
2605
		}
2606
2607
		// Return valid empty Jed locale
2608
		return '{ "locale_data": { "messages": { "": {} } } }';
2609
	}
2610
2611
	/**
2612
	 * Add locale data setup to wp-i18n
2613
	 *
2614
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2615
	 *
2616
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2617
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2618
	 *
2619
	 * This method provides a safe way to request the setup multiple times but add the script at
2620
	 * most once.
2621
	 *
2622
	 * @since 6.7.0
2623
	 *
2624
	 * @return void
2625
	 */
2626
	public static function setup_wp_i18n_locale_data() {
2627
		static $script_added = false;
2628
		if ( ! $script_added ) {
2629
			$script_added = true;
2630
			wp_add_inline_script(
2631
				'wp-i18n',
2632
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2633
			);
2634
		}
2635
	}
2636
2637
	/**
2638
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2639
	 *
2640
	 * @since 3.9.2
2641
	 *
2642
	 * @param array $modules
2643
	 *
2644
	 * @return string|void
2645
	 */
2646
	public static function get_translated_modules( $modules ) {
2647
		foreach ( $modules as $index => $module ) {
2648
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2649
			if ( isset( $module['name'] ) ) {
2650
				$modules[ $index ]['name'] = $i18n_module['name'];
2651
			}
2652
			if ( isset( $module['description'] ) ) {
2653
				$modules[ $index ]['description'] = $i18n_module['description'];
2654
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2655
			}
2656
		}
2657
		return $modules;
2658
	}
2659
2660
	/**
2661
	 * Get a list of activated modules as an array of module slugs.
2662
	 */
2663
	public static function get_active_modules() {
2664
		$active = Jetpack_Options::get_option( 'active_modules' );
2665
2666
		if ( ! is_array( $active ) ) {
2667
			$active = array();
2668
		}
2669
2670
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2671
			$active[] = 'vaultpress';
2672
		} else {
2673
			$active = array_diff( $active, array( 'vaultpress' ) );
2674
		}
2675
2676
		//If protect is active on the main site of a multisite, it should be active on all sites.
2677
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2678
			$active[] = 'protect';
2679
		}
2680
2681
		/**
2682
		 * Allow filtering of the active modules.
2683
		 *
2684
		 * Gives theme and plugin developers the power to alter the modules that
2685
		 * are activated on the fly.
2686
		 *
2687
		 * @since 5.8.0
2688
		 *
2689
		 * @param array $active Array of active module slugs.
2690
		 */
2691
		$active = apply_filters( 'jetpack_active_modules', $active );
2692
2693
		return array_unique( $active );
2694
	}
2695
2696
	/**
2697
	 * Check whether or not a Jetpack module is active.
2698
	 *
2699
	 * @param string $module The slug of a Jetpack module.
2700
	 * @return bool
2701
	 *
2702
	 * @static
2703
	 */
2704
	public static function is_module_active( $module ) {
2705
		return in_array( $module, self::get_active_modules() );
2706
	}
2707
2708
	public static function is_module( $module ) {
2709
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2710
	}
2711
2712
	/**
2713
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2714
	 *
2715
	 * @param bool $catch True to start catching, False to stop.
2716
	 *
2717
	 * @static
2718
	 */
2719
	public static function catch_errors( $catch ) {
2720
		static $display_errors, $error_reporting;
2721
2722
		if ( $catch ) {
2723
			$display_errors  = @ini_set( 'display_errors', 1 );
2724
			$error_reporting = @error_reporting( E_ALL );
2725
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2726
		} else {
2727
			@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...
2728
			@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...
2729
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2730
		}
2731
	}
2732
2733
	/**
2734
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2735
	 */
2736
	public static function catch_errors_on_shutdown() {
2737
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2738
	}
2739
2740
	/**
2741
	 * Rewrite any string to make paths easier to read.
2742
	 *
2743
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2744
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2745
	 *
2746
	 * @param $string
2747
	 * @return mixed
2748
	 */
2749
	public static function alias_directories( $string ) {
2750
		// ABSPATH has a trailing slash.
2751
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2752
		// WP_CONTENT_DIR does not have a trailing slash.
2753
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2754
2755
		return $string;
2756
	}
2757
2758
	public static function activate_default_modules(
2759
		$min_version = false,
2760
		$max_version = false,
2761
		$other_modules = array(),
2762
		$redirect = true,
2763
		$send_state_messages = true
2764
	) {
2765
		$jetpack = Jetpack::init();
2766
2767
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2768
		$modules = array_merge( $other_modules, $modules );
2769
2770
		// Look for standalone plugins and disable if active.
2771
2772
		$to_deactivate = array();
2773
		foreach ( $modules as $module ) {
2774
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2775
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2776
			}
2777
		}
2778
2779
		$deactivated = array();
2780
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2781
			list( $probable_file, $probable_title ) = $deactivate_me;
2782
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2783
				$deactivated[] = $module;
2784
			}
2785
		}
2786
2787
		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...
2788
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2789
2790
			$url = add_query_arg(
2791
				array(
2792
					'action'   => 'activate_default_modules',
2793
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2794
				),
2795
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2796
			);
2797
			wp_safe_redirect( $url );
2798
			exit;
2799
		}
2800
2801
		/**
2802
		 * Fires before default modules are activated.
2803
		 *
2804
		 * @since 1.9.0
2805
		 *
2806
		 * @param string $min_version Minimum version number required to use modules.
2807
		 * @param string $max_version Maximum version number required to use modules.
2808
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2809
		 */
2810
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2811
2812
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2813
		if ( $send_state_messages ) {
2814
			Jetpack::restate();
2815
			Jetpack::catch_errors( true );
2816
		}
2817
2818
		$active = Jetpack::get_active_modules();
2819
2820
		foreach ( $modules as $module ) {
2821
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2822
				$active[] = $module;
2823
				self::update_active_modules( $active );
2824
				continue;
2825
			}
2826
2827
			if ( $send_state_messages && in_array( $module, $active ) ) {
2828
				$module_info = Jetpack::get_module( $module );
2829 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2830
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2831
					if ( $active_state = Jetpack::state( $state ) ) {
2832
						$active_state = explode( ',', $active_state );
2833
					} else {
2834
						$active_state = array();
2835
					}
2836
					$active_state[] = $module;
2837
					Jetpack::state( $state, implode( ',', $active_state ) );
2838
				}
2839
				continue;
2840
			}
2841
2842
			$file = Jetpack::get_module_path( $module );
2843
			if ( ! file_exists( $file ) ) {
2844
				continue;
2845
			}
2846
2847
			// we'll override this later if the plugin can be included without fatal error
2848
			if ( $redirect ) {
2849
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2850
			}
2851
2852
			if ( $send_state_messages ) {
2853
				Jetpack::state( 'error', 'module_activation_failed' );
2854
				Jetpack::state( 'module', $module );
2855
			}
2856
2857
			ob_start();
2858
			require_once $file;
2859
2860
			$active[] = $module;
2861
2862 View Code Duplication
			if ( $send_state_messages ) {
2863
2864
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2865
				if ( $active_state = Jetpack::state( $state ) ) {
2866
					$active_state = explode( ',', $active_state );
2867
				} else {
2868
					$active_state = array();
2869
				}
2870
				$active_state[] = $module;
2871
				Jetpack::state( $state, implode( ',', $active_state ) );
2872
			}
2873
2874
			Jetpack::update_active_modules( $active );
2875
2876
			ob_end_clean();
2877
		}
2878
2879
		if ( $send_state_messages ) {
2880
			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...
2881
			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...
2882
		}
2883
2884
		Jetpack::catch_errors( false );
2885
		/**
2886
		 * Fires when default modules are activated.
2887
		 *
2888
		 * @since 1.9.0
2889
		 *
2890
		 * @param string $min_version Minimum version number required to use modules.
2891
		 * @param string $max_version Maximum version number required to use modules.
2892
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2893
		 */
2894
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2895
	}
2896
2897
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2898
		/**
2899
		 * Fires before a module is activated.
2900
		 *
2901
		 * @since 2.6.0
2902
		 *
2903
		 * @param string $module Module slug.
2904
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2905
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2906
		 */
2907
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2908
2909
		$jetpack = Jetpack::init();
2910
2911
		if ( ! strlen( $module ) )
2912
			return false;
2913
2914
		if ( ! Jetpack::is_module( $module ) )
2915
			return false;
2916
2917
		// If it's already active, then don't do it again
2918
		$active = Jetpack::get_active_modules();
2919
		foreach ( $active as $act ) {
2920
			if ( $act == $module )
2921
				return true;
2922
		}
2923
2924
		$module_data = Jetpack::get_module( $module );
2925
2926
		if ( ! Jetpack::is_active() ) {
2927
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2928
				return false;
2929
2930
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2931
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2932
				return false;
2933
		}
2934
2935
		// Check and see if the old plugin is active
2936
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2937
			// Deactivate the old plugin
2938
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2939
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2940
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2941
				Jetpack::state( 'deactivated_plugins', $module );
2942
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2943
				exit;
2944
			}
2945
		}
2946
2947
		// Protect won't work with mis-configured IPs
2948
		if ( 'protect' === $module ) {
2949
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2950
			if ( ! jetpack_protect_get_ip() ) {
2951
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2952
				return false;
2953
			}
2954
		}
2955
2956
		if ( ! Jetpack_Plan::supports( $module ) ) {
2957
			return false;
2958
		}
2959
2960
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2961
		Jetpack::state( 'module', $module );
2962
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2963
2964
		Jetpack::catch_errors( true );
2965
		ob_start();
2966
		require Jetpack::get_module_path( $module );
2967
		/** This action is documented in class.jetpack.php */
2968
		do_action( 'jetpack_activate_module', $module );
2969
		$active[] = $module;
2970
		Jetpack::update_active_modules( $active );
2971
2972
		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...
2973
		ob_end_clean();
2974
		Jetpack::catch_errors( false );
2975
2976
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
2977 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
2978
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
2979
2980
			//Jump start is being dismissed send data to MC Stats
2981
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
2982
2983
			$jetpack->do_stats( 'server_side' );
2984
		}
2985
2986
		if ( $redirect ) {
2987
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2988
		}
2989
		if ( $exit ) {
2990
			exit;
2991
		}
2992
		return true;
2993
	}
2994
2995
	function activate_module_actions( $module ) {
2996
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2997
	}
2998
2999
	public static function deactivate_module( $module ) {
3000
		/**
3001
		 * Fires when a module is deactivated.
3002
		 *
3003
		 * @since 1.9.0
3004
		 *
3005
		 * @param string $module Module slug.
3006
		 */
3007
		do_action( 'jetpack_pre_deactivate_module', $module );
3008
3009
		$jetpack = Jetpack::init();
3010
3011
		$active = Jetpack::get_active_modules();
3012
		$new    = array_filter( array_diff( $active, (array) $module ) );
3013
3014
		// A flag for Jump Start so it's not shown again.
3015 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
3016
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
3017
3018
			//Jump start is being dismissed send data to MC Stats
3019
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
3020
3021
			$jetpack->do_stats( 'server_side' );
3022
		}
3023
3024
		return self::update_active_modules( $new );
3025
	}
3026
3027
	public static function enable_module_configurable( $module ) {
3028
		$module = Jetpack::get_module_slug( $module );
3029
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3030
	}
3031
3032
	/**
3033
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3034
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3035
	 *
3036
	 * @param string $module Module slug
3037
	 * @return string $url module configuration URL
3038
	 */
3039
	public static function module_configuration_url( $module ) {
3040
		$module = Jetpack::get_module_slug( $module );
3041
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3042
		/**
3043
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3044
		 *
3045
		 * @since 6.9.0
3046
		 *
3047
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3048
		 */
3049
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3050
3051
		return $url;
3052
	}
3053
3054
/* Installation */
3055
	public static function bail_on_activation( $message, $deactivate = true ) {
3056
?>
3057
<!doctype html>
3058
<html>
3059
<head>
3060
<meta charset="<?php bloginfo( 'charset' ); ?>">
3061
<style>
3062
* {
3063
	text-align: center;
3064
	margin: 0;
3065
	padding: 0;
3066
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3067
}
3068
p {
3069
	margin-top: 1em;
3070
	font-size: 18px;
3071
}
3072
</style>
3073
<body>
3074
<p><?php echo esc_html( $message ); ?></p>
3075
</body>
3076
</html>
3077
<?php
3078
		if ( $deactivate ) {
3079
			$plugins = get_option( 'active_plugins' );
3080
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3081
			$update  = false;
3082
			foreach ( $plugins as $i => $plugin ) {
3083
				if ( $plugin === $jetpack ) {
3084
					$plugins[$i] = false;
3085
					$update = true;
3086
				}
3087
			}
3088
3089
			if ( $update ) {
3090
				update_option( 'active_plugins', array_filter( $plugins ) );
3091
			}
3092
		}
3093
		exit;
3094
	}
3095
3096
	/**
3097
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3098
	 * @static
3099
	 */
3100
	public static function plugin_activation( $network_wide ) {
3101
		Jetpack_Options::update_option( 'activated', 1 );
3102
3103
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3104
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3105
		}
3106
3107
		if ( $network_wide )
3108
			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...
3109
3110
		// For firing one-off events (notices) immediately after activation
3111
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3112
3113
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3114
3115
		Jetpack::plugin_initialize();
3116
	}
3117
3118
	public static function get_activation_source( $referer_url ) {
3119
3120
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3121
			return array( 'wp-cli', null );
3122
		}
3123
3124
		$referer = parse_url( $referer_url );
3125
3126
		$source_type = 'unknown';
3127
		$source_query = null;
3128
3129
		if ( ! is_array( $referer ) ) {
3130
			return array( $source_type, $source_query );
3131
		}
3132
3133
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3134
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3135
3136
		if ( isset( $referer['query'] ) ) {
3137
			parse_str( $referer['query'], $query_parts );
3138
		} else {
3139
			$query_parts = array();
3140
		}
3141
3142
		if ( $plugins_path === $referer['path'] ) {
3143
			$source_type = 'list';
3144
		} elseif ( $plugins_install_path === $referer['path'] ) {
3145
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3146
			switch( $tab ) {
3147
				case 'popular':
3148
					$source_type = 'popular';
3149
					break;
3150
				case 'recommended':
3151
					$source_type = 'recommended';
3152
					break;
3153
				case 'favorites':
3154
					$source_type = 'favorites';
3155
					break;
3156
				case 'search':
3157
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3158
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3159
					break;
3160
				default:
3161
					$source_type = 'featured';
3162
			}
3163
		}
3164
3165
		return array( $source_type, $source_query );
3166
	}
3167
3168
	/**
3169
	 * Runs before bumping version numbers up to a new version
3170
	 * @param  string $version    Version:timestamp
3171
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3172
	 * @return null              [description]
3173
	 */
3174
	public static function do_version_bump( $version, $old_version ) {
3175
		if ( ! $old_version ) { // For new sites
3176
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3177
		}
3178
	}
3179
3180
	/**
3181
	 * Sets the internal version number and activation state.
3182
	 * @static
3183
	 */
3184
	public static function plugin_initialize() {
3185
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3186
			Jetpack_Options::update_option( 'activated', 2 );
3187
		}
3188
3189 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3190
			$version = $old_version = JETPACK__VERSION . ':' . time();
3191
			/** This action is documented in class.jetpack.php */
3192
			do_action( 'updating_jetpack_version', $version, false );
3193
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3194
		}
3195
3196
		Jetpack::load_modules();
3197
3198
		Jetpack_Options::delete_option( 'do_activate' );
3199
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3200
	}
3201
3202
	/**
3203
	 * Removes all connection options
3204
	 * @static
3205
	 */
3206
	public static function plugin_deactivation( ) {
3207
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3208
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3209
			Jetpack_Network::init()->deactivate();
3210
		} else {
3211
			Jetpack::disconnect( false );
3212
			//Jetpack_Heartbeat::init()->deactivate();
3213
		}
3214
	}
3215
3216
	/**
3217
	 * Disconnects from the Jetpack servers.
3218
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3219
	 * @static
3220
	 */
3221
	public static function disconnect( $update_activated_state = true ) {
3222
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3223
		Jetpack::clean_nonces( true );
3224
3225
		// If the site is in an IDC because sync is not allowed,
3226
		// let's make sure to not disconnect the production site.
3227
		if ( ! self::validate_sync_error_idc_option() ) {
3228
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3229
			Jetpack::load_xml_rpc_client();
3230
			$xml = new Jetpack_IXR_Client();
3231
			$xml->query( 'jetpack.deregister' );
3232
		}
3233
3234
		Jetpack_Options::delete_option(
3235
			array(
3236
				'blog_token',
3237
				'user_token',
3238
				'user_tokens',
3239
				'master_user',
3240
				'time_diff',
3241
				'fallback_no_verify_ssl_certs',
3242
			)
3243
		);
3244
3245
		Jetpack_IDC::clear_all_idc_options();
3246
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3247
3248
		if ( $update_activated_state ) {
3249
			Jetpack_Options::update_option( 'activated', 4 );
3250
		}
3251
3252
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3253
			// Check then record unique disconnection if site has never been disconnected previously
3254
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3255
				$jetpack_unique_connection['disconnected'] = 1;
3256
			} else {
3257
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3258
					//track unique disconnect
3259
					$jetpack = Jetpack::init();
3260
3261
					$jetpack->stat( 'connections', 'unique-disconnect' );
3262
					$jetpack->do_stats( 'server_side' );
3263
				}
3264
				// increment number of times disconnected
3265
				$jetpack_unique_connection['disconnected'] += 1;
3266
			}
3267
3268
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3269
		}
3270
3271
		// Delete cached connected user data
3272
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3273
		delete_transient( $transient_key );
3274
3275
		// Delete all the sync related data. Since it could be taking up space.
3276
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3277
		Jetpack_Sync_Sender::get_instance()->uninstall();
3278
3279
		// Disable the Heartbeat cron
3280
		Jetpack_Heartbeat::init()->deactivate();
3281
	}
3282
3283
	/**
3284
	 * Unlinks the current user from the linked WordPress.com user
3285
	 */
3286
	public static function unlink_user( $user_id = null ) {
3287
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3288
			return false;
3289
3290
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3291
3292
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3293
			return false;
3294
3295
		if ( ! isset( $tokens[ $user_id ] ) )
3296
			return false;
3297
3298
		Jetpack::load_xml_rpc_client();
3299
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3300
		$xml->query( 'jetpack.unlink_user', $user_id );
3301
3302
		unset( $tokens[ $user_id ] );
3303
3304
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3305
3306
		/**
3307
		 * Fires after the current user has been unlinked from WordPress.com.
3308
		 *
3309
		 * @since 4.1.0
3310
		 *
3311
		 * @param int $user_id The current user's ID.
3312
		 */
3313
		do_action( 'jetpack_unlinked_user', $user_id );
3314
3315
		return true;
3316
	}
3317
3318
	/**
3319
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3320
	 */
3321
	public static function try_registration() {
3322
		// The user has agreed to the TOS at some point by now.
3323
		Jetpack_Options::update_option( 'tos_agreed', true );
3324
3325
		// Let's get some testing in beta versions and such.
3326
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3327
			// Before attempting to connect, let's make sure that the domains are viable.
3328
			$domains_to_check = array_unique( array(
3329
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3330
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3331
			) );
3332
			foreach ( $domains_to_check as $domain ) {
3333
				$result = Jetpack_Data::is_usable_domain( $domain );
3334
				if ( is_wp_error( $result ) ) {
3335
					return $result;
3336
				}
3337
			}
3338
		}
3339
3340
		$result = Jetpack::register();
3341
3342
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3343
		if ( ! $result || is_wp_error( $result ) ) {
3344
			return $result;
3345
		} else {
3346
			return true;
3347
		}
3348
	}
3349
3350
	/**
3351
	 * Tracking an internal event log. Try not to put too much chaff in here.
3352
	 *
3353
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3354
	 */
3355
	public static function log( $code, $data = null ) {
3356
		// only grab the latest 200 entries
3357
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3358
3359
		// Append our event to the log
3360
		$log_entry = array(
3361
			'time'    => time(),
3362
			'user_id' => get_current_user_id(),
3363
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3364
			'code'    => $code,
3365
		);
3366
		// Don't bother storing it unless we've got some.
3367
		if ( ! is_null( $data ) ) {
3368
			$log_entry['data'] = $data;
3369
		}
3370
		$log[] = $log_entry;
3371
3372
		// Try add_option first, to make sure it's not autoloaded.
3373
		// @todo: Add an add_option method to Jetpack_Options
3374
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3375
			Jetpack_Options::update_option( 'log', $log );
3376
		}
3377
3378
		/**
3379
		 * Fires when Jetpack logs an internal event.
3380
		 *
3381
		 * @since 3.0.0
3382
		 *
3383
		 * @param array $log_entry {
3384
		 *	Array of details about the log entry.
3385
		 *
3386
		 *	@param string time Time of the event.
3387
		 *	@param int user_id ID of the user who trigerred the event.
3388
		 *	@param int blog_id Jetpack Blog ID.
3389
		 *	@param string code Unique name for the event.
3390
		 *	@param string data Data about the event.
3391
		 * }
3392
		 */
3393
		do_action( 'jetpack_log_entry', $log_entry );
3394
	}
3395
3396
	/**
3397
	 * Get the internal event log.
3398
	 *
3399
	 * @param $event (string) - only return the specific log events
3400
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3401
	 *
3402
	 * @return array of log events || WP_Error for invalid params
3403
	 */
3404
	public static function get_log( $event = false, $num = false ) {
3405
		if ( $event && ! is_string( $event ) ) {
3406
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3407
		}
3408
3409
		if ( $num && ! is_numeric( $num ) ) {
3410
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3411
		}
3412
3413
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3414
3415
		// If nothing set - act as it did before, otherwise let's start customizing the output
3416
		if ( ! $num && ! $event ) {
3417
			return $entire_log;
3418
		} else {
3419
			$entire_log = array_reverse( $entire_log );
3420
		}
3421
3422
		$custom_log_output = array();
3423
3424
		if ( $event ) {
3425
			foreach ( $entire_log as $log_event ) {
3426
				if ( $event == $log_event[ 'code' ] ) {
3427
					$custom_log_output[] = $log_event;
3428
				}
3429
			}
3430
		} else {
3431
			$custom_log_output = $entire_log;
3432
		}
3433
3434
		if ( $num ) {
3435
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3436
		}
3437
3438
		return $custom_log_output;
3439
	}
3440
3441
	/**
3442
	 * Log modification of important settings.
3443
	 */
3444
	public static function log_settings_change( $option, $old_value, $value ) {
3445
		switch( $option ) {
3446
			case 'jetpack_sync_non_public_post_stati':
3447
				self::log( $option, $value );
3448
				break;
3449
		}
3450
	}
3451
3452
	/**
3453
	 * Return stat data for WPCOM sync
3454
	 */
3455
	public static function get_stat_data( $encode = true, $extended = true ) {
3456
		$data = Jetpack_Heartbeat::generate_stats_array();
3457
3458
		if ( $extended ) {
3459
			$additional_data = self::get_additional_stat_data();
3460
			$data = array_merge( $data, $additional_data );
3461
		}
3462
3463
		if ( $encode ) {
3464
			return json_encode( $data );
3465
		}
3466
3467
		return $data;
3468
	}
3469
3470
	/**
3471
	 * Get additional stat data to sync to WPCOM
3472
	 */
3473
	public static function get_additional_stat_data( $prefix = '' ) {
3474
		$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...
3475
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3476
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3477
		$return["{$prefix}site-count"]     = 0;
3478
3479
		if ( function_exists( 'get_blog_count' ) ) {
3480
			$return["{$prefix}site-count"] = get_blog_count();
3481
		}
3482
		return $return;
3483
	}
3484
3485
	private static function get_site_user_count() {
3486
		global $wpdb;
3487
3488
		if ( function_exists( 'wp_is_large_network' ) ) {
3489
			if ( wp_is_large_network( 'users' ) ) {
3490
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3491
			}
3492
		}
3493 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3494
			// It wasn't there, so regenerate the data and save the transient
3495
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3496
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3497
		}
3498
		return $user_count;
3499
	}
3500
3501
	/* Admin Pages */
3502
3503
	function admin_init() {
3504
		// If the plugin is not connected, display a connect message.
3505
		if (
3506
			// the plugin was auto-activated and needs its candy
3507
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3508
		||
3509
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3510
			! Jetpack_Options::get_option( 'activated' )
3511
		) {
3512
			Jetpack::plugin_initialize();
3513
		}
3514
3515
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3516
			Jetpack_Connection_Banner::init();
3517
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3518
			// Upgrade: 1.1 -> 1.1.1
3519
			// Check and see if host can verify the Jetpack servers' SSL certificate
3520
			$args = array();
3521
			Jetpack_Client::_wp_remote_request(
3522
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3523
				$args,
3524
				true
3525
			);
3526
		}
3527
3528
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3529
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3530
		}
3531
3532
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3533
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3534
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3535
3536
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3537
			// Artificially throw errors in certain whitelisted cases during plugin activation
3538
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3539
		}
3540
3541
		// Add custom column in wp-admin/users.php to show whether user is linked.
3542
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3543
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3544
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3545
	}
3546
3547
	function admin_body_class( $admin_body_class = '' ) {
3548
		$classes = explode( ' ', trim( $admin_body_class ) );
3549
3550
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3551
3552
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3553
		return " $admin_body_class ";
3554
	}
3555
3556
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3557
		return $admin_body_class . ' jetpack-pagestyles ';
3558
	}
3559
3560
	/**
3561
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3562
	 * This function artificially throws errors for such cases (whitelisted).
3563
	 *
3564
	 * @param string $plugin The activated plugin.
3565
	 */
3566
	function throw_error_on_activate_plugin( $plugin ) {
3567
		$active_modules = Jetpack::get_active_modules();
3568
3569
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3570
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3571
			$throw = false;
3572
3573
			// Try and make sure it really was the stats plugin
3574
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3575
				if ( 'stats.php' == basename( $plugin ) ) {
3576
					$throw = true;
3577
				}
3578
			} else {
3579
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3580
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3581
					$throw = true;
3582
				}
3583
			}
3584
3585
			if ( $throw ) {
3586
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3587
			}
3588
		}
3589
	}
3590
3591
	function intercept_plugin_error_scrape_init() {
3592
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3593
	}
3594
3595
	function intercept_plugin_error_scrape( $action, $result ) {
3596
		if ( ! $result ) {
3597
			return;
3598
		}
3599
3600
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3601
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3602
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3603
			}
3604
		}
3605
	}
3606
3607
	function add_remote_request_handlers() {
3608
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3609
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3610
	}
3611
3612
	function remote_request_handlers() {
3613
		$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...
3614
3615
		switch ( current_filter() ) {
3616
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3617
			$response = $this->upload_handler();
3618
			break;
3619
3620
		case 'wp_ajax_nopriv_jetpack_update_file' :
3621
			$response = $this->upload_handler( true );
3622
			break;
3623
		default :
3624
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3625
			break;
3626
		}
3627
3628
		if ( ! $response ) {
3629
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3630
		}
3631
3632
		if ( is_wp_error( $response ) ) {
3633
			$status_code       = $response->get_error_data();
3634
			$error             = $response->get_error_code();
3635
			$error_description = $response->get_error_message();
3636
3637
			if ( ! is_int( $status_code ) ) {
3638
				$status_code = 400;
3639
			}
3640
3641
			status_header( $status_code );
3642
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3643
		}
3644
3645
		status_header( 200 );
3646
		if ( true === $response ) {
3647
			exit;
3648
		}
3649
3650
		die( json_encode( (object) $response ) );
3651
	}
3652
3653
	/**
3654
	 * Uploads a file gotten from the global $_FILES.
3655
	 * If `$update_media_item` is true and `post_id` is defined
3656
	 * the attachment file of the media item (gotten through of the post_id)
3657
	 * will be updated instead of add a new one.
3658
	 *
3659
	 * @param  boolean $update_media_item - update media attachment
3660
	 * @return array - An array describing the uploadind files process
3661
	 */
3662
	function upload_handler( $update_media_item = false ) {
3663
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3664
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3665
		}
3666
3667
		$user = wp_authenticate( '', '' );
3668
		if ( ! $user || is_wp_error( $user ) ) {
3669
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3670
		}
3671
3672
		wp_set_current_user( $user->ID );
3673
3674
		if ( ! current_user_can( 'upload_files' ) ) {
3675
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3676
		}
3677
3678
		if ( empty( $_FILES ) ) {
3679
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3680
		}
3681
3682
		foreach ( array_keys( $_FILES ) as $files_key ) {
3683
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3684
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3685
			}
3686
		}
3687
3688
		$media_keys = array_keys( $_FILES['media'] );
3689
3690
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3691
		if ( ! $token || is_wp_error( $token ) ) {
3692
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3693
		}
3694
3695
		$uploaded_files = array();
3696
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3697
		unset( $GLOBALS['post'] );
3698
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3699
			$file = array();
3700
			foreach ( $media_keys as $media_key ) {
3701
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3702
			}
3703
3704
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3705
3706
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3707
			if ( $hmac_provided !== $hmac_file ) {
3708
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3709
				continue;
3710
			}
3711
3712
			$_FILES['.jetpack.upload.'] = $file;
3713
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3714
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3715
				$post_id = 0;
3716
			}
3717
3718
			if ( $update_media_item ) {
3719
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3720
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3721
				}
3722
3723
				$media_array = $_FILES['media'];
3724
3725
				$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...
3726
				$file_array['type'] = $media_array['type'][0];
3727
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3728
				$file_array['error'] = $media_array['error'][0];
3729
				$file_array['size'] = $media_array['size'][0];
3730
3731
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3732
3733
				if ( is_wp_error( $edited_media_item ) ) {
3734
					return $edited_media_item;
3735
				}
3736
3737
				$response = (object) array(
3738
					'id'   => (string) $post_id,
3739
					'file' => (string) $edited_media_item->post_title,
3740
					'url'  => (string) wp_get_attachment_url( $post_id ),
3741
					'type' => (string) $edited_media_item->post_mime_type,
3742
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3743
				);
3744
3745
				return (array) array( $response );
3746
			}
3747
3748
			$attachment_id = media_handle_upload(
3749
				'.jetpack.upload.',
3750
				$post_id,
3751
				array(),
3752
				array(
3753
					'action' => 'jetpack_upload_file',
3754
				)
3755
			);
3756
3757
			if ( ! $attachment_id ) {
3758
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3759
			} elseif ( is_wp_error( $attachment_id ) ) {
3760
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3761
			} else {
3762
				$attachment = get_post( $attachment_id );
3763
				$uploaded_files[$index] = (object) array(
3764
					'id'   => (string) $attachment_id,
3765
					'file' => $attachment->post_title,
3766
					'url'  => wp_get_attachment_url( $attachment_id ),
3767
					'type' => $attachment->post_mime_type,
3768
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3769
				);
3770
				// Zip files uploads are not supported unless they are done for installation purposed
3771
				// lets delete them in case something goes wrong in this whole process
3772
				if ( 'application/zip' === $attachment->post_mime_type ) {
3773
					// Schedule a cleanup for 2 hours from now in case of failed install.
3774
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3775
				}
3776
			}
3777
		}
3778
		if ( ! is_null( $global_post ) ) {
3779
			$GLOBALS['post'] = $global_post;
3780
		}
3781
3782
		return $uploaded_files;
3783
	}
3784
3785
	/**
3786
	 * Add help to the Jetpack page
3787
	 *
3788
	 * @since Jetpack (1.2.3)
3789
	 * @return false if not the Jetpack page
3790
	 */
3791
	function admin_help() {
3792
		$current_screen = get_current_screen();
3793
3794
		// Overview
3795
		$current_screen->add_help_tab(
3796
			array(
3797
				'id'		=> 'home',
3798
				'title'		=> __( 'Home', 'jetpack' ),
3799
				'content'	=>
3800
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3801
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3802
					'<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>',
3803
			)
3804
		);
3805
3806
		// Screen Content
3807
		if ( current_user_can( 'manage_options' ) ) {
3808
			$current_screen->add_help_tab(
3809
				array(
3810
					'id'		=> 'settings',
3811
					'title'		=> __( 'Settings', 'jetpack' ),
3812
					'content'	=>
3813
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3814
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3815
						'<ol>' .
3816
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3817
							'<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>' .
3818
						'</ol>' .
3819
						'<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>'
3820
				)
3821
			);
3822
		}
3823
3824
		// Help Sidebar
3825
		$current_screen->set_help_sidebar(
3826
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3827
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3828
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3829
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3830
		);
3831
	}
3832
3833
	function admin_menu_css() {
3834
		wp_enqueue_style( 'jetpack-icons' );
3835
	}
3836
3837
	function admin_menu_order() {
3838
		return true;
3839
	}
3840
3841 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3842
		$jp_menu_order = array();
3843
3844
		foreach ( $menu_order as $index => $item ) {
3845
			if ( $item != 'jetpack' ) {
3846
				$jp_menu_order[] = $item;
3847
			}
3848
3849
			if ( $index == 0 ) {
3850
				$jp_menu_order[] = 'jetpack';
3851
			}
3852
		}
3853
3854
		return $jp_menu_order;
3855
	}
3856
3857
	function admin_banner_styles() {
3858
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3859
3860
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3861
			wp_register_style(
3862
				'jetpack-dops-style',
3863
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3864
				array(),
3865
				JETPACK__VERSION
3866
			);
3867
		}
3868
3869
		wp_enqueue_style(
3870
			'jetpack',
3871
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3872
			array( 'jetpack-dops-style' ),
3873
			 JETPACK__VERSION . '-20121016'
3874
		);
3875
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3876
		wp_style_add_data( 'jetpack', 'suffix', $min );
3877
	}
3878
3879
	function plugin_action_links( $actions ) {
3880
3881
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3882
3883
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3884
			return array_merge(
3885
				$jetpack_home,
3886
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3887
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3888
				$actions
3889
				);
3890
			}
3891
3892
		return array_merge( $jetpack_home, $actions );
3893
	}
3894
3895
	/*
3896
	 * Registration flow:
3897
	 * 1 - ::admin_page_load() action=register
3898
	 * 2 - ::try_registration()
3899
	 * 3 - ::register()
3900
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3901
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3902
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3903
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3904
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3905
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3906
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3907
	 *       jetpack_id, jetpack_secret, jetpack_public
3908
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3909
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3910
	 * 5 - user logs in with WP.com account
3911
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3912
	 *		- Jetpack_Client_Server::authorize()
3913
	 *		- Jetpack_Client_Server::get_token()
3914
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3915
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3916
	 *			- which responds with access_token, token_type, scope
3917
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3918
	 *		- Jetpack::activate_default_modules()
3919
	 *     		- Deactivates deprecated plugins
3920
	 *     		- Activates all default modules
3921
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3922
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3923
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3924
	 *     Done!
3925
	 */
3926
3927
	/**
3928
	 * Handles the page load events for the Jetpack admin page
3929
	 */
3930
	function admin_page_load() {
3931
		$error = false;
3932
3933
		// Make sure we have the right body class to hook stylings for subpages off of.
3934
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3935
3936
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3937
			// Should only be used in intermediate redirects to preserve state across redirects
3938
			Jetpack::restate();
3939
		}
3940
3941
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3942
			// User clicked in the iframe to link their accounts
3943
			if ( ! Jetpack::is_user_connected() ) {
3944
				$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3945
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3946
3947
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3948
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3949
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3950
3951
				if ( isset( $_GET['notes_iframe'] ) )
3952
					$connect_url .= '&notes_iframe';
3953
				wp_redirect( $connect_url );
3954
				exit;
3955
			} else {
3956
				if ( ! isset( $_GET['calypso_env'] ) ) {
3957
					Jetpack::state( 'message', 'already_authorized' );
3958
					wp_safe_redirect( Jetpack::admin_url() );
3959
					exit;
3960
				} else {
3961
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
3962
					$connect_url .= '&already_authorized=true';
3963
					wp_redirect( $connect_url );
3964
					exit;
3965
				}
3966
			}
3967
		}
3968
3969
3970
		if ( isset( $_GET['action'] ) ) {
3971
			switch ( $_GET['action'] ) {
3972
			case 'authorize':
3973
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3974
					Jetpack::state( 'message', 'already_authorized' );
3975
					wp_safe_redirect( Jetpack::admin_url() );
3976
					exit;
3977
				}
3978
				Jetpack::log( 'authorize' );
3979
				$client_server = new Jetpack_Client_Server;
3980
				$client_server->client_authorize();
3981
				exit;
3982
			case 'register' :
3983
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3984
					$error = 'cheatin';
3985
					break;
3986
				}
3987
				check_admin_referer( 'jetpack-register' );
3988
				Jetpack::log( 'register' );
3989
				Jetpack::maybe_set_version_option();
3990
				$registered = Jetpack::try_registration();
3991
				if ( is_wp_error( $registered ) ) {
3992
					$error = $registered->get_error_code();
3993
					Jetpack::state( 'error', $error );
3994
					Jetpack::state( 'error', $registered->get_error_message() );
3995
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
3996
						'error_code' => $error,
3997
						'error_message' => $registered->get_error_message()
3998
					) );
3999
					break;
4000
				}
4001
4002
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4003
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4004
4005
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4006
					'from' => $from
4007
				) );
4008
4009
				$url = $this->build_connect_url( true, $redirect, $from );
4010
4011
				if ( ! empty( $_GET['onboarding'] ) ) {
4012
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4013
				}
4014
4015
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4016
					$url = add_query_arg( 'auth_approved', 'true', $url );
4017
				}
4018
4019
				wp_redirect( $url );
4020
				exit;
4021
			case 'activate' :
4022
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4023
					$error = 'cheatin';
4024
					break;
4025
				}
4026
4027
				$module = stripslashes( $_GET['module'] );
4028
				check_admin_referer( "jetpack_activate-$module" );
4029
				Jetpack::log( 'activate', $module );
4030
				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...
4031
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4032
				}
4033
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4034
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4035
				exit;
4036
			case 'activate_default_modules' :
4037
				check_admin_referer( 'activate_default_modules' );
4038
				Jetpack::log( 'activate_default_modules' );
4039
				Jetpack::restate();
4040
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4041
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4042
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4043
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4044
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4045
				exit;
4046
			case 'disconnect' :
4047
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4048
					$error = 'cheatin';
4049
					break;
4050
				}
4051
4052
				check_admin_referer( 'jetpack-disconnect' );
4053
				Jetpack::log( 'disconnect' );
4054
				Jetpack::disconnect();
4055
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4056
				exit;
4057
			case 'reconnect' :
4058
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4059
					$error = 'cheatin';
4060
					break;
4061
				}
4062
4063
				check_admin_referer( 'jetpack-reconnect' );
4064
				Jetpack::log( 'reconnect' );
4065
				$this->disconnect();
4066
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4067
				exit;
4068 View Code Duplication
			case 'deactivate' :
4069
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4070
					$error = 'cheatin';
4071
					break;
4072
				}
4073
4074
				$modules = stripslashes( $_GET['module'] );
4075
				check_admin_referer( "jetpack_deactivate-$modules" );
4076
				foreach ( explode( ',', $modules ) as $module ) {
4077
					Jetpack::log( 'deactivate', $module );
4078
					Jetpack::deactivate_module( $module );
4079
					Jetpack::state( 'message', 'module_deactivated' );
4080
				}
4081
				Jetpack::state( 'module', $modules );
4082
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4083
				exit;
4084
			case 'unlink' :
4085
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4086
				check_admin_referer( 'jetpack-unlink' );
4087
				Jetpack::log( 'unlink' );
4088
				$this->unlink_user();
4089
				Jetpack::state( 'message', 'unlinked' );
4090
				if ( 'sub-unlink' == $redirect ) {
4091
					wp_safe_redirect( admin_url() );
4092
				} else {
4093
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4094
				}
4095
				exit;
4096
			case 'onboard' :
4097
				if ( ! current_user_can( 'manage_options' ) ) {
4098
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4099
				} else {
4100
					Jetpack::create_onboarding_token();
4101
					$url = $this->build_connect_url( true );
4102
4103
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4104
						$url = add_query_arg( 'onboarding', $token, $url );
4105
					}
4106
4107
					$calypso_env = ! empty( $_GET[ 'calypso_env' ] ) ? $_GET[ 'calypso_env' ] : false;
4108
					if ( $calypso_env ) {
4109
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4110
					}
4111
4112
					wp_redirect( $url );
4113
					exit;
4114
				}
4115
				exit;
4116
			default:
4117
				/**
4118
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4119
				 *
4120
				 * @since 2.6.0
4121
				 *
4122
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4123
				 */
4124
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4125
			}
4126
		}
4127
4128
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4129
			self::activate_new_modules( true );
4130
		}
4131
4132
		$message_code = Jetpack::state( 'message' );
4133
		if ( Jetpack::state( 'optin-manage' ) ) {
4134
			$activated_manage = $message_code;
4135
			$message_code = 'jetpack-manage';
4136
		}
4137
4138
		switch ( $message_code ) {
4139
		case 'jetpack-manage':
4140
			$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>';
4141
			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...
4142
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4143
			}
4144
			break;
4145
4146
		}
4147
4148
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4149
4150
		if ( ! empty( $deactivated_plugins ) ) {
4151
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4152
			$deactivated_titles  = array();
4153
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4154
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4155
					continue;
4156
				}
4157
4158
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4159
			}
4160
4161
			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...
4162
				if ( $this->message ) {
4163
					$this->message .= "<br /><br />\n";
4164
				}
4165
4166
				$this->message .= wp_sprintf(
4167
					_n(
4168
						'Jetpack contains the most recent version of the old %l plugin.',
4169
						'Jetpack contains the most recent versions of the old %l plugins.',
4170
						count( $deactivated_titles ),
4171
						'jetpack'
4172
					),
4173
					$deactivated_titles
4174
				);
4175
4176
				$this->message .= "<br />\n";
4177
4178
				$this->message .= _n(
4179
					'The old version has been deactivated and can be removed from your site.',
4180
					'The old versions have been deactivated and can be removed from your site.',
4181
					count( $deactivated_titles ),
4182
					'jetpack'
4183
				);
4184
			}
4185
		}
4186
4187
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4188
4189
		if ( $this->message || $this->error || $this->privacy_checks ) {
4190
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4191
		}
4192
4193
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4194
	}
4195
4196
	function admin_notices() {
4197
4198
		if ( $this->error ) {
4199
?>
4200
<div id="message" class="jetpack-message jetpack-err">
4201
	<div class="squeezer">
4202
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4203
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4204
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4205
<?php	endif; ?>
4206
	</div>
4207
</div>
4208
<?php
4209
		}
4210
4211
		if ( $this->message ) {
4212
?>
4213
<div id="message" class="jetpack-message">
4214
	<div class="squeezer">
4215
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4216
	</div>
4217
</div>
4218
<?php
4219
		}
4220
4221
		if ( $this->privacy_checks ) :
4222
			$module_names = $module_slugs = array();
4223
4224
			$privacy_checks = explode( ',', $this->privacy_checks );
4225
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4226
			foreach ( $privacy_checks as $module_slug ) {
4227
				$module = Jetpack::get_module( $module_slug );
4228
				if ( ! $module ) {
4229
					continue;
4230
				}
4231
4232
				$module_slugs[] = $module_slug;
4233
				$module_names[] = "<strong>{$module['name']}</strong>";
4234
			}
4235
4236
			$module_slugs = join( ',', $module_slugs );
4237
?>
4238
<div id="message" class="jetpack-message jetpack-err">
4239
	<div class="squeezer">
4240
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4241
		<p><?php
4242
			echo wp_kses(
4243
				wptexturize(
4244
					wp_sprintf(
4245
						_nx(
4246
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4247
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4248
							count( $privacy_checks ),
4249
							'%l = list of Jetpack module/feature names',
4250
							'jetpack'
4251
						),
4252
						$module_names
4253
					)
4254
				),
4255
				array( 'strong' => true )
4256
			);
4257
4258
			echo "\n<br />\n";
4259
4260
			echo wp_kses(
4261
				sprintf(
4262
					_nx(
4263
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4264
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4265
						count( $privacy_checks ),
4266
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4267
						'jetpack'
4268
					),
4269
					wp_nonce_url(
4270
						Jetpack::admin_url(
4271
							array(
4272
								'page'   => 'jetpack',
4273
								'action' => 'deactivate',
4274
								'module' => urlencode( $module_slugs ),
4275
							)
4276
						),
4277
						"jetpack_deactivate-$module_slugs"
4278
					),
4279
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4280
				),
4281
				array( 'a' => array( 'href' => true, 'title' => true ) )
4282
			);
4283
		?></p>
4284
	</div>
4285
</div>
4286
<?php endif;
4287
	}
4288
4289
	/**
4290
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4291
	 */
4292
	function stat( $group, $detail ) {
4293
		if ( ! isset( $this->stats[ $group ] ) )
4294
			$this->stats[ $group ] = array();
4295
		$this->stats[ $group ][] = $detail;
4296
	}
4297
4298
	/**
4299
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4300
	 */
4301
	function do_stats( $method = '' ) {
4302
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4303
			foreach ( $this->stats as $group => $stats ) {
4304
				if ( is_array( $stats ) && count( $stats ) ) {
4305
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4306
					if ( 'server_side' === $method ) {
4307
						self::do_server_side_stat( $args );
4308
					} else {
4309
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4310
					}
4311
				}
4312
				unset( $this->stats[ $group ] );
4313
			}
4314
		}
4315
	}
4316
4317
	/**
4318
	 * Runs stats code for a one-off, server-side.
4319
	 *
4320
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4321
	 *
4322
	 * @return bool If it worked.
4323
	 */
4324
	static function do_server_side_stat( $args ) {
4325
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4326
		if ( is_wp_error( $response ) )
4327
			return false;
4328
4329
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4330
			return false;
4331
4332
		return true;
4333
	}
4334
4335
	/**
4336
	 * Builds the stats url.
4337
	 *
4338
	 * @param $args array|string The arguments to append to the URL.
4339
	 *
4340
	 * @return string The URL to be pinged.
4341
	 */
4342
	static function build_stats_url( $args ) {
4343
		$defaults = array(
4344
			'v'    => 'wpcom2',
4345
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4346
		);
4347
		$args     = wp_parse_args( $args, $defaults );
4348
		/**
4349
		 * Filter the URL used as the Stats tracking pixel.
4350
		 *
4351
		 * @since 2.3.2
4352
		 *
4353
		 * @param string $url Base URL used as the Stats tracking pixel.
4354
		 */
4355
		$base_url = apply_filters(
4356
			'jetpack_stats_base_url',
4357
			'https://pixel.wp.com/g.gif'
4358
		);
4359
		$url      = add_query_arg( $args, $base_url );
4360
		return $url;
4361
	}
4362
4363
	static function translate_current_user_to_role() {
4364
		foreach ( self::$capability_translations as $role => $cap ) {
4365
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4366
				return $role;
4367
			}
4368
		}
4369
4370
		return false;
4371
	}
4372
4373
	static function translate_user_to_role( $user ) {
4374
		foreach ( self::$capability_translations as $role => $cap ) {
4375
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4376
				return $role;
4377
			}
4378
		}
4379
4380
		return false;
4381
    }
4382
4383
	static function translate_role_to_cap( $role ) {
4384
		if ( ! isset( self::$capability_translations[$role] ) ) {
4385
			return false;
4386
		}
4387
4388
		return self::$capability_translations[$role];
4389
	}
4390
4391
	static function sign_role( $role, $user_id = null ) {
4392
		if ( empty( $user_id ) ) {
4393
			$user_id = (int) get_current_user_id();
4394
		}
4395
4396
		if ( ! $user_id  ) {
4397
			return false;
4398
		}
4399
4400
		$token = Jetpack_Data::get_access_token();
4401
		if ( ! $token || is_wp_error( $token ) ) {
4402
			return false;
4403
		}
4404
4405
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4406
	}
4407
4408
4409
	/**
4410
	 * Builds a URL to the Jetpack connection auth page
4411
	 *
4412
	 * @since 3.9.5
4413
	 *
4414
	 * @param bool $raw If true, URL will not be escaped.
4415
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4416
	 *                              If string, will be a custom redirect.
4417
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4418
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4419
	 *
4420
	 * @return string Connect URL
4421
	 */
4422
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4423
		$site_id = Jetpack_Options::get_option( 'id' );
4424
		$token = Jetpack_Options::get_option( 'blog_token' );
4425
4426
		if ( $register || ! $token || ! $site_id ) {
4427
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4428
4429
			if ( ! empty( $redirect ) ) {
4430
				$url = add_query_arg(
4431
					'redirect',
4432
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4433
					$url
4434
				);
4435
			}
4436
4437
			if( is_network_admin() ) {
4438
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4439
			}
4440
		} else {
4441
4442
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4443
			// because otherwise this logic can get us in to a loop.
4444
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4445
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4446
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4447
4448
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4449
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4450
					'1.1'
4451
				);
4452
4453
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4454
					// Generating a register URL instead to refresh the existing token
4455
					return $this->build_connect_url( $raw, $redirect, $from, true );
4456
				}
4457
			}
4458
4459
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4460
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4461
			}
4462
4463
			$role = self::translate_current_user_to_role();
4464
			$signed_role = self::sign_role( $role );
4465
4466
			$user = wp_get_current_user();
4467
4468
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4469
			$redirect = $redirect
4470
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4471
				: $jetpack_admin_page;
4472
4473
			if( isset( $_REQUEST['is_multisite'] ) ) {
4474
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4475
			}
4476
4477
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4478
4479
			/**
4480
			 * Filter the type of authorization.
4481
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4482
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4483
			 *
4484
			 * @since 4.3.3
4485
			 *
4486
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4487
			 */
4488
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4489
4490
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4491
4492
			$args = urlencode_deep(
4493
				array(
4494
					'response_type' => 'code',
4495
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4496
					'redirect_uri'  => add_query_arg(
4497
						array(
4498
							'action'   => 'authorize',
4499
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4500
							'redirect' => urlencode( $redirect ),
4501
						),
4502
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4503
					),
4504
					'state'         => $user->ID,
4505
					'scope'         => $signed_role,
4506
					'user_email'    => $user->user_email,
4507
					'user_login'    => $user->user_login,
4508
					'is_active'     => Jetpack::is_active(),
4509
					'jp_version'    => JETPACK__VERSION,
4510
					'auth_type'     => $auth_type,
4511
					'secret'        => $secrets['secret_1'],
4512
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4513
					'blogname'      => get_option( 'blogname' ),
4514
					'site_url'      => site_url(),
4515
					'home_url'      => home_url(),
4516
					'site_icon'     => get_site_icon_url(),
4517
					'site_lang'     => get_locale(),
4518
					'_ui'           => $tracks_identity['_ui'],
4519
					'_ut'           => $tracks_identity['_ut'],
4520
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4521
				)
4522
			);
4523
4524
			self::apply_activation_source_to_args( $args );
4525
4526
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4527
		}
4528
4529
		if ( $from ) {
4530
			$url = add_query_arg( 'from', $from, $url );
4531
		}
4532
4533
		// Ensure that class to get the affiliate code is loaded
4534
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4535
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4536
		}
4537
		// Get affiliate code and add it to the URL
4538
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4539
4540
		if ( isset( $_GET['calypso_env'] ) ) {
4541
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4542
		}
4543
4544
		return $raw ? $url : esc_url( $url );
4545
	}
4546
4547
	/**
4548
	 * Get our assumed site creation date.
4549
	 * Calculated based on the earlier date of either:
4550
	 * - Earliest admin user registration date.
4551
	 * - Earliest date of post of any post type.
4552
	 *
4553
	 * @since 7.2.0
4554
	 *
4555
	 * @return string Assumed site creation date and time.
4556
	 */
4557
	public static function get_assumed_site_creation_date() {
4558
		$earliest_registered_users = get_users( array(
4559
			'role'    => 'administrator',
4560
			'orderby' => 'user_registered',
4561
			'order'   => 'ASC',
4562
			'fields'  => array( 'user_registered' ),
4563
			'number'  => 1,
4564
		) );
4565
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4566
4567
		$earliest_posts = get_posts( array(
4568
			'posts_per_page' => 1,
4569
			'post_type'      => 'any',
4570
			'post_status'    => 'any',
4571
			'orderby'        => 'date',
4572
			'order'          => 'ASC',
4573
		) );
4574
4575
		// If there are no posts at all, we'll count only on user registration date.
4576
		if ( $earliest_posts ) {
4577
			$earliest_post_date = $earliest_posts[0]->post_date;
4578
		} else {
4579
			$earliest_post_date = PHP_INT_MAX;
4580
		}
4581
4582
		return min( $earliest_registration_date, $earliest_post_date );
4583
	}
4584
4585
	public static function apply_activation_source_to_args( &$args ) {
4586
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4587
4588
		if ( $activation_source_name ) {
4589
			$args['_as'] = urlencode( $activation_source_name );
4590
		}
4591
4592
		if ( $activation_source_keyword ) {
4593
			$args['_ak'] = urlencode( $activation_source_keyword );
4594
		}
4595
	}
4596
4597
	function build_reconnect_url( $raw = false ) {
4598
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4599
		return $raw ? $url : esc_url( $url );
4600
	}
4601
4602
	public static function admin_url( $args = null ) {
4603
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4604
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4605
		return $url;
4606
	}
4607
4608
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4609
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4610
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4611
	}
4612
4613
	function dismiss_jetpack_notice() {
4614
4615
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4616
			return;
4617
		}
4618
4619
		switch( $_GET['jetpack-notice'] ) {
4620
			case 'dismiss':
4621
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4622
4623
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4624
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4625
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4626
				}
4627
				break;
4628
			case 'jetpack-protect-multisite-opt-out':
4629
4630
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4631
					// Don't show the banner again
4632
4633
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4634
					// redirect back to the page that had the notice
4635
					if ( wp_get_referer() ) {
4636
						wp_safe_redirect( wp_get_referer() );
4637
					} else {
4638
						// Take me to Jetpack
4639
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4640
					}
4641
				}
4642
				break;
4643
		}
4644
	}
4645
4646
	public static function sort_modules( $a, $b ) {
4647
		if ( $a['sort'] == $b['sort'] )
4648
			return 0;
4649
4650
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4651
	}
4652
4653
	function ajax_recheck_ssl() {
4654
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4655
		$result = Jetpack::permit_ssl( true );
4656
		wp_send_json( array(
4657
			'enabled' => $result,
4658
			'message' => get_transient( 'jetpack_https_test_message' )
4659
		) );
4660
	}
4661
4662
/* Client API */
4663
4664
	/**
4665
	 * Returns the requested Jetpack API URL
4666
	 *
4667
	 * @return string
4668
	 */
4669
	public static function api_url( $relative_url ) {
4670
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4671
	}
4672
4673
	/**
4674
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4675
	 */
4676
	public static function fix_url_for_bad_hosts( $url ) {
4677
		if ( 0 !== strpos( $url, 'https://' ) ) {
4678
			return $url;
4679
		}
4680
4681
		switch ( JETPACK_CLIENT__HTTPS ) {
4682
			case 'ALWAYS' :
4683
				return $url;
4684
			case 'NEVER' :
4685
				return set_url_scheme( $url, 'http' );
4686
			// default : case 'AUTO' :
4687
		}
4688
4689
		// we now return the unmodified SSL URL by default, as a security precaution
4690
		return $url;
4691
	}
4692
4693
	/**
4694
	 * Create a random secret for validating onboarding payload
4695
	 *
4696
	 * @return string Secret token
4697
	 */
4698
	public static function create_onboarding_token() {
4699
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4700
			$token = wp_generate_password( 32, false );
4701
			Jetpack_Options::update_option( 'onboarding', $token );
4702
		}
4703
4704
		return $token;
4705
	}
4706
4707
	/**
4708
	 * Remove the onboarding token
4709
	 *
4710
	 * @return bool True on success, false on failure
4711
	 */
4712
	public static function invalidate_onboarding_token() {
4713
		return Jetpack_Options::delete_option( 'onboarding' );
4714
	}
4715
4716
	/**
4717
	 * Validate an onboarding token for a specific action
4718
	 *
4719
	 * @return boolean True if token/action pair is accepted, false if not
4720
	 */
4721
	public static function validate_onboarding_token_action( $token, $action ) {
4722
		// Compare tokens, bail if tokens do not match
4723
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4724
			return false;
4725
		}
4726
4727
		// List of valid actions we can take
4728
		$valid_actions = array(
4729
			'/jetpack/v4/settings',
4730
		);
4731
4732
		// Whitelist the action
4733
		if ( ! in_array( $action, $valid_actions ) ) {
4734
			return false;
4735
		}
4736
4737
		return true;
4738
	}
4739
4740
	/**
4741
	 * Checks to see if the URL is using SSL to connect with Jetpack
4742
	 *
4743
	 * @since 2.3.3
4744
	 * @return boolean
4745
	 */
4746
	public static function permit_ssl( $force_recheck = false ) {
4747
		// Do some fancy tests to see if ssl is being supported
4748
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4749
			$message = '';
4750
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4751
				$ssl = 0;
4752
			} else {
4753
				switch ( JETPACK_CLIENT__HTTPS ) {
4754
					case 'NEVER':
4755
						$ssl = 0;
4756
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4757
						break;
4758
					case 'ALWAYS':
4759
					case 'AUTO':
4760
					default:
4761
						$ssl = 1;
4762
						break;
4763
				}
4764
4765
				// If it's not 'NEVER', test to see
4766
				if ( $ssl ) {
4767
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4768
						$ssl = 0;
4769
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4770
					} else {
4771
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4772
						if ( is_wp_error( $response ) ) {
4773
							$ssl = 0;
4774
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4775
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4776
							$ssl = 0;
4777
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4778
						}
4779
					}
4780
				}
4781
			}
4782
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4783
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4784
		}
4785
4786
		return (bool) $ssl;
4787
	}
4788
4789
	/*
4790
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4791
	 */
4792
	public function alert_auto_ssl_fail() {
4793
		if ( ! current_user_can( 'manage_options' ) )
4794
			return;
4795
4796
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4797
		?>
4798
4799
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4800
			<div class="jp-banner__content">
4801
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4802
				<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>
4803
				<p>
4804
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4805
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4806
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4807
				</p>
4808
				<p>
4809
					<?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' ),
4810
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4811
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4812
				</p>
4813
			</div>
4814
		</div>
4815
		<style>
4816
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4817
		</style>
4818
		<script type="text/javascript">
4819
			jQuery( document ).ready( function( $ ) {
4820
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4821
					var $this = $( this );
4822
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4823
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4824
					e.preventDefault();
4825
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4826
					$.post( ajaxurl, data )
4827
					  .done( function( response ) {
4828
					  	if ( response.enabled ) {
4829
					  		$( '#jetpack-ssl-warning' ).hide();
4830
					  	} else {
4831
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4832
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4833
					  	}
4834
					  }.bind( $this ) );
4835
				} );
4836
			} );
4837
		</script>
4838
4839
		<?php
4840
	}
4841
4842
	/**
4843
	 * Returns the Jetpack XML-RPC API
4844
	 *
4845
	 * @return string
4846
	 */
4847
	public static function xmlrpc_api_url() {
4848
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4849
		return untrailingslashit( $base ) . '/xmlrpc.php';
4850
	}
4851
4852
	/**
4853
	 * Creates two secret tokens and the end of life timestamp for them.
4854
	 *
4855
	 * Note these tokens are unique per call, NOT static per site for connecting.
4856
	 *
4857
	 * @since 2.6
4858
	 * @return array
4859
	 */
4860
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4861
		if ( ! $user_id ) {
4862
			$user_id = get_current_user_id();
4863
		}
4864
4865
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
4866
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4867
4868
		if (
4869
			isset( $secrets[ $secret_name ] ) &&
4870
			$secrets[ $secret_name ]['exp'] > time()
4871
		) {
4872
			return $secrets[ $secret_name ];
4873
		}
4874
4875
		$secret_value = array(
4876
			'secret_1'  => wp_generate_password( 32, false ),
4877
			'secret_2'  => wp_generate_password( 32, false ),
4878
			'exp'       => time() + $exp,
4879
		);
4880
4881
		$secrets[ $secret_name ] = $secret_value;
4882
4883
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4884
		return $secrets[ $secret_name ];
4885
	}
4886
4887
	public static function get_secrets( $action, $user_id ) {
4888
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4889
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4890
4891
		if ( ! isset( $secrets[ $secret_name ] ) ) {
4892
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4893
		}
4894
4895
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
4896
			self::delete_secrets( $action, $user_id );
4897
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4898
		}
4899
4900
		return $secrets[ $secret_name ];
4901
	}
4902
4903
	public static function delete_secrets( $action, $user_id ) {
4904
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
4905
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
4906
		if ( isset( $secrets[ $secret_name ] ) ) {
4907
			unset( $secrets[ $secret_name ] );
4908
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
4909
		}
4910
	}
4911
4912
	/**
4913
	 * Builds the timeout limit for queries talking with the wpcom servers.
4914
	 *
4915
	 * Based on local php max_execution_time in php.ini
4916
	 *
4917
	 * @since 2.6
4918
	 * @return int
4919
	 * @deprecated
4920
	 **/
4921
	public function get_remote_query_timeout_limit() {
4922
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4923
		return Jetpack::get_max_execution_time();
4924
	}
4925
4926
	/**
4927
	 * Builds the timeout limit for queries talking with the wpcom servers.
4928
	 *
4929
	 * Based on local php max_execution_time in php.ini
4930
	 *
4931
	 * @since 5.4
4932
	 * @return int
4933
	 **/
4934
	public static function get_max_execution_time() {
4935
		$timeout = (int) ini_get( 'max_execution_time' );
4936
4937
		// Ensure exec time set in php.ini
4938
		if ( ! $timeout ) {
4939
			$timeout = 30;
4940
		}
4941
		return $timeout;
4942
	}
4943
4944
	/**
4945
	 * Sets a minimum request timeout, and returns the current timeout
4946
	 *
4947
	 * @since 5.4
4948
	 **/
4949
	public static function set_min_time_limit( $min_timeout ) {
4950
		$timeout = self::get_max_execution_time();
4951
		if ( $timeout < $min_timeout ) {
4952
			$timeout = $min_timeout;
4953
			set_time_limit( $timeout );
4954
		}
4955
		return $timeout;
4956
	}
4957
4958
4959
	/**
4960
	 * Takes the response from the Jetpack register new site endpoint and
4961
	 * verifies it worked properly.
4962
	 *
4963
	 * @since 2.6
4964
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4965
	 **/
4966
	public function validate_remote_register_response( $response ) {
4967
	  if ( is_wp_error( $response ) ) {
4968
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
4969
		}
4970
4971
		$code   = wp_remote_retrieve_response_code( $response );
4972
		$entity = wp_remote_retrieve_body( $response );
4973
		if ( $entity )
4974
			$registration_response = json_decode( $entity );
4975
		else
4976
			$registration_response = false;
4977
4978
		$code_type = intval( $code / 100 );
4979
		if ( 5 == $code_type ) {
4980
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4981
		} elseif ( 408 == $code ) {
4982
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4983
		} elseif ( ! empty( $registration_response->error ) ) {
4984
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4985
				$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' );
4986
			} else {
4987
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4988
			}
4989
4990
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
4991
		} elseif ( 200 != $code ) {
4992
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
4993
		}
4994
4995
		// Jetpack ID error block
4996
		if ( empty( $registration_response->jetpack_id ) ) {
4997
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
4998
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4999
			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 );
5000
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5001
			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 );
5002
		}
5003
5004
	    return $registration_response;
5005
	}
5006
	/**
5007
	 * @return bool|WP_Error
5008
	 */
5009
	public static function register() {
5010
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5011
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5012
		$secrets = Jetpack::generate_secrets( 'register' );
5013
5014 View Code Duplication
		if (
5015
			empty( $secrets['secret_1'] ) ||
5016
			empty( $secrets['secret_2'] ) ||
5017
			empty( $secrets['exp'] )
5018
		) {
5019
			return new Jetpack_Error( 'missing_secrets' );
5020
		}
5021
5022
		// better to try (and fail) to set a higher timeout than this system
5023
		// supports than to have register fail for more users than it should
5024
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5025
5026
		$gmt_offset = get_option( 'gmt_offset' );
5027
		if ( ! $gmt_offset ) {
5028
			$gmt_offset = 0;
5029
		}
5030
5031
		$stats_options = get_option( 'stats_options' );
5032
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5033
5034
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5035
5036
		$args = array(
5037
			'method'  => 'POST',
5038
			'body'    => array(
5039
				'siteurl'         => site_url(),
5040
				'home'            => home_url(),
5041
				'gmt_offset'      => $gmt_offset,
5042
				'timezone_string' => (string) get_option( 'timezone_string' ),
5043
				'site_name'       => (string) get_option( 'blogname' ),
5044
				'secret_1'        => $secrets['secret_1'],
5045
				'secret_2'        => $secrets['secret_2'],
5046
				'site_lang'       => get_locale(),
5047
				'timeout'         => $timeout,
5048
				'stats_id'        => $stats_id,
5049
				'state'           => get_current_user_id(),
5050
				'_ui'             => $tracks_identity['_ui'],
5051
				'_ut'             => $tracks_identity['_ut'],
5052
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5053
				'jetpack_version' => JETPACK__VERSION
5054
			),
5055
			'headers' => array(
5056
				'Accept' => 'application/json',
5057
			),
5058
			'timeout' => $timeout,
5059
		);
5060
5061
		self::apply_activation_source_to_args( $args['body'] );
5062
5063
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5064
5065
		// Make sure the response is valid and does not contain any Jetpack errors
5066
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5067
		if ( is_wp_error( $registration_details ) ) {
5068
			return $registration_details;
5069
		} elseif ( ! $registration_details ) {
5070
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5071
		}
5072
5073 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5074
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5075
		}
5076
5077
		if ( isset( $registration_details->jetpack_public ) ) {
5078
			$jetpack_public = (int) $registration_details->jetpack_public;
5079
		} else {
5080
			$jetpack_public = false;
5081
		}
5082
5083
		Jetpack_Options::update_options(
5084
			array(
5085
				'id'         => (int)    $registration_details->jetpack_id,
5086
				'blog_token' => (string) $registration_details->jetpack_secret,
5087
				'public'     => $jetpack_public,
5088
			)
5089
		);
5090
5091
		/**
5092
		 * Fires when a site is registered on WordPress.com.
5093
		 *
5094
		 * @since 3.7.0
5095
		 *
5096
		 * @param int $json->jetpack_id Jetpack Blog ID.
5097
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5098
		 * @param int|bool $jetpack_public Is the site public.
5099
		 */
5100
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5101
5102
		// Initialize Jump Start for the first and only time.
5103
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5104
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5105
5106
			$jetpack = Jetpack::init();
5107
5108
			$jetpack->stat( 'jumpstart', 'unique-views' );
5109
			$jetpack->do_stats( 'server_side' );
5110
		};
5111
5112
		return true;
5113
	}
5114
5115
	/**
5116
	 * If the db version is showing something other that what we've got now, bump it to current.
5117
	 *
5118
	 * @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...
5119
	 */
5120
	public static function maybe_set_version_option() {
5121
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5122
		if ( JETPACK__VERSION != $version ) {
5123
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5124
5125
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5126
				/** This action is documented in class.jetpack.php */
5127
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5128
			}
5129
5130
			return true;
5131
		}
5132
		return false;
5133
	}
5134
5135
/* Client Server API */
5136
5137
	/**
5138
	 * Loads the Jetpack XML-RPC client
5139
	 */
5140
	public static function load_xml_rpc_client() {
5141
		require_once ABSPATH . WPINC . '/class-IXR.php';
5142
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5143
	}
5144
5145
	/**
5146
	 * Resets the saved authentication state in between testing requests.
5147
	 */
5148
	public function reset_saved_auth_state() {
5149
		$this->xmlrpc_verification = null;
5150
		$this->rest_authentication_status = null;
5151
	}
5152
5153
	function verify_xml_rpc_signature() {
5154
		if ( $this->xmlrpc_verification ) {
5155
			return $this->xmlrpc_verification;
5156
		}
5157
5158
		// It's not for us
5159
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5160
			return false;
5161
		}
5162
5163
		@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...
5164
		if (
5165
			empty( $token_key )
5166
		||
5167
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5168
		) {
5169
			return false;
5170
		}
5171
5172
		if ( '0' === $user_id ) {
5173
			$token_type = 'blog';
5174
			$user_id = 0;
5175
		} else {
5176
			$token_type = 'user';
5177
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5178
				return false;
5179
			}
5180
			$user_id = (int) $user_id;
5181
5182
			$user = new WP_User( $user_id );
5183
			if ( ! $user || ! $user->exists() ) {
5184
				return false;
5185
			}
5186
		}
5187
5188
		$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...
5189
		if ( ! $token ) {
5190
			return false;
5191
		}
5192
5193
		$token_check = "$token_key.";
5194
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5195
			return false;
5196
		}
5197
5198
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5199
5200
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5201
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5202
			$post_data   = $_POST;
5203
			$file_hashes = array();
5204
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5205
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5206
					continue;
5207
				}
5208
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5209
				$file_hashes[$post_data_key] = $post_data_value;
5210
			}
5211
5212
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5213
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5214
				$post_data[$post_data_key] = $post_data_value;
5215
			}
5216
5217
			ksort( $post_data );
5218
5219
			$body = http_build_query( stripslashes_deep( $post_data ) );
5220
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5221
			$body = file_get_contents( 'php://input' );
5222
		} else {
5223
			$body = null;
5224
		}
5225
5226
		$signature = $jetpack_signature->sign_current_request(
5227
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5228
		);
5229
5230
		if ( ! $signature ) {
5231
			return false;
5232
		} else if ( is_wp_error( $signature ) ) {
5233
			return $signature;
5234
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5235
			return false;
5236
		}
5237
5238
		$timestamp = (int) $_GET['timestamp'];
5239
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5240
5241
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5242
			return false;
5243
		}
5244
5245
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5246
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5247
			if ( ! empty( $_GET['onboarding'] ) ) {
5248
				$jpo = $_GET;
5249
			} else {
5250
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5251
			}
5252
5253
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5254
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5255
5256
			if (
5257
				isset( $jpo_user ) && isset( $jpo_token ) &&
5258
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5259
				isset( $_GET['rest_route'] ) &&
5260
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5261
			) {
5262
				$jpUser = get_user_by( 'email', $jpo_user );
5263
				if ( is_a( $jpUser, 'WP_User' ) ) {
5264
					wp_set_current_user( $jpUser->ID );
5265
					$user_can = is_multisite()
5266
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5267
						: current_user_can( 'manage_options' );
5268
					if ( $user_can ) {
5269
						$token_type = 'user';
5270
						$token->external_user_id = $jpUser->ID;
5271
					}
5272
				}
5273
			}
5274
		}
5275
5276
		$this->xmlrpc_verification = array(
5277
			'type'    => $token_type,
5278
			'user_id' => $token->external_user_id,
5279
		);
5280
5281
		return $this->xmlrpc_verification;
5282
	}
5283
5284
	/**
5285
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5286
	 */
5287
	function authenticate_jetpack( $user, $username, $password ) {
5288
		if ( is_a( $user, 'WP_User' ) ) {
5289
			return $user;
5290
		}
5291
5292
		$token_details = $this->verify_xml_rpc_signature();
5293
5294
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5295
			return $user;
5296
		}
5297
5298
		if ( 'user' !== $token_details['type'] ) {
5299
			return $user;
5300
		}
5301
5302
		if ( ! $token_details['user_id'] ) {
5303
			return $user;
5304
		}
5305
5306
		nocache_headers();
5307
5308
		return new WP_User( $token_details['user_id'] );
5309
	}
5310
5311
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5312
	// Uses the existing XMLRPC request signing implementation.
5313
	function wp_rest_authenticate( $user ) {
5314
		if ( ! empty( $user ) ) {
5315
			// Another authentication method is in effect.
5316
			return $user;
5317
		}
5318
5319
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5320
			// Nothing to do for this authentication method.
5321
			return null;
5322
		}
5323
5324
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5325
			// Nothing to do for this authentication method.
5326
			return null;
5327
		}
5328
5329
		// Ensure that we always have the request body available.  At this
5330
		// point, the WP REST API code to determine the request body has not
5331
		// run yet.  That code may try to read from 'php://input' later, but
5332
		// this can only be done once per request in PHP versions prior to 5.6.
5333
		// So we will go ahead and perform this read now if needed, and save
5334
		// the request body where both the Jetpack signature verification code
5335
		// and the WP REST API code can see it.
5336
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5337
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5338
		}
5339
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5340
5341
		// Only support specific request parameters that have been tested and
5342
		// are known to work with signature verification.  A different method
5343
		// can be passed to the WP REST API via the '?_method=' parameter if
5344
		// needed.
5345
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5346
			$this->rest_authentication_status = new WP_Error(
5347
				'rest_invalid_request',
5348
				__( 'This request method is not supported.', 'jetpack' ),
5349
				array( 'status' => 400 )
5350
			);
5351
			return null;
5352
		}
5353
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5354
			$this->rest_authentication_status = new WP_Error(
5355
				'rest_invalid_request',
5356
				__( 'This request method does not support body parameters.', 'jetpack' ),
5357
				array( 'status' => 400 )
5358
			);
5359
			return null;
5360
		}
5361
5362
		$verified = $this->verify_xml_rpc_signature();
5363
5364
		if ( is_wp_error( $verified ) ) {
5365
			$this->rest_authentication_status = $verified;
5366
			return null;
5367
		}
5368
5369
		if (
5370
			$verified &&
5371
			isset( $verified['type'] ) &&
5372
			'user' === $verified['type'] &&
5373
			! empty( $verified['user_id'] )
5374
		) {
5375
			// Authentication successful.
5376
			$this->rest_authentication_status = true;
5377
			return $verified['user_id'];
5378
		}
5379
5380
		// Something else went wrong.  Probably a signature error.
5381
		$this->rest_authentication_status = new WP_Error(
5382
			'rest_invalid_signature',
5383
			__( 'The request is not signed correctly.', 'jetpack' ),
5384
			array( 'status' => 400 )
5385
		);
5386
		return null;
5387
	}
5388
5389
	/**
5390
	 * Report authentication status to the WP REST API.
5391
	 *
5392
	 * @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...
5393
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5394
	 */
5395
	public function wp_rest_authentication_errors( $value ) {
5396
		if ( $value !== null ) {
5397
			return $value;
5398
		}
5399
		return $this->rest_authentication_status;
5400
	}
5401
5402
	function add_nonce( $timestamp, $nonce ) {
5403
		global $wpdb;
5404
		static $nonces_used_this_request = array();
5405
5406
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5407
			return $nonces_used_this_request["$timestamp:$nonce"];
5408
		}
5409
5410
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5411
		$timestamp = (int) $timestamp;
5412
		$nonce     = esc_sql( $nonce );
5413
5414
		// Raw query so we can avoid races: add_option will also update
5415
		$show_errors = $wpdb->show_errors( false );
5416
5417
		$old_nonce = $wpdb->get_row(
5418
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5419
		);
5420
5421
		if ( is_null( $old_nonce ) ) {
5422
			$return = $wpdb->query(
5423
				$wpdb->prepare(
5424
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5425
					"jetpack_nonce_{$timestamp}_{$nonce}",
5426
					time(),
5427
					'no'
5428
				)
5429
			);
5430
		} else {
5431
			$return = false;
5432
		}
5433
5434
		$wpdb->show_errors( $show_errors );
5435
5436
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5437
5438
		return $return;
5439
	}
5440
5441
	/**
5442
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5443
	 * Capture it here so we can verify the signature later.
5444
	 */
5445
	function xmlrpc_methods( $methods ) {
5446
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5447
		return $methods;
5448
	}
5449
5450
	function public_xmlrpc_methods( $methods ) {
5451
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5452
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5453
		}
5454
		return $methods;
5455
	}
5456
5457
	function jetpack_getOptions( $args ) {
5458
		global $wp_xmlrpc_server;
5459
5460
		$wp_xmlrpc_server->escape( $args );
5461
5462
		$username	= $args[1];
5463
		$password	= $args[2];
5464
5465
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5466
			return $wp_xmlrpc_server->error;
5467
		}
5468
5469
		$options = array();
5470
		$user_data = $this->get_connected_user_data();
5471
		if ( is_array( $user_data ) ) {
5472
			$options['jetpack_user_id'] = array(
5473
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5474
				'readonly'      => true,
5475
				'value'         => $user_data['ID'],
5476
			);
5477
			$options['jetpack_user_login'] = array(
5478
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5479
				'readonly'      => true,
5480
				'value'         => $user_data['login'],
5481
			);
5482
			$options['jetpack_user_email'] = array(
5483
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5484
				'readonly'      => true,
5485
				'value'         => $user_data['email'],
5486
			);
5487
			$options['jetpack_user_site_count'] = array(
5488
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5489
				'readonly'      => true,
5490
				'value'         => $user_data['site_count'],
5491
			);
5492
		}
5493
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5494
		$args = stripslashes_deep( $args );
5495
		return $wp_xmlrpc_server->wp_getOptions( $args );
5496
	}
5497
5498
	function xmlrpc_options( $options ) {
5499
		$jetpack_client_id = false;
5500
		if ( self::is_active() ) {
5501
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5502
		}
5503
		$options['jetpack_version'] = array(
5504
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5505
				'readonly'      => true,
5506
				'value'         => JETPACK__VERSION,
5507
		);
5508
5509
		$options['jetpack_client_id'] = array(
5510
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5511
				'readonly'      => true,
5512
				'value'         => $jetpack_client_id,
5513
		);
5514
		return $options;
5515
	}
5516
5517
	public static function clean_nonces( $all = false ) {
5518
		global $wpdb;
5519
5520
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5521
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5522
5523
		if ( true !== $all ) {
5524
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5525
			$sql_args[] = time() - 3600;
5526
		}
5527
5528
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5529
5530
		$sql = $wpdb->prepare( $sql, $sql_args );
5531
5532
		for ( $i = 0; $i < 1000; $i++ ) {
5533
			if ( ! $wpdb->query( $sql ) ) {
5534
				break;
5535
			}
5536
		}
5537
	}
5538
5539
	/**
5540
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5541
	 * SET: state( $key, $value );
5542
	 * GET: $value = state( $key );
5543
	 *
5544
	 * @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...
5545
	 * @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...
5546
	 * @param bool $restate private
5547
	 */
5548
	public static function state( $key = null, $value = null, $restate = false ) {
5549
		static $state = array();
5550
		static $path, $domain;
5551
		if ( ! isset( $path ) ) {
5552
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5553
			$admin_url = Jetpack::admin_url();
5554
			$bits      = wp_parse_url( $admin_url );
5555
5556
			if ( is_array( $bits ) ) {
5557
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5558
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5559
			} else {
5560
				$path = $domain = null;
5561
			}
5562
		}
5563
5564
		// Extract state from cookies and delete cookies
5565
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5566
			$yum = $_COOKIE[ 'jetpackState' ];
5567
			unset( $_COOKIE[ 'jetpackState' ] );
5568
			foreach ( $yum as $k => $v ) {
5569
				if ( strlen( $v ) )
5570
					$state[ $k ] = $v;
5571
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5572
			}
5573
		}
5574
5575
		if ( $restate ) {
5576
			foreach ( $state as $k => $v ) {
5577
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5578
			}
5579
			return;
5580
		}
5581
5582
		// Get a state variable
5583
		if ( isset( $key ) && ! isset( $value ) ) {
5584
			if ( array_key_exists( $key, $state ) )
5585
				return $state[ $key ];
5586
			return null;
5587
		}
5588
5589
		// Set a state variable
5590
		if ( isset ( $key ) && isset( $value ) ) {
5591
			if( is_array( $value ) && isset( $value[0] ) ) {
5592
				$value = $value[0];
5593
			}
5594
			$state[ $key ] = $value;
5595
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5596
		}
5597
	}
5598
5599
	public static function restate() {
5600
		Jetpack::state( null, null, true );
5601
	}
5602
5603
	public static function check_privacy( $file ) {
5604
		static $is_site_publicly_accessible = null;
5605
5606
		if ( is_null( $is_site_publicly_accessible ) ) {
5607
			$is_site_publicly_accessible = false;
5608
5609
			Jetpack::load_xml_rpc_client();
5610
			$rpc = new Jetpack_IXR_Client();
5611
5612
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5613
			if ( $success ) {
5614
				$response = $rpc->getResponse();
5615
				if ( $response ) {
5616
					$is_site_publicly_accessible = true;
5617
				}
5618
			}
5619
5620
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5621
		}
5622
5623
		if ( $is_site_publicly_accessible ) {
5624
			return;
5625
		}
5626
5627
		$module_slug = self::get_module_slug( $file );
5628
5629
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5630
		if ( ! $privacy_checks ) {
5631
			$privacy_checks = $module_slug;
5632
		} else {
5633
			$privacy_checks .= ",$module_slug";
5634
		}
5635
5636
		Jetpack::state( 'privacy_checks', $privacy_checks );
5637
	}
5638
5639
	/**
5640
	 * Helper method for multicall XMLRPC.
5641
	 */
5642
	public static function xmlrpc_async_call() {
5643
		global $blog_id;
5644
		static $clients = array();
5645
5646
		$client_blog_id = is_multisite() ? $blog_id : 0;
5647
5648
		if ( ! isset( $clients[$client_blog_id] ) ) {
5649
			Jetpack::load_xml_rpc_client();
5650
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5651
			if ( function_exists( 'ignore_user_abort' ) ) {
5652
				ignore_user_abort( true );
5653
			}
5654
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5655
		}
5656
5657
		$args = func_get_args();
5658
5659
		if ( ! empty( $args[0] ) ) {
5660
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5661
		} elseif ( is_multisite() ) {
5662
			foreach ( $clients as $client_blog_id => $client ) {
5663
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5664
					continue;
5665
				}
5666
5667
				$switch_success = switch_to_blog( $client_blog_id, true );
5668
				if ( ! $switch_success ) {
5669
					continue;
5670
				}
5671
5672
				flush();
5673
				$client->query();
5674
5675
				restore_current_blog();
5676
			}
5677
		} else {
5678
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5679
				flush();
5680
				$clients[0]->query();
5681
			}
5682
		}
5683
	}
5684
5685
	public static function staticize_subdomain( $url ) {
5686
5687
		// Extract hostname from URL
5688
		$host = parse_url( $url, PHP_URL_HOST );
5689
5690
		// Explode hostname on '.'
5691
		$exploded_host = explode( '.', $host );
5692
5693
		// Retrieve the name and TLD
5694
		if ( count( $exploded_host ) > 1 ) {
5695
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5696
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5697
			// Rebuild domain excluding subdomains
5698
			$domain = $name . '.' . $tld;
5699
		} else {
5700
			$domain = $host;
5701
		}
5702
		// Array of Automattic domains
5703
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5704
5705
		// Return $url if not an Automattic domain
5706
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5707
			return $url;
5708
		}
5709
5710
		if ( is_ssl() ) {
5711
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5712
		}
5713
5714
		srand( crc32( basename( $url ) ) );
5715
		$static_counter = rand( 0, 2 );
5716
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5717
5718
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5719
	}
5720
5721
/* JSON API Authorization */
5722
5723
	/**
5724
	 * Handles the login action for Authorizing the JSON API
5725
	 */
5726
	function login_form_json_api_authorization() {
5727
		$this->verify_json_api_authorization_request();
5728
5729
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5730
5731
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5732
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5733
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5734
	}
5735
5736
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5737
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5738
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5739
			return $url;
5740
		}
5741
5742
		$parsed_url = parse_url( $url );
5743
		$url = strtok( $url, '?' );
5744
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5745
		if ( ! empty( $parsed_url['query'] ) )
5746
			$url .= "&{$parsed_url['query']}";
5747
5748
		return $url;
5749
	}
5750
5751
	// Make sure the POSTed request is handled by the same action
5752
	function preserve_action_in_login_form_for_json_api_authorization() {
5753
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5754
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5755
	}
5756
5757
	// If someone logs in to approve API access, store the Access Code in usermeta
5758
	function store_json_api_authorization_token( $user_login, $user ) {
5759
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5760
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5761
		$token = wp_generate_password( 32, false );
5762
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5763
	}
5764
5765
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5766
	function allow_wpcom_public_api_domain( $domains ) {
5767
		$domains[] = 'public-api.wordpress.com';
5768
		return $domains;
5769
	}
5770
5771
	static function is_redirect_encoded( $redirect_url ) {
5772
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5773
	}
5774
5775
	// Add all wordpress.com environments to the safe redirect whitelist
5776
	function allow_wpcom_environments( $domains ) {
5777
		$domains[] = 'wordpress.com';
5778
		$domains[] = 'wpcalypso.wordpress.com';
5779
		$domains[] = 'horizon.wordpress.com';
5780
		$domains[] = 'calypso.localhost';
5781
		return $domains;
5782
	}
5783
5784
	// Add the Access Code details to the public-api.wordpress.com redirect
5785
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5786
		return add_query_arg(
5787
			urlencode_deep(
5788
				array(
5789
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5790
					'jetpack-user-id' => (int) $user->ID,
5791
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5792
				)
5793
			),
5794
			$redirect_to
5795
		);
5796
	}
5797
5798
5799
	/**
5800
	 * Verifies the request by checking the signature
5801
	 *
5802
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5803
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5804
	 *
5805
	 * @param null|array $environment
5806
	 */
5807
	function verify_json_api_authorization_request( $environment = null ) {
5808
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5809
5810
		$environment = is_null( $environment )
5811
			? $_REQUEST
5812
			: $environment;
5813
5814
		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...
5815
		$token = Jetpack_Data::get_access_token( $envUserId );
5816
		if ( ! $token || empty( $token->secret ) ) {
5817
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5818
		}
5819
5820
		$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' );
5821
5822
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5823
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5824
			JetpackTracking::record_user_event( 'error_double_encode' );
5825
5826
			$die_error = sprintf(
5827
				/* translators: %s is a URL */
5828
				__( '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' ),
5829
				'https://jetpack.com/support/double-encoding/'
5830
			);
5831
		}
5832
5833
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5834
5835
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5836
			$signature = $jetpack_signature->sign_request(
5837
				$environment['token'],
5838
				$environment['timestamp'],
5839
				$environment['nonce'],
5840
				'',
5841
				'GET',
5842
				$environment['jetpack_json_api_original_query'],
5843
				null,
5844
				true
5845
			);
5846
		} else {
5847
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5848
		}
5849
5850
		if ( ! $signature ) {
5851
			wp_die( $die_error );
5852
		} else if ( is_wp_error( $signature ) ) {
5853
			wp_die( $die_error );
5854
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5855
			if ( is_ssl() ) {
5856
				// 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
5857
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5858
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5859
					wp_die( $die_error );
5860
				}
5861
			} else {
5862
				wp_die( $die_error );
5863
			}
5864
		}
5865
5866
		$timestamp = (int) $environment['timestamp'];
5867
		$nonce     = stripslashes( (string) $environment['nonce'] );
5868
5869
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5870
			// De-nonce the nonce, at least for 5 minutes.
5871
			// 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)
5872
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5873
			if ( $old_nonce_time < time() - 300 ) {
5874
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5875
			}
5876
		}
5877
5878
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5879
		$data_filters = array(
5880
			'state'        => 'opaque',
5881
			'client_id'    => 'int',
5882
			'client_title' => 'string',
5883
			'client_image' => 'url',
5884
		);
5885
5886
		foreach ( $data_filters as $key => $sanitation ) {
5887
			if ( ! isset( $data->$key ) ) {
5888
				wp_die( $die_error );
5889
			}
5890
5891
			switch ( $sanitation ) {
5892
			case 'int' :
5893
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5894
				break;
5895
			case 'opaque' :
5896
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5897
				break;
5898
			case 'string' :
5899
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5900
				break;
5901
			case 'url' :
5902
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5903
				break;
5904
			}
5905
		}
5906
5907
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5908
			wp_die( $die_error );
5909
		}
5910
	}
5911
5912
	function login_message_json_api_authorization( $message ) {
5913
		return '<p class="message">' . sprintf(
5914
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5915
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5916
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5917
	}
5918
5919
	/**
5920
	 * Get $content_width, but with a <s>twist</s> filter.
5921
	 */
5922
	public static function get_content_width() {
5923
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
5924
		/**
5925
		 * Filter the Content Width value.
5926
		 *
5927
		 * @since 2.2.3
5928
		 *
5929
		 * @param string $content_width Content Width value.
5930
		 */
5931
		return apply_filters( 'jetpack_content_width', $content_width );
5932
	}
5933
5934
	/**
5935
	 * Pings the WordPress.com Mirror Site for the specified options.
5936
	 *
5937
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5938
	 *
5939
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5940
	 */
5941
	public function get_cloud_site_options( $option_names ) {
5942
		$option_names = array_filter( (array) $option_names, 'is_string' );
5943
5944
		Jetpack::load_xml_rpc_client();
5945
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5946
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5947
		if ( $xml->isError() ) {
5948
			return array(
5949
				'error_code' => $xml->getErrorCode(),
5950
				'error_msg'  => $xml->getErrorMessage(),
5951
			);
5952
		}
5953
		$cloud_site_options = $xml->getResponse();
5954
5955
		return $cloud_site_options;
5956
	}
5957
5958
	/**
5959
	 * Checks if the site is currently in an identity crisis.
5960
	 *
5961
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5962
	 */
5963
	public static function check_identity_crisis() {
5964
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5965
			return false;
5966
		}
5967
5968
		return Jetpack_Options::get_option( 'sync_error_idc' );
5969
	}
5970
5971
	/**
5972
	 * Checks whether the home and siteurl specifically are whitelisted
5973
	 * Written so that we don't have re-check $key and $value params every time
5974
	 * we want to check if this site is whitelisted, for example in footer.php
5975
	 *
5976
	 * @since  3.8.0
5977
	 * @return bool True = already whitelisted False = not whitelisted
5978
	 */
5979
	public static function is_staging_site() {
5980
		$is_staging = false;
5981
5982
		$known_staging = array(
5983
			'urls' => array(
5984
				'#\.staging\.wpengine\.com$#i', // WP Engine
5985
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5986
				),
5987
			'constants' => array(
5988
				'IS_WPE_SNAPSHOT',      // WP Engine
5989
				'KINSTA_DEV_ENV',       // Kinsta.com
5990
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5991
				'JETPACK_STAGING_MODE', // Generic
5992
				)
5993
			);
5994
		/**
5995
		 * Filters the flags of known staging sites.
5996
		 *
5997
		 * @since 3.9.0
5998
		 *
5999
		 * @param array $known_staging {
6000
		 *     An array of arrays that each are used to check if the current site is staging.
6001
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6002
		 *     @type array $constants PHP constants of known staging/developement environments.
6003
		 *  }
6004
		 */
6005
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6006
6007
		if ( isset( $known_staging['urls'] ) ) {
6008
			foreach ( $known_staging['urls'] as $url ){
6009
				if ( preg_match( $url, site_url() ) ) {
6010
					$is_staging = true;
6011
					break;
6012
				}
6013
			}
6014
		}
6015
6016
		if ( isset( $known_staging['constants'] ) ) {
6017
			foreach ( $known_staging['constants'] as $constant ) {
6018
				if ( defined( $constant ) && constant( $constant ) ) {
6019
					$is_staging = true;
6020
				}
6021
			}
6022
		}
6023
6024
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6025
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6026
			$is_staging = true;
6027
		}
6028
6029
		/**
6030
		 * Filters is_staging_site check.
6031
		 *
6032
		 * @since 3.9.0
6033
		 *
6034
		 * @param bool $is_staging If the current site is a staging site.
6035
		 */
6036
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6037
	}
6038
6039
	/**
6040
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6041
	 *
6042
	 * @since 4.4.0
6043
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6044
	 *
6045
	 * @return bool
6046
	 */
6047
	public static function validate_sync_error_idc_option() {
6048
		$is_valid = false;
6049
6050
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6051
		if ( false === $idc_allowed ) {
6052
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6053
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6054
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6055
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6056
				$transient_duration = HOUR_IN_SECONDS;
6057
			} else {
6058
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6059
				$idc_allowed = '1';
6060
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6061
			}
6062
6063
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6064
		}
6065
6066
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6067
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6068
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6069
			$local_options = self::get_sync_error_idc_option();
6070
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6071
				$is_valid = true;
6072
			}
6073
		}
6074
6075
		/**
6076
		 * Filters whether the sync_error_idc option is valid.
6077
		 *
6078
		 * @since 4.4.0
6079
		 *
6080
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6081
		 */
6082
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6083
6084
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6085
			// Since the option exists, and did not validate, delete it
6086
			Jetpack_Options::delete_option( 'sync_error_idc' );
6087
		}
6088
6089
		return $is_valid;
6090
	}
6091
6092
	/**
6093
	 * Normalizes a url by doing three things:
6094
	 *  - Strips protocol
6095
	 *  - Strips www
6096
	 *  - Adds a trailing slash
6097
	 *
6098
	 * @since 4.4.0
6099
	 * @param string $url
6100
	 * @return WP_Error|string
6101
	 */
6102
	public static function normalize_url_protocol_agnostic( $url ) {
6103
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6104
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6105
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6106
		}
6107
6108
		// Strip www and protocols
6109
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6110
		return $url;
6111
	}
6112
6113
	/**
6114
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6115
	 *
6116
	 * @since 4.4.0
6117
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6118
	 *
6119
	 * @param array $response
6120
	 * @return array Array of the local urls, wpcom urls, and error code
6121
	 */
6122
	public static function get_sync_error_idc_option( $response = array() ) {
6123
		// Since the local options will hit the database directly, store the values
6124
		// in a transient to allow for autoloading and caching on subsequent views.
6125
		$local_options = get_transient( 'jetpack_idc_local' );
6126
		if ( false === $local_options ) {
6127
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6128
			$local_options = array(
6129
				'home'    => Jetpack_Sync_Functions::home_url(),
6130
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6131
			);
6132
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6133
		}
6134
6135
		$options = array_merge( $local_options, $response );
6136
6137
		$returned_values = array();
6138
		foreach( $options as $key => $option ) {
6139
			if ( 'error_code' === $key ) {
6140
				$returned_values[ $key ] = $option;
6141
				continue;
6142
			}
6143
6144
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6145
				continue;
6146
			}
6147
6148
			$returned_values[ $key ] = $normalized_url;
6149
		}
6150
6151
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6152
6153
		return $returned_values;
6154
	}
6155
6156
	/**
6157
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6158
	 * If set to true, the site will be put into staging mode.
6159
	 *
6160
	 * @since 4.3.2
6161
	 * @return bool
6162
	 */
6163
	public static function sync_idc_optin() {
6164
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6165
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6166
		} else {
6167
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6168
		}
6169
6170
		/**
6171
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6172
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6173
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6174
		 *
6175
		 * @since 4.3.2
6176
		 *
6177
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6178
		 */
6179
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6180
	}
6181
6182
	/**
6183
	 * Maybe Use a .min.css stylesheet, maybe not.
6184
	 *
6185
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6186
	 */
6187
	public static function maybe_min_asset( $url, $path, $plugin ) {
6188
		// Short out on things trying to find actual paths.
6189
		if ( ! $path || empty( $plugin ) ) {
6190
			return $url;
6191
		}
6192
6193
		$path = ltrim( $path, '/' );
6194
6195
		// Strip out the abspath.
6196
		$base = dirname( plugin_basename( $plugin ) );
6197
6198
		// Short out on non-Jetpack assets.
6199
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6200
			return $url;
6201
		}
6202
6203
		// File name parsing.
6204
		$file              = "{$base}/{$path}";
6205
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6206
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6207
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6208
		$extension         = array_shift( $file_name_parts_r );
6209
6210
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6211
			// Already pointing at the minified version.
6212
			if ( 'min' === $file_name_parts_r[0] ) {
6213
				return $url;
6214
			}
6215
6216
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6217
			if ( file_exists( $min_full_path ) ) {
6218
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6219
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6220
				if ( 'css' === $extension ) {
6221
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6222
					self::$min_assets[ $key ] = $path;
6223
				}
6224
			}
6225
		}
6226
6227
		return $url;
6228
	}
6229
6230
	/**
6231
	 * If the asset is minified, let's flag .min as the suffix.
6232
	 *
6233
	 * Attached to `style_loader_src` filter.
6234
	 *
6235
	 * @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...
6236
	 * @param string $handle The registered handle of the script in question.
6237
	 * @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...
6238
	 */
6239
	public static function set_suffix_on_min( $src, $handle ) {
6240
		if ( false === strpos( $src, '.min.css' ) ) {
6241
			return $src;
6242
		}
6243
6244
		if ( ! empty( self::$min_assets ) ) {
6245
			foreach ( self::$min_assets as $file => $path ) {
6246
				if ( false !== strpos( $src, $file ) ) {
6247
					wp_style_add_data( $handle, 'suffix', '.min' );
6248
					return $src;
6249
				}
6250
			}
6251
		}
6252
6253
		return $src;
6254
	}
6255
6256
	/**
6257
	 * Maybe inlines a stylesheet.
6258
	 *
6259
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6260
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6261
	 *
6262
	 * Attached to `style_loader_tag` filter.
6263
	 *
6264
	 * @param string $tag The tag that would link to the external asset.
6265
	 * @param string $handle The registered handle of the script in question.
6266
	 *
6267
	 * @return string
6268
	 */
6269
	public static function maybe_inline_style( $tag, $handle ) {
6270
		global $wp_styles;
6271
		$item = $wp_styles->registered[ $handle ];
6272
6273
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6274
			return $tag;
6275
		}
6276
6277
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6278
			$href = $matches[1];
6279
			// Strip off query string
6280
			if ( $pos = strpos( $href, '?' ) ) {
6281
				$href = substr( $href, 0, $pos );
6282
			}
6283
			// Strip off fragment
6284
			if ( $pos = strpos( $href, '#' ) ) {
6285
				$href = substr( $href, 0, $pos );
6286
			}
6287
		} else {
6288
			return $tag;
6289
		}
6290
6291
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6292
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6293
			return $tag;
6294
		}
6295
6296
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6297
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6298
			// And this isn't the pass that actually deals with the RTL version...
6299
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6300
				// Short out, as the RTL version will deal with it in a moment.
6301
				return $tag;
6302
			}
6303
		}
6304
6305
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6306
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6307
		if ( $css ) {
6308
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6309
			if ( empty( $item->extra['after'] ) ) {
6310
				wp_add_inline_style( $handle, $css );
6311
			} else {
6312
				array_unshift( $item->extra['after'], $css );
6313
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6314
			}
6315
		}
6316
6317
		return $tag;
6318
	}
6319
6320
	/**
6321
	 * Loads a view file from the views
6322
	 *
6323
	 * Data passed in with the $data parameter will be available in the
6324
	 * template file as $data['value']
6325
	 *
6326
	 * @param string $template - Template file to load
6327
	 * @param array $data - Any data to pass along to the template
6328
	 * @return boolean - If template file was found
6329
	 **/
6330
	public function load_view( $template, $data = array() ) {
6331
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6332
6333
		if( file_exists( $views_dir . $template ) ) {
6334
			require_once( $views_dir . $template );
6335
			return true;
6336
		}
6337
6338
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6339
		return false;
6340
	}
6341
6342
	/**
6343
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6344
	 */
6345
	public function deprecated_hooks() {
6346
		global $wp_filter;
6347
6348
		/*
6349
		 * Format:
6350
		 * deprecated_filter_name => replacement_name
6351
		 *
6352
		 * If there is no replacement, use null for replacement_name
6353
		 */
6354
		$deprecated_list = array(
6355
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6356
			'wpl_sharing_2014_1'                                     => null,
6357
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6358
			'jetpack_identity_crisis_options_to_check'               => null,
6359
			'update_option_jetpack_single_user_site'                 => null,
6360
			'audio_player_default_colors'                            => null,
6361
			'add_option_jetpack_featured_images_enabled'             => null,
6362
			'add_option_jetpack_update_details'                      => null,
6363
			'add_option_jetpack_updates'                             => null,
6364
			'add_option_jetpack_network_name'                        => null,
6365
			'add_option_jetpack_network_allow_new_registrations'     => null,
6366
			'add_option_jetpack_network_add_new_users'               => null,
6367
			'add_option_jetpack_network_site_upload_space'           => null,
6368
			'add_option_jetpack_network_upload_file_types'           => null,
6369
			'add_option_jetpack_network_enable_administration_menus' => null,
6370
			'add_option_jetpack_is_multi_site'                       => null,
6371
			'add_option_jetpack_is_main_network'                     => null,
6372
			'add_option_jetpack_main_network_site'                   => null,
6373
			'jetpack_sync_all_registered_options'                    => null,
6374
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6375
			'jetpack_is_post_mailable'                               => null,
6376
			'jetpack_seo_site_host'                                  => null,
6377
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6378
			'jetpack_holiday_snow_option_name'                       => null,
6379
			'jetpack_holiday_chance_of_snow'                         => null,
6380
			'jetpack_holiday_snow_js_url'                            => null,
6381
			'jetpack_is_holiday_snow_season'                         => null,
6382
			'jetpack_holiday_snow_option_updated'                    => null,
6383
			'jetpack_holiday_snowing'                                => null,
6384
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6385
			'jetpack_cache_plans'                                    => null,
6386
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6387
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6388
			'jetpack_enable_site_verification'                       => null,
6389
			'can_display_jetpack_manage_notice'                      => null,
6390
			'can_display_jetpack_manage_notice'                      => 'jetpack_json_manage_api_enabled',
6391
		);
6392
6393
		// This is a silly loop depth. Better way?
6394
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6395
			if ( has_action( $hook ) ) {
6396
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6397
					foreach( $values AS $hooked ) {
6398
						if ( is_callable( $hooked['function'] ) ) {
6399
							$function_name = 'an anonymous function';
6400
						} else {
6401
							$function_name = $hooked['function'];
6402
						}
6403
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6404
					}
6405
				}
6406
			}
6407
		}
6408
	}
6409
6410
	/**
6411
	 * Converts any url in a stylesheet, to the correct absolute url.
6412
	 *
6413
	 * Considerations:
6414
	 *  - Normal, relative URLs     `feh.png`
6415
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6416
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6417
	 *  - Absolute URLs             `http://domain.com/feh.png`
6418
	 *  - Domain root relative URLs `/feh.png`
6419
	 *
6420
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6421
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6422
	 *
6423
	 * @return mixed|string
6424
	 */
6425
	public static function absolutize_css_urls( $css, $css_file_url ) {
6426
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6427
		$css_dir = dirname( $css_file_url );
6428
		$p       = parse_url( $css_dir );
6429
		$domain  = sprintf(
6430
					'%1$s//%2$s%3$s%4$s',
6431
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6432
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6433
					$p['host'],
6434
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6435
				);
6436
6437
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6438
			$find = $replace = array();
6439
			foreach ( $matches as $match ) {
6440
				$url = trim( $match['path'], "'\" \t" );
6441
6442
				// If this is a data url, we don't want to mess with it.
6443
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6444
					continue;
6445
				}
6446
6447
				// If this is an absolute or protocol-agnostic url,
6448
				// we don't want to mess with it.
6449
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6450
					continue;
6451
				}
6452
6453
				switch ( substr( $url, 0, 1 ) ) {
6454
					case '/':
6455
						$absolute = $domain . $url;
6456
						break;
6457
					default:
6458
						$absolute = $css_dir . '/' . $url;
6459
				}
6460
6461
				$find[]    = $match[0];
6462
				$replace[] = sprintf( 'url("%s")', $absolute );
6463
			}
6464
			$css = str_replace( $find, $replace, $css );
6465
		}
6466
6467
		return $css;
6468
	}
6469
6470
	/**
6471
	 * This methods removes all of the registered css files on the front end
6472
	 * from Jetpack in favor of using a single file. In effect "imploding"
6473
	 * all the files into one file.
6474
	 *
6475
	 * Pros:
6476
	 * - Uses only ONE css asset connection instead of 15
6477
	 * - Saves a minimum of 56k
6478
	 * - Reduces server load
6479
	 * - Reduces time to first painted byte
6480
	 *
6481
	 * Cons:
6482
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6483
	 *		should not cause any issues with themes.
6484
	 * - Plugins/themes dequeuing styles no longer do anything. See
6485
	 *		jetpack_implode_frontend_css filter for a workaround
6486
	 *
6487
	 * For some situations developers may wish to disable css imploding and
6488
	 * instead operate in legacy mode where each file loads seperately and
6489
	 * can be edited individually or dequeued. This can be accomplished with
6490
	 * the following line:
6491
	 *
6492
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6493
	 *
6494
	 * @since 3.2
6495
	 **/
6496
	public function implode_frontend_css( $travis_test = false ) {
6497
		$do_implode = true;
6498
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6499
			$do_implode = false;
6500
		}
6501
6502
		// Do not implode CSS when the page loads via the AMP plugin.
6503
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6504
			$do_implode = false;
6505
		}
6506
6507
		/**
6508
		 * Allow CSS to be concatenated into a single jetpack.css file.
6509
		 *
6510
		 * @since 3.2.0
6511
		 *
6512
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6513
		 */
6514
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6515
6516
		// Do not use the imploded file when default behavior was altered through the filter
6517
		if ( ! $do_implode ) {
6518
			return;
6519
		}
6520
6521
		// We do not want to use the imploded file in dev mode, or if not connected
6522
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6523
			if ( ! $travis_test ) {
6524
				return;
6525
			}
6526
		}
6527
6528
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6529
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6530
			return;
6531
		}
6532
6533
		/*
6534
		 * Now we assume Jetpack is connected and able to serve the single
6535
		 * file.
6536
		 *
6537
		 * In the future there will be a check here to serve the file locally
6538
		 * or potentially from the Jetpack CDN
6539
		 *
6540
		 * For now:
6541
		 * - Enqueue a single imploded css file
6542
		 * - Zero out the style_loader_tag for the bundled ones
6543
		 * - Be happy, drink scotch
6544
		 */
6545
6546
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6547
6548
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6549
6550
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6551
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6552
	}
6553
6554
	function concat_remove_style_loader_tag( $tag, $handle ) {
6555
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6556
			$tag = '';
6557
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6558
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6559
			}
6560
		}
6561
6562
		return $tag;
6563
	}
6564
6565
	/*
6566
	 * Check the heartbeat data
6567
	 *
6568
	 * Organizes the heartbeat data by severity.  For example, if the site
6569
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6570
	 *
6571
	 * Data will be added to "caution" array, if it either:
6572
	 *  - Out of date Jetpack version
6573
	 *  - Out of date WP version
6574
	 *  - Out of date PHP version
6575
	 *
6576
	 * $return array $filtered_data
6577
	 */
6578
	public static function jetpack_check_heartbeat_data() {
6579
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6580
6581
		$good    = array();
6582
		$caution = array();
6583
		$bad     = array();
6584
6585
		foreach ( $raw_data as $stat => $value ) {
6586
6587
			// Check jetpack version
6588
			if ( 'version' == $stat ) {
6589
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6590
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6591
					continue;
6592
				}
6593
			}
6594
6595
			// Check WP version
6596
			if ( 'wp-version' == $stat ) {
6597
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6598
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6599
					continue;
6600
				}
6601
			}
6602
6603
			// Check PHP version
6604
			if ( 'php-version' == $stat ) {
6605
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6606
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6607
					continue;
6608
				}
6609
			}
6610
6611
			// Check ID crisis
6612
			if ( 'identitycrisis' == $stat ) {
6613
				if ( 'yes' == $value ) {
6614
					$bad[ $stat ] = $value;
6615
					continue;
6616
				}
6617
			}
6618
6619
			// The rest are good :)
6620
			$good[ $stat ] = $value;
6621
		}
6622
6623
		$filtered_data = array(
6624
			'good'    => $good,
6625
			'caution' => $caution,
6626
			'bad'     => $bad
6627
		);
6628
6629
		return $filtered_data;
6630
	}
6631
6632
6633
	/*
6634
	 * This method is used to organize all options that can be reset
6635
	 * without disconnecting Jetpack.
6636
	 *
6637
	 * It is used in class.jetpack-cli.php to reset options
6638
	 *
6639
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6640
	 *
6641
	 * @return array of options to delete.
6642
	 */
6643
	public static function get_jetpack_options_for_reset() {
6644
		return Jetpack_Options::get_options_for_reset();
6645
	}
6646
6647
	/**
6648
	 * Check if an option of a Jetpack module has been updated.
6649
	 *
6650
	 * If any module option has been updated before Jump Start has been dismissed,
6651
	 * update the 'jumpstart' option so we can hide Jump Start.
6652
	 *
6653
	 * @param string $option_name
6654
	 *
6655
	 * @return bool
6656
	 */
6657
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6658
		// Bail if Jump Start has already been dismissed
6659
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6660
			return false;
6661
		}
6662
6663
		$jetpack = Jetpack::init();
6664
6665
		// Manual build of module options
6666
		$option_names = self::get_jetpack_options_for_reset();
6667
6668
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6669
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6670
6671
			//Jump start is being dismissed send data to MC Stats
6672
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6673
6674
			$jetpack->do_stats( 'server_side' );
6675
		}
6676
6677
	}
6678
6679
	/*
6680
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6681
	 * so we can bring them directly to their site in calypso.
6682
	 *
6683
	 * @param string | url
6684
	 * @return string | url without the guff
6685
	 */
6686
	public static function build_raw_urls( $url ) {
6687
		$strip_http = '/.*?:\/\//i';
6688
		$url = preg_replace( $strip_http, '', $url  );
6689
		$url = str_replace( '/', '::', $url );
6690
		return $url;
6691
	}
6692
6693
	/**
6694
	 * Stores and prints out domains to prefetch for page speed optimization.
6695
	 *
6696
	 * @param mixed $new_urls
6697
	 */
6698
	public static function dns_prefetch( $new_urls = null ) {
6699
		static $prefetch_urls = array();
6700
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6701
			echo "\r\n";
6702
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6703
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6704
			}
6705
		} elseif ( ! empty( $new_urls ) ) {
6706
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6707
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6708
			}
6709
			foreach ( (array) $new_urls as $this_new_url ) {
6710
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6711
			}
6712
			$prefetch_urls = array_unique( $prefetch_urls );
6713
		}
6714
	}
6715
6716
	public function wp_dashboard_setup() {
6717
		if ( self::is_active() ) {
6718
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6719
		}
6720
6721
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6722
			$widget_title = sprintf(
6723
				wp_kses(
6724
					/* translators: Placeholder is a Jetpack logo. */
6725
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6726
					array( 'span' => array() )
6727
				),
6728
				Jetpack::get_jp_emblem( true )
6729
			);
6730
6731
			wp_add_dashboard_widget(
6732
				'jetpack_summary_widget',
6733
				$widget_title,
6734
				array( __CLASS__, 'dashboard_widget' )
6735
			);
6736
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6737
6738
			// If we're inactive and not in development mode, sort our box to the top.
6739
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6740
				global $wp_meta_boxes;
6741
6742
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6743
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6744
6745
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6746
			}
6747
		}
6748
	}
6749
6750
	/**
6751
	 * @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...
6752
	 * @return mixed
6753
	 */
6754
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6755
		if ( ! is_array( $sorted ) ) {
6756
			return $sorted;
6757
		}
6758
6759
		foreach ( $sorted as $box_context => $ids ) {
6760
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6761
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6762
				continue;
6763
			}
6764
6765
			$ids_array = explode( ',', $ids );
6766
			$key = array_search( 'dashboard_stats', $ids_array );
6767
6768
			if ( false !== $key ) {
6769
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6770
				$ids_array[ $key ] = 'jetpack_summary_widget';
6771
				$sorted[ $box_context ] = implode( ',', $ids_array );
6772
				// We've found it, stop searching, and just return.
6773
				break;
6774
			}
6775
		}
6776
6777
		return $sorted;
6778
	}
6779
6780
	public static function dashboard_widget() {
6781
		/**
6782
		 * Fires when the dashboard is loaded.
6783
		 *
6784
		 * @since 3.4.0
6785
		 */
6786
		do_action( 'jetpack_dashboard_widget' );
6787
	}
6788
6789
	public static function dashboard_widget_footer() {
6790
		?>
6791
		<footer>
6792
6793
		<div class="protect">
6794
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6795
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6796
				<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>
6797
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6798
				<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' ); ?>">
6799
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6800
				</a>
6801
			<?php else : ?>
6802
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6803
			<?php endif; ?>
6804
		</div>
6805
6806
		<div class="akismet">
6807
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6808
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6809
				<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>
6810
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6811
				<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">
6812
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6813
				</a>
6814
			<?php else : ?>
6815
				<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>
6816
			<?php endif; ?>
6817
		</div>
6818
6819
		</footer>
6820
		<?php
6821
	}
6822
6823
	/**
6824
	 * Return string containing the Jetpack logo.
6825
	 *
6826
	 * @since 3.9.0
6827
	 *
6828
	 * @param bool $logotype Should we use the full logotype (logo + text). Default to false.
6829
	 *
6830
	 * @return string
6831
	 */
6832
	public static function get_jp_emblem( $logotype = false ) {
6833
		$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"/>';
6834
		$text = '
6835
<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" />
6836
<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" />
6837
<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" />
6838
<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" />
6839
<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" />
6840
<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" />
6841
<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" />
6842
		';
6843
6844
		return sprintf(
6845
			'<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>',
6846
			( true === $logotype ? '118' : '32' ),
6847
			( true === $logotype ? $logo . $text : $logo )
6848
		);
6849
	}
6850
6851
	/*
6852
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6853
	 */
6854
	function jetpack_icon_user_connected( $columns ) {
6855
		$columns['user_jetpack'] = '';
6856
		return $columns;
6857
	}
6858
6859
	/*
6860
	 * Show Jetpack icon if the user is linked.
6861
	 */
6862
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6863
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6864
			$emblem_html = sprintf(
6865
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6866
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6867
				Jetpack::get_jp_emblem()
6868
			);
6869
			return $emblem_html;
6870
		}
6871
6872
		return $val;
6873
	}
6874
6875
	/*
6876
	 * Style the Jetpack user column
6877
	 */
6878
	function jetpack_user_col_style() {
6879
		global $current_screen;
6880
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6881
			<style>
6882
				.fixed .column-user_jetpack {
6883
					width: 21px;
6884
				}
6885
				.jp-emblem-user-admin svg {
6886
					width: 20px;
6887
					height: 20px;
6888
				}
6889
				.jp-emblem-user-admin path {
6890
					fill: #00BE28;
6891
				}
6892
			</style>
6893
		<?php }
6894
	}
6895
6896
	/**
6897
	 * Checks if Akismet is active and working.
6898
	 *
6899
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6900
	 * that implied usage of methods present since more recent version.
6901
	 * See https://github.com/Automattic/jetpack/pull/9585
6902
	 *
6903
	 * @since  5.1.0
6904
	 *
6905
	 * @return bool True = Akismet available. False = Aksimet not available.
6906
	 */
6907
	public static function is_akismet_active() {
6908
		static $status = null;
6909
6910
		if ( ! is_null( $status ) ) {
6911
			return $status;
6912
		}
6913
6914
		// Check if a modern version of Akismet is active.
6915
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6916
			$status = false;
6917
			return $status;
6918
		}
6919
6920
		// Make sure there is a key known to Akismet at all before verifying key.
6921
		$akismet_key = Akismet::get_api_key();
6922
		if ( ! $akismet_key ) {
6923
			$status = false;
6924
			return $status;
6925
		}
6926
6927
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6928
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6929
6930
		// 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.
6931
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6932
		// We cache the result of the Akismet key verification for ten minutes.
6933
		if ( ! $akismet_key_state || $recheck ) {
6934
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6935
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6936
		}
6937
6938
		$status = 'valid' === $akismet_key_state;
6939
6940
		return $status;
6941
	}
6942
6943
	/**
6944
	 * Checks if one or more function names is in debug_backtrace
6945
	 *
6946
	 * @param $names Mixed string name of function or array of string names of functions
6947
	 *
6948
	 * @return bool
6949
	 */
6950
	public static function is_function_in_backtrace( $names ) {
6951
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6952
		if ( ! is_array( $names ) ) {
6953
			$names = array( $names );
6954
		}
6955
		$names_as_keys = array_flip( $names );
6956
6957
		//Do check in constant O(1) time for PHP5.5+
6958
		if ( function_exists( 'array_column' ) ) {
6959
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6960
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6961
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6962
			return ! empty ( $intersection );
6963
		}
6964
6965
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6966
		foreach ( $backtrace as $call ) {
6967
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6968
				return true;
6969
			}
6970
		}
6971
		return false;
6972
	}
6973
6974
	/**
6975
	 * Given a minified path, and a non-minified path, will return
6976
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6977
	 *
6978
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6979
	 * root Jetpack directory.
6980
	 *
6981
	 * @since 5.6.0
6982
	 *
6983
	 * @param string $min_path
6984
	 * @param string $non_min_path
6985
	 * @return string The URL to the file
6986
	 */
6987
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6988
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
6989
			? $non_min_path
6990
			: $min_path;
6991
6992
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6993
	}
6994
6995
	/**
6996
	 * Checks for whether Jetpack Backup & Scan is enabled.
6997
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6998
	 * @return bool|int|mixed
6999
	 */
7000
	public static function is_rewind_enabled() {
7001
		if ( ! Jetpack::is_active() ) {
7002
			return false;
7003
		}
7004
7005
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7006
		if ( false === $rewind_enabled ) {
7007
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7008
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7009
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7010
				&& ! empty( $rewind_data['state'] )
7011
				&& 'active' === $rewind_data['state'] )
7012
				? 1
7013
				: 0;
7014
7015
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7016
		}
7017
		return $rewind_enabled;
7018
	}
7019
7020
	/**
7021
	 * Checks whether or not TOS has been agreed upon.
7022
	 * Will return true if a user has clicked to register, or is already connected.
7023
	 */
7024
	public static function jetpack_tos_agreed() {
7025
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7026
	}
7027
7028
	/**
7029
	 * Handles activating default modules as well general cleanup for the new connection.
7030
	 *
7031
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7032
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7033
	 * @param boolean $send_state_messages          Whether to send state messages.
7034
	 * @return void
7035
	 */
7036
	public static function handle_post_authorization_actions(
7037
		$activate_sso = false,
7038
		$redirect_on_activation_error = false,
7039
		$send_state_messages = true
7040
	) {
7041
		$other_modules = $activate_sso
7042
			? array( 'sso' )
7043
			: array();
7044
7045
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7046
			Jetpack::delete_active_modules();
7047
7048
			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...
7049
		} else {
7050
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7051
		}
7052
7053
		// Since this is a fresh connection, be sure to clear out IDC options
7054
		Jetpack_IDC::clear_all_idc_options();
7055
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7056
7057
		// Start nonce cleaner
7058
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7059
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7060
7061
		if ( $send_state_messages ) {
7062
			Jetpack::state( 'message', 'authorized' );
7063
		}
7064
	}
7065
7066
	/**
7067
	 * Returns a boolean for whether backups UI should be displayed or not.
7068
	 *
7069
	 * @return bool Should backups UI be displayed?
7070
	 */
7071
	public static function show_backups_ui() {
7072
		/**
7073
		 * Whether UI for backups should be displayed.
7074
		 *
7075
		 * @since 6.5.0
7076
		 *
7077
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7078
		 */
7079
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7080
	}
7081
7082
	/*
7083
	 * Deprecated manage functions
7084
	 */
7085
	function prepare_manage_jetpack_notice() {
7086
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7087
	}
7088
	function manage_activate_screen() {
7089
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7090
	}
7091
	function admin_jetpack_manage_notice() {
7092
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7093
	}
7094
	function opt_out_jetpack_manage_url() {
7095
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7096
	}
7097
	function opt_in_jetpack_manage_url() {
7098
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7099
	}
7100
	function opt_in_jetpack_manage_notice() {
7101
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7102
	}
7103
	function can_display_jetpack_manage_notice() {
7104
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7105
	}
7106
}
7107