Completed
Push — add/private-sites ( 11bd70...ee9ac5 )
by
unknown
08:45
created

Jetpack::private_site_privacy_on_link_text()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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