Completed
Push — gm18/grunionblock ( c0d4d9...98e9b9 )
by George
10:00 queued 01:55
created

Jetpack::prepare_manage_jetpack_notice()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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