Completed
Push — remove/vr-gutenblock ( 84993f...ae61cd )
by Bernhard
385:01 queued 377:44
created

Jetpack::enqueue_gutenberg_locale()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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