Completed
Push — update/use-wordpress-api-fetch... ( 2f6fe4...cd05e3 )
by
unknown
124:11 queued 116:32
created

Jetpack::is_akismet_active()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

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