Completed
Push — update/package-tracks-move-mor... ( 3dab7f...8b58be )
by Marin
188:46 queued 181:30
created

Jetpack::track_jetpack_verify_secrets_fail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
5
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
6
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
7
use Automattic\Jetpack\Constants;
8
use Automattic\Jetpack\Tracking;
9
10
/*
11
Options:
12
jetpack_options (array)
13
	An array of options.
14
	@see Jetpack_Options::get_option_names()
15
16
jetpack_register (string)
17
	Temporary verification secrets.
18
19
jetpack_activated (int)
20
	1: the plugin was activated normally
21
	2: the plugin was activated on this site because of a network-wide activation
22
	3: the plugin was auto-installed
23
	4: the plugin was manually disconnected (but is still installed)
24
25
jetpack_active_modules (array)
26
	Array of active module slugs.
27
28
jetpack_do_activate (bool)
29
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
30
*/
31
32
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
33
34
class Jetpack {
35
	public $xmlrpc_server = null;
36
37
	private $xmlrpc_verification = null;
38
	private $rest_authentication_status = null;
39
40
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
41
42
	private $tracking;
43
44
	/**
45
	 * @var array The handles of styles that are concatenated into jetpack.css.
46
	 *
47
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
48
	 */
49
	public $concatenated_style_handles = array(
50
		'jetpack-carousel',
51
		'grunion.css',
52
		'the-neverending-homepage',
53
		'jetpack_likes',
54
		'jetpack_related-posts',
55
		'sharedaddy',
56
		'jetpack-slideshow',
57
		'presentations',
58
		'quiz',
59
		'jetpack-subscriptions',
60
		'jetpack-responsive-videos-style',
61
		'jetpack-social-menu',
62
		'tiled-gallery',
63
		'jetpack_display_posts_widget',
64
		'gravatar-profile-widget',
65
		'goodreads-widget',
66
		'jetpack_social_media_icons_widget',
67
		'jetpack-top-posts-widget',
68
		'jetpack_image_widget',
69
		'jetpack-my-community-widget',
70
		'jetpack-authors-widget',
71
		'wordads',
72
		'eu-cookie-law-style',
73
		'flickr-widget-style',
74
		'jetpack-search-widget',
75
		'jetpack-simple-payments-widget-style',
76
		'jetpack-widget-social-icons-styles',
77
	);
78
79
	/**
80
	 * Contains all assets that have had their URL rewritten to minified versions.
81
	 *
82
	 * @var array
83
	 */
84
	static $min_assets = array();
85
86
	public $plugins_to_deactivate = array(
87
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
88
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
89
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
90
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
91
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
92
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
93
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
94
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
95
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
96
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
97
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
98
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
99
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
100
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
101
	);
102
103
	static $capability_translations = array(
104
		'administrator' => 'manage_options',
105
		'editor'        => 'edit_others_posts',
106
		'author'        => 'publish_posts',
107
		'contributor'   => 'edit_posts',
108
		'subscriber'    => 'read',
109
	);
110
111
	/**
112
	 * Map of modules that have conflicts with plugins and should not be auto-activated
113
	 * if the plugins are active.  Used by filter_default_modules
114
	 *
115
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
116
	 * change `module-slug` and add this to your plugin:
117
	 *
118
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
119
	 * function my_jetpack_get_default_modules( $modules ) {
120
	 *     return array_diff( $modules, array( 'module-slug' ) );
121
	 * }
122
	 *
123
	 * @var array
124
	 */
125
	private $conflicting_plugins = array(
126
		'comments'          => array(
127
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
128
			'Disqus'                               => 'disqus-comment-system/disqus.php',
129
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
130
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
131
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
132
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
133
		),
134
		'comment-likes' => array(
135
			'Epoch'                                => 'epoch/plugincore.php',
136
		),
137
		'contact-form'      => array(
138
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
139
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
140
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
141
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
142
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
143
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
144
		),
145
		'minileven'         => array(
146
			'WPtouch'                              => 'wptouch/wptouch.php',
147
		),
148
		'latex'             => array(
149
			'LaTeX for WordPress'                  => 'latex/latex.php',
150
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
151
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
152
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
153
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
154
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
155
		),
156
		'protect'           => array(
157
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
158
			'Captcha'                              => 'captcha/captcha.php',
159
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
160
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
161
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
162
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
163
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
164
			'Security-protection'                  => 'security-protection/security-protection.php',
165
			'Login Security'                       => 'login-security/login-security.php',
166
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
167
			'Wordfence Security'                   => 'wordfence/wordfence.php',
168
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
169
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
170
		),
171
		'random-redirect'   => array(
172
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
173
		),
174
		'related-posts'     => array(
175
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
176
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
177
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
178
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
179
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
180
			'outbrain'                             => 'outbrain/outbrain.php',
181
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
182
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
183
		),
184
		'sharedaddy'        => array(
185
			'AddThis'                              => 'addthis/addthis_social_widget.php',
186
			'Add To Any'                           => 'add-to-any/add-to-any.php',
187
			'ShareThis'                            => 'share-this/sharethis.php',
188
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
189
		),
190
		'seo-tools' => array(
191
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
192
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
193
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
194
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
195
			'The SEO Framework'                    => 'autodescription/autodescription.php',
196
		),
197
		'verification-tools' => array(
198
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
199
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
200
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
201
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
202
			'The SEO Framework'                    => 'autodescription/autodescription.php',
203
		),
204
		'widget-visibility' => array(
205
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
206
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
207
		),
208
		'sitemaps' => array(
209
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
210
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
211
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
212
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
213
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
214
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'                    => 'autodescription/autodescription.php',
219
			'Sitemap'                              => 'sitemap/sitemap.php',
220
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
221
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
222
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
223
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
224
		),
225
		'lazy-images' => array(
226
			'Lazy Load'              => 'lazy-load/lazy-load.php',
227
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
228
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
229
		),
230
	);
231
232
	/**
233
	 * Plugins for which we turn off our Facebook OG Tags implementation.
234
	 *
235
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
236
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
237
	 *
238
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
239
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
240
	 */
241
	private $open_graph_conflicting_plugins = array(
242
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
243
		                                                         // 2 Click Social Media Buttons
244
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
245
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
246
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
247
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
248
		                                                         // Open Graph Meta Tags by Heateor
249
		'facebook/facebook.php',                                 // Facebook (official plugin)
250
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
251
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
252
		                                                         // Facebook Featured Image & OG Meta Tags
253
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
254
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
255
		                                                         // Facebook Open Graph Meta Tags for WordPress
256
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
257
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
258
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
259
		                                                         // Fedmich's Facebook Open Graph Meta
260
		'network-publisher/networkpub.php',                      // Network Publisher
261
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
262
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
263
		                                                         // NextScripts SNAP
264
		'og-tags/og-tags.php',                                   // OG Tags
265
		'opengraph/opengraph.php',                               // Open Graph
266
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
267
		                                                         // Open Graph Protocol Framework
268
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
269
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
270
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
271
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
272
		'sharepress/sharepress.php',                             // SharePress
273
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
274
		'social-discussions/social-discussions.php',             // Social Discussions
275
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
276
		'socialize/socialize.php',                               // Socialize
277
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
278
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
279
		                                                         // Tweet, Like, Google +1 and Share
280
		'wordbooker/wordbooker.php',                             // Wordbooker
281
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
282
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
283
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
284
		                                                         // WP Facebook Like Send & Open Graph Meta
285
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
286
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
287
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
288
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
289
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
290
	);
291
292
	/**
293
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
294
	 */
295
	private $twitter_cards_conflicting_plugins = array(
296
	//	'twitter/twitter.php',                       // The official one handles this on its own.
297
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
298
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
299
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
300
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
301
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
302
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
303
		'twitter-cards/twitter-cards.php',           // Twitter Cards
304
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
305
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
306
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
307
	);
308
309
	/**
310
	 * Message to display in admin_notice
311
	 * @var string
312
	 */
313
	public $message = '';
314
315
	/**
316
	 * Error to display in admin_notice
317
	 * @var string
318
	 */
319
	public $error = '';
320
321
	/**
322
	 * Modules that need more privacy description.
323
	 * @var string
324
	 */
325
	public $privacy_checks = '';
326
327
	/**
328
	 * Stats to record once the page loads
329
	 *
330
	 * @var array
331
	 */
332
	public $stats = array();
333
334
	/**
335
	 * Jetpack_Sync object
336
	 */
337
	public $sync;
338
339
	/**
340
	 * Verified data for JSON authorization request
341
	 */
342
	public $json_api_authorization_request = array();
343
344
	/**
345
	 * @var \Automattic\Jetpack\Connection\Manager
346
	 */
347
	protected $connection_manager;
348
349
	/**
350
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
351
	 */
352
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
353
354
	/**
355
	 * Holds the singleton instance of this class
356
	 * @since 2.3.3
357
	 * @var Jetpack
358
	 */
359
	static $instance = false;
360
361
	/**
362
	 * Singleton
363
	 * @static
364
	 */
365
	public static function init() {
366
		if ( ! self::$instance ) {
367
			self::$instance = new Jetpack;
368
369
			self::$instance->plugin_upgrade();
370
		}
371
372
		return self::$instance;
373
	}
374
375
	/**
376
	 * Must never be called statically
377
	 */
378
	function plugin_upgrade() {
379
		if ( Jetpack::is_active() ) {
380
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
381
			if ( JETPACK__VERSION != $version ) {
382
				// Prevent multiple upgrades at once - only a single process should trigger
383
				// an upgrade to avoid stampedes
384
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
385
					return;
386
				}
387
388
				// Set a short lock to prevent multiple instances of the upgrade
389
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
390
391
				// check which active modules actually exist and remove others from active_modules list
392
				$unfiltered_modules = Jetpack::get_active_modules();
393
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
394
				if ( array_diff( $unfiltered_modules, $modules ) ) {
395
					Jetpack::update_active_modules( $modules );
396
				}
397
398
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
399
400
				// Upgrade to 4.3.0
401
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
402
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
403
				}
404
405
				// Make sure Markdown for posts gets turned back on
406
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
407
					update_option( 'wpcom_publish_posts_with_markdown', true );
408
				}
409
410
				if ( did_action( 'wp_loaded' ) ) {
411
					self::upgrade_on_load();
412
				} else {
413
					add_action(
414
						'wp_loaded',
415
						array( __CLASS__, 'upgrade_on_load' )
416
					);
417
				}
418
			}
419
		}
420
	}
421
422
	/**
423
	 * Runs upgrade routines that need to have modules loaded.
424
	 */
425
	static function upgrade_on_load() {
426
427
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
428
		// This can happen in case Jetpack has been just upgraded and is
429
		// being initialized late during the page load. In this case we wait
430
		// until the next proper admin page load with Jetpack active.
431
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
432
			delete_transient( self::$plugin_upgrade_lock_key );
433
434
			return;
435
		}
436
437
		Jetpack::maybe_set_version_option();
438
439
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
440
			Jetpack_Widget_Conditions::migrate_post_type_rules();
441
		}
442
443
		if (
444
			class_exists( 'Jetpack_Sitemap_Manager' )
445
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
446
		) {
447
			do_action( 'jetpack_sitemaps_purge_data' );
448
		}
449
450
		delete_transient( self::$plugin_upgrade_lock_key );
451
	}
452
453
	/**
454
	 * Saves all the currently active modules to options.
455
	 * Also fires Action hooks for each newly activated and deactivated module.
456
	 *
457
	 * @param $modules Array Array of active modules to be saved in options.
458
	 *
459
	 * @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...
460
	 */
461
	static function update_active_modules( $modules ) {
462
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
463
		$active_modules       = Jetpack::get_active_modules();
464
		$new_active_modules   = array_diff( $modules, $current_modules );
465
		$new_inactive_modules = array_diff( $active_modules, $modules );
466
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
467
		$reindexed_modules    = array_values( $new_current_modules );
468
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
469
470
		foreach ( $new_active_modules as $module ) {
471
			/**
472
			 * Fires when a specific module is activated.
473
			 *
474
			 * @since 1.9.0
475
			 *
476
			 * @param string $module Module slug.
477
			 * @param boolean $success whether the module was activated. @since 4.2
478
			 */
479
			do_action( 'jetpack_activate_module', $module, $success );
480
			/**
481
			 * Fires when a module is activated.
482
			 * The dynamic part of the filter, $module, is the module slug.
483
			 *
484
			 * @since 1.9.0
485
			 *
486
			 * @param string $module Module slug.
487
			 */
488
			do_action( "jetpack_activate_module_$module", $module );
489
		}
490
491
		foreach ( $new_inactive_modules as $module ) {
492
			/**
493
			 * Fired after a module has been deactivated.
494
			 *
495
			 * @since 4.2.0
496
			 *
497
			 * @param string $module Module slug.
498
			 * @param boolean $success whether the module was deactivated.
499
			 */
500
			do_action( 'jetpack_deactivate_module', $module, $success );
501
			/**
502
			 * Fires when a module is deactivated.
503
			 * The dynamic part of the filter, $module, is the module slug.
504
			 *
505
			 * @since 1.9.0
506
			 *
507
			 * @param string $module Module slug.
508
			 */
509
			do_action( "jetpack_deactivate_module_$module", $module );
510
		}
511
512
		return $success;
513
	}
514
515
	static function delete_active_modules() {
516
		self::update_active_modules( array() );
517
	}
518
519
	/**
520
	 * Constructor.  Initializes WordPress hooks
521
	 */
522
	private function __construct() {
523
		/*
524
		 * Check for and alert any deprecated hooks
525
		 */
526
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
527
528
		/*
529
		 * Enable enhanced handling of previewing sites in Calypso
530
		 */
531
		if ( Jetpack::is_active() ) {
532
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
533
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
534
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
535
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
536
		}
537
538
		$this->tracking = new Tracking( 'jetpack' );
539
		add_action( 'init', array( $this, 'track_jetpack_usage' ) );
540
541
		/*
542
		 * Load things that should only be in Network Admin.
543
		 *
544
		 * For now blow away everything else until a more full
545
		 * understanding of what is needed at the network level is
546
		 * available
547
		 */
548
		if ( is_multisite() ) {
549
			Jetpack_Network::init();
550
		}
551
552
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
553
			return function() {
554
				return wp_generate_password( 32, false );
555
			};
556
		} );
557
558
		$this->connection_manager = new Connection_Manager( );
559
560
		/**
561
		 * Prepare Gutenberg Editor functionality
562
		 */
563
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
564
		Jetpack_Gutenberg::init();
565
		Jetpack_Gutenberg::load_independent_blocks();
566
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
567
568
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
569
570
		// Unlink user before deleting the user from .com
571
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
572
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
573
574
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
575
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
576
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
577
				define( 'XMLRPC_REQUEST', true );
578
			}
579
580
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
581
582
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
583
		}
584
585
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
586
			@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...
587
588
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
589
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
590
591
			$this->require_jetpack_authentication();
592
593
			if ( Jetpack::is_active() ) {
594
				// Hack to preserve $HTTP_RAW_POST_DATA
595
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
596
597
				$signed = $this->verify_xml_rpc_signature();
598
				if ( $signed && ! is_wp_error( $signed ) ) {
599
					// The actual API methods.
600
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
601
				} else {
602
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
603
					// active Jetpack connection, so that additional users can link their account.
604
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
605
				}
606
			} else {
607
				new XMLRPC_Connector( $this->connection_manager );
608
609
				// The bootstrap API methods.
610
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
611
				$signed = $this->verify_xml_rpc_signature();
612
				if ( $signed && ! is_wp_error( $signed ) ) {
613
					// the jetpack Provision method is available for blog-token-signed requests
614
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
615
				}
616
			}
617
618
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
619
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
620
		} elseif (
621
			is_admin() &&
622
			isset( $_POST['action'] ) && (
623
				'jetpack_upload_file' == $_POST['action'] ||
624
				'jetpack_update_file' == $_POST['action']
625
			)
626
		) {
627
			$this->require_jetpack_authentication();
628
			$this->add_remote_request_handlers();
629
		} else {
630
			if ( Jetpack::is_active() ) {
631
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
632
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
633
			} else {
634
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
635
			}
636
		}
637
638
		if ( Jetpack::is_active() ) {
639
			Jetpack_Heartbeat::init();
640
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
641
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
642
				Jetpack_Search_Performance_Logger::init();
643
			}
644
		}
645
646
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
647
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
648
649
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
650
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
651
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
652
		}
653
654
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
655
656
		add_action( 'admin_init', array( $this, 'admin_init' ) );
657
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
658
659
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
660
661
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
662
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
663
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
664
665
		// returns HTTPS support status
666
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
667
668
		// JITM AJAX callback function
669
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
670
671
		// Universal ajax callback for all tracking events triggered via js
672
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
673
674
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
675
676
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
677
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
678
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
679
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
680
681
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
682
683
		/**
684
		 * These actions run checks to load additional files.
685
		 * They check for external files or plugins, so they need to run as late as possible.
686
		 */
687
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
688
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
689
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
690
691
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
692
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
693
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
694
695
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
696
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
697
698
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
700
701
		// A filter to control all just in time messages
702
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
703
704
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
705
706
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
707
		// We should make sure to only do this for front end links.
708
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
709
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
710
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
711
712
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
713
			//so they point moderation links on emails to Calypso
714
			jetpack_require_lib( 'functions.wp-notify' );
715
		}
716
717
		// Update the Jetpack plan from API on heartbeats
718
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
719
720
		/**
721
		 * This is the hack to concatenate all css files into one.
722
		 * For description and reasoning see the implode_frontend_css method
723
		 *
724
		 * Super late priority so we catch all the registered styles
725
		 */
726
		if( !is_admin() ) {
727
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
728
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
729
		}
730
731
732
		/**
733
		 * These are sync actions that we need to keep track of for jitms
734
		 */
735
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
736
737
		// Actually push the stats on shutdown.
738
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
739
			add_action( 'shutdown', array( $this, 'push_stats' ) );
740
		}
741
742
		// Track that we've begun verifying the previously generated secret.
743
		add_action( 'jetpack_verify_secrets_begin', array( $this, 'track_jetpack_verify_secrets_begin' ), 10, 2 );
744
		add_action( 'jetpack_verify_secrets_success', array( $this, 'track_jetpack_verify_secrets_success' ), 10, 2 );
745
		add_action( 'jetpack_verify_secrets_fail', array( $this, 'track_jetpack_verify_secrets_fail' ), 10, 3 );
746
	}
747
748
	function initialize_rest_api_registration_connector() {
749
		new REST_Connector( $this->connection_manager );
750
	}
751
752
	/**
753
	 * This is ported over from the manage module, which has been deprecated and baked in here.
754
	 *
755
	 * @param $domains
756
	 */
757
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
758
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
759
	}
760
761
	/**
762
	 * Return $domains, with 'wordpress.com' appended.
763
	 * This is ported over from the manage module, which has been deprecated and baked in here.
764
	 *
765
	 * @param $domains
766
	 * @return array
767
	 */
768
	function allow_wpcom_domain( $domains ) {
769
		if ( empty( $domains ) ) {
770
			$domains = array();
771
		}
772
		$domains[] = 'wordpress.com';
773
		return array_unique( $domains );
774
	}
775
776
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
777
		$post = get_post( $post_id );
778
779
		if ( empty( $post ) ) {
780
			return $default_url;
781
		}
782
783
		$post_type = $post->post_type;
784
785
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
786
		// https://en.support.wordpress.com/custom-post-types/
787
		$allowed_post_types = array(
788
			'post' => 'post',
789
			'page' => 'page',
790
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
791
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
792
		);
793
794
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
795
			return $default_url;
796
		}
797
798
		$path_prefix = $allowed_post_types[ $post_type ];
799
800
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
801
802
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
803
	}
804
805
	function point_edit_comment_links_to_calypso( $url ) {
806
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
807
		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...
808
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
809
			Jetpack::build_raw_urls( get_home_url() ),
810
			$query_args['amp;c']
811
		) );
812
	}
813
814
	function jetpack_track_last_sync_callback( $params ) {
815
		/**
816
		 * Filter to turn off jitm caching
817
		 *
818
		 * @since 5.4.0
819
		 *
820
		 * @param bool false Whether to cache just in time messages
821
		 */
822
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
823
			return $params;
824
		}
825
826
		if ( is_array( $params ) && isset( $params[0] ) ) {
827
			$option = $params[0];
828
			if ( 'active_plugins' === $option ) {
829
				// use the cache if we can, but not terribly important if it gets evicted
830
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
831
			}
832
		}
833
834
		return $params;
835
	}
836
837
	function jetpack_connection_banner_callback() {
838
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
839
840
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
841
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
842
			wp_send_json_success();
843
		}
844
845
		wp_die();
846
	}
847
848
	/**
849
	 * Removes all XML-RPC methods that are not `jetpack.*`.
850
	 * Only used in our alternate XML-RPC endpoint, where we want to
851
	 * ensure that Core and other plugins' methods are not exposed.
852
	 *
853
	 * @param array $methods
854
	 * @return array filtered $methods
855
	 */
856
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
857
		$jetpack_methods = array();
858
859
		foreach ( $methods as $method => $callback ) {
860
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
861
				$jetpack_methods[ $method ] = $callback;
862
			}
863
		}
864
865
		return $jetpack_methods;
866
	}
867
868
	/**
869
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
870
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
871
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
872
	 * which is accessible via a different URI. Most of the below is copied directly
873
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
874
	 */
875
	function alternate_xmlrpc() {
876
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
877
		global $HTTP_RAW_POST_DATA;
878
879
		// Some browser-embedded clients send cookies. We don't want them.
880
		$_COOKIE = array();
881
882
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
883
		// but we can do it ourself.
884
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
885
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
886
		}
887
888
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
889
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
890
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
891
		}
892
893
		// phpcs:enable
894
895
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
896
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
897
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
898
899
		/**
900
		 * Filters the class used for handling XML-RPC requests.
901
		 *
902
		 * @since 3.1.0
903
		 *
904
		 * @param string $class The name of the XML-RPC server class.
905
		 */
906
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
907
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
908
909
		// Fire off the request
910
		nocache_headers();
911
		$wp_xmlrpc_server->serve_request();
912
913
		exit;
914
	}
915
916
	function jetpack_admin_ajax_tracks_callback() {
917
		// Check for nonce
918
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
919
			wp_die( 'Permissions check failed.' );
920
		}
921
922
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
923
			wp_die( 'No valid event name or type.' );
924
		}
925
926
		$tracks_data = array();
927
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
928
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
929
				$tracks_data = $_REQUEST['tracksEventProp'];
930
			} else {
931
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
932
			}
933
		}
934
935
		$this->tracking->record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
936
		wp_send_json_success();
937
		wp_die();
938
	}
939
940
	/**
941
	 * The callback for the JITM ajax requests.
942
	 */
943
	function jetpack_jitm_ajax_callback() {
944
		// Check for nonce
945
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
946
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
947
		}
948
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
949
			$module_slug = $_REQUEST['jitmModule'];
950
			Jetpack::log( 'activate', $module_slug );
951
			Jetpack::activate_module( $module_slug, false, false );
952
			Jetpack::state( 'message', 'no_message' );
953
954
			//A Jetpack module is being activated through a JITM, track it
955
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
956
			$this->do_stats( 'server_side' );
957
958
			wp_send_json_success();
959
		}
960
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
961
			// get the hide_jitm options array
962
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
963
			$module_slug = $_REQUEST['jitmModule'];
964
965
			if( ! $jetpack_hide_jitm ) {
966
				$jetpack_hide_jitm = array(
967
					$module_slug => 'hide'
968
				);
969
			} else {
970
				$jetpack_hide_jitm[$module_slug] = 'hide';
971
			}
972
973
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
974
975
			//jitm is being dismissed forever, track it
976
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
977
			$this->do_stats( 'server_side' );
978
979
			wp_send_json_success();
980
		}
981 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
982
			$module_slug = $_REQUEST['jitmModule'];
983
984
			// User went to WordPress.com, track this
985
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
986
			$this->do_stats( 'server_side' );
987
988
			wp_send_json_success();
989
		}
990 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
991
			$track = $_REQUEST['jitmModule'];
992
993
			// User is viewing JITM, track it.
994
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
995
			$this->do_stats( 'server_side' );
996
997
			wp_send_json_success();
998
		}
999
	}
1000
1001
	/**
1002
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1003
	 */
1004
	function push_stats() {
1005
		if ( ! empty( $this->stats ) ) {
1006
			$this->do_stats( 'server_side' );
1007
		}
1008
	}
1009
1010
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1011
		switch( $cap ) {
1012
			case 'jetpack_connect' :
1013
			case 'jetpack_reconnect' :
1014
				if ( Jetpack::is_development_mode() ) {
1015
					$caps = array( 'do_not_allow' );
1016
					break;
1017
				}
1018
				/**
1019
				 * Pass through. If it's not development mode, these should match disconnect.
1020
				 * Let users disconnect if it's development mode, just in case things glitch.
1021
				 */
1022
			case 'jetpack_disconnect' :
1023
				/**
1024
				 * In multisite, can individual site admins manage their own connection?
1025
				 *
1026
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1027
				 */
1028
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1029
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1030
						/**
1031
						 * We need to update the option name -- it's terribly unclear which
1032
						 * direction the override goes.
1033
						 *
1034
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1035
						 */
1036
						$caps = array( 'do_not_allow' );
1037
						break;
1038
					}
1039
				}
1040
1041
				$caps = array( 'manage_options' );
1042
				break;
1043
			case 'jetpack_manage_modules' :
1044
			case 'jetpack_activate_modules' :
1045
			case 'jetpack_deactivate_modules' :
1046
				$caps = array( 'manage_options' );
1047
				break;
1048
			case 'jetpack_configure_modules' :
1049
				$caps = array( 'manage_options' );
1050
				break;
1051
			case 'jetpack_manage_autoupdates' :
1052
				$caps = array(
1053
					'manage_options',
1054
					'update_plugins',
1055
				);
1056
				break;
1057
			case 'jetpack_network_admin_page':
1058
			case 'jetpack_network_settings_page':
1059
				$caps = array( 'manage_network_plugins' );
1060
				break;
1061
			case 'jetpack_network_sites_page':
1062
				$caps = array( 'manage_sites' );
1063
				break;
1064
			case 'jetpack_admin_page' :
1065
				if ( Jetpack::is_development_mode() ) {
1066
					$caps = array( 'manage_options' );
1067
					break;
1068
				} else {
1069
					$caps = array( 'read' );
1070
				}
1071
				break;
1072
			case 'jetpack_connect_user' :
1073
				if ( Jetpack::is_development_mode() ) {
1074
					$caps = array( 'do_not_allow' );
1075
					break;
1076
				}
1077
				$caps = array( 'read' );
1078
				break;
1079
		}
1080
		return $caps;
1081
	}
1082
1083
	function require_jetpack_authentication() {
1084
		// Don't let anyone authenticate
1085
		$_COOKIE = array();
1086
		remove_all_filters( 'authenticate' );
1087
		remove_all_actions( 'wp_login_failed' );
1088
1089
		if ( Jetpack::is_active() ) {
1090
			// Allow Jetpack authentication
1091
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1092
		}
1093
	}
1094
1095
	/**
1096
	 * Load language files
1097
	 * @action plugins_loaded
1098
	 */
1099
	public static function plugin_textdomain() {
1100
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1101
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1102
	}
1103
1104
	/**
1105
	 * Register assets for use in various modules and the Jetpack admin page.
1106
	 *
1107
	 * @uses wp_script_is, wp_register_script, plugins_url
1108
	 * @action wp_loaded
1109
	 * @return null
1110
	 */
1111
	public function register_assets() {
1112
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1113
			wp_register_script(
1114
				'spin',
1115
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1116
				false,
1117
				'1.3'
1118
			);
1119
		}
1120
1121
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1122
			wp_register_script(
1123
				'jquery.spin',
1124
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1125
				array( 'jquery', 'spin' ),
1126
				'1.3'
1127
			);
1128
		}
1129
1130 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1131
			wp_register_script(
1132
				'jetpack-gallery-settings',
1133
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1134
				array( 'media-views' ),
1135
				'20121225'
1136
			);
1137
		}
1138
1139
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1140
			wp_register_script(
1141
				'jetpack-twitter-timeline',
1142
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1143
				array( 'jquery' ),
1144
				'4.0.0',
1145
				true
1146
			);
1147
		}
1148
1149
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1150
			wp_register_script(
1151
				'jetpack-facebook-embed',
1152
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1153
				array( 'jquery' ),
1154
				null,
1155
				true
1156
			);
1157
1158
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1159
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1160
			if ( ! is_numeric( $fb_app_id ) ) {
1161
				$fb_app_id = '';
1162
			}
1163
			wp_localize_script(
1164
				'jetpack-facebook-embed',
1165
				'jpfbembed',
1166
				array(
1167
					'appid' => $fb_app_id,
1168
					'locale' => $this->get_locale(),
1169
				)
1170
			);
1171
		}
1172
1173
		/**
1174
		 * As jetpack_register_genericons is by default fired off a hook,
1175
		 * the hook may have already fired by this point.
1176
		 * So, let's just trigger it manually.
1177
		 */
1178
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1179
		jetpack_register_genericons();
1180
1181
		/**
1182
		 * Register the social logos
1183
		 */
1184
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1185
		jetpack_register_social_logos();
1186
1187 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1188
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1189
	}
1190
1191
	/**
1192
	 * Guess locale from language code.
1193
	 *
1194
	 * @param string $lang Language code.
1195
	 * @return string|bool
1196
	 */
1197 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1198
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1199
			return 'en_US';
1200
		}
1201
1202
		if ( ! class_exists( 'GP_Locales' ) ) {
1203
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1204
				return false;
1205
			}
1206
1207
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1208
		}
1209
1210
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1211
			// WP.com: get_locale() returns 'it'
1212
			$locale = GP_Locales::by_slug( $lang );
1213
		} else {
1214
			// Jetpack: get_locale() returns 'it_IT';
1215
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1216
		}
1217
1218
		if ( ! $locale ) {
1219
			return false;
1220
		}
1221
1222
		if ( empty( $locale->facebook_locale ) ) {
1223
			if ( empty( $locale->wp_locale ) ) {
1224
				return false;
1225
			} else {
1226
				// Facebook SDK is smart enough to fall back to en_US if a
1227
				// locale isn't supported. Since supported Facebook locales
1228
				// can fall out of sync, we'll attempt to use the known
1229
				// wp_locale value and rely on said fallback.
1230
				return $locale->wp_locale;
1231
			}
1232
		}
1233
1234
		return $locale->facebook_locale;
1235
	}
1236
1237
	/**
1238
	 * Get the locale.
1239
	 *
1240
	 * @return string|bool
1241
	 */
1242
	function get_locale() {
1243
		$locale = $this->guess_locale_from_lang( get_locale() );
1244
1245
		if ( ! $locale ) {
1246
			$locale = 'en_US';
1247
		}
1248
1249
		return $locale;
1250
	}
1251
1252
	/**
1253
	 * Device Pixels support
1254
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1255
	 */
1256
	function devicepx() {
1257
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1258
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1259
		}
1260
	}
1261
1262
	/**
1263
	 * Return the network_site_url so that .com knows what network this site is a part of.
1264
	 * @param  bool $option
1265
	 * @return string
1266
	 */
1267
	public function jetpack_main_network_site_option( $option ) {
1268
		return network_site_url();
1269
	}
1270
	/**
1271
	 * Network Name.
1272
	 */
1273
	static function network_name( $option = null ) {
1274
		global $current_site;
1275
		return $current_site->site_name;
1276
	}
1277
	/**
1278
	 * Does the network allow new user and site registrations.
1279
	 * @return string
1280
	 */
1281
	static function network_allow_new_registrations( $option = null ) {
1282
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1283
	}
1284
	/**
1285
	 * Does the network allow admins to add new users.
1286
	 * @return boolian
1287
	 */
1288
	static function network_add_new_users( $option = null ) {
1289
		return (bool) get_site_option( 'add_new_users' );
1290
	}
1291
	/**
1292
	 * File upload psace left per site in MB.
1293
	 *  -1 means NO LIMIT.
1294
	 * @return number
1295
	 */
1296
	static function network_site_upload_space( $option = null ) {
1297
		// value in MB
1298
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1299
	}
1300
1301
	/**
1302
	 * Network allowed file types.
1303
	 * @return string
1304
	 */
1305
	static function network_upload_file_types( $option = null ) {
1306
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1307
	}
1308
1309
	/**
1310
	 * Maximum file upload size set by the network.
1311
	 * @return number
1312
	 */
1313
	static function network_max_upload_file_size( $option = null ) {
1314
		// value in KB
1315
		return get_site_option( 'fileupload_maxk', 300 );
1316
	}
1317
1318
	/**
1319
	 * Lets us know if a site allows admins to manage the network.
1320
	 * @return array
1321
	 */
1322
	static function network_enable_administration_menus( $option = null ) {
1323
		return get_site_option( 'menu_items' );
1324
	}
1325
1326
	/**
1327
	 * If a user has been promoted to or demoted from admin, we need to clear the
1328
	 * jetpack_other_linked_admins transient.
1329
	 *
1330
	 * @since 4.3.2
1331
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1332
	 *
1333
	 * @param int    $user_id   The user ID whose role changed.
1334
	 * @param string $role      The new role.
1335
	 * @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...
1336
	 */
1337
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1338
		if ( 'administrator' == $role
1339
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1340
			|| is_null( $old_roles )
1341
		) {
1342
			delete_transient( 'jetpack_other_linked_admins' );
1343
		}
1344
	}
1345
1346
	/**
1347
	 * Checks to see if there are any other users available to become primary
1348
	 * Users must both:
1349
	 * - Be linked to wpcom
1350
	 * - Be an admin
1351
	 *
1352
	 * @return mixed False if no other users are linked, Int if there are.
1353
	 */
1354
	static function get_other_linked_admins() {
1355
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1356
1357
		if ( false === $other_linked_users ) {
1358
			$admins = get_users( array( 'role' => 'administrator' ) );
1359
			if ( count( $admins ) > 1 ) {
1360
				$available = array();
1361
				foreach ( $admins as $admin ) {
1362
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1363
						$available[] = $admin->ID;
1364
					}
1365
				}
1366
1367
				$count_connected_admins = count( $available );
1368
				if ( count( $available ) > 1 ) {
1369
					$other_linked_users = $count_connected_admins;
1370
				} else {
1371
					$other_linked_users = 0;
1372
				}
1373
			} else {
1374
				$other_linked_users = 0;
1375
			}
1376
1377
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1378
		}
1379
1380
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1381
	}
1382
1383
	/**
1384
	 * Return whether we are dealing with a multi network setup or not.
1385
	 * The reason we are type casting this is because we want to avoid the situation where
1386
	 * the result is false since when is_main_network_option return false it cases
1387
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1388
	 * database which could be set to anything as opposed to what this function returns.
1389
	 * @param  bool  $option
1390
	 *
1391
	 * @return boolean
1392
	 */
1393
	public function is_main_network_option( $option ) {
1394
		// return '1' or ''
1395
		return (string) (bool) Jetpack::is_multi_network();
1396
	}
1397
1398
	/**
1399
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1400
	 *
1401
	 * @param  string  $option
1402
	 * @return boolean
1403
	 */
1404
	public function is_multisite( $option ) {
1405
		return (string) (bool) is_multisite();
1406
	}
1407
1408
	/**
1409
	 * Implemented since there is no core is multi network function
1410
	 * Right now there is no way to tell if we which network is the dominant network on the system
1411
	 *
1412
	 * @since  3.3
1413
	 * @return boolean
1414
	 */
1415
	public static function is_multi_network() {
1416
		global  $wpdb;
1417
1418
		// if we don't have a multi site setup no need to do any more
1419
		if ( ! is_multisite() ) {
1420
			return false;
1421
		}
1422
1423
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1424
		if ( $num_sites > 1 ) {
1425
			return true;
1426
		} else {
1427
			return false;
1428
		}
1429
	}
1430
1431
	/**
1432
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1433
	 * @return null
1434
	 */
1435
	function update_jetpack_main_network_site_option() {
1436
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1437
	}
1438
	/**
1439
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1440
	 *
1441
	 */
1442
	function update_jetpack_network_settings() {
1443
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1444
		// Only sync this info for the main network site.
1445
	}
1446
1447
	/**
1448
	 * Get back if the current site is single user site.
1449
	 *
1450
	 * @return bool
1451
	 */
1452
	public static function is_single_user_site() {
1453
		global $wpdb;
1454
1455 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1456
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1457
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1458
		}
1459
		return 1 === (int) $some_users;
1460
	}
1461
1462
	/**
1463
	 * Returns true if the site has file write access false otherwise.
1464
	 * @return string ( '1' | '0' )
1465
	 **/
1466
	public static function file_system_write_access() {
1467
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1468
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1469
		}
1470
1471
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1472
1473
		$filesystem_method = get_filesystem_method();
1474
		if ( $filesystem_method === 'direct' ) {
1475
			return 1;
1476
		}
1477
1478
		ob_start();
1479
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1480
		ob_end_clean();
1481
		if ( $filesystem_credentials_are_stored ) {
1482
			return 1;
1483
		}
1484
		return 0;
1485
	}
1486
1487
	/**
1488
	 * Finds out if a site is using a version control system.
1489
	 * @return string ( '1' | '0' )
1490
	 **/
1491
	public static function is_version_controlled() {
1492
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1493
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1494
	}
1495
1496
	/**
1497
	 * Determines whether the current theme supports featured images or not.
1498
	 * @return string ( '1' | '0' )
1499
	 */
1500
	public static function featured_images_enabled() {
1501
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1502
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1503
	}
1504
1505
	/**
1506
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1507
	 *
1508
	 * @deprecated 4.7 use get_avatar_url instead.
1509
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1510
	 * @param int $size Size of the avatar image
1511
	 * @param string $default URL to a default image to use if no avatar is available
1512
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1513
	 *
1514
	 * @return array
1515
	 */
1516
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1517
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1518
		return get_avatar_url( $id_or_email, array(
1519
			'size' => $size,
1520
			'default' => $default,
1521
			'force_default' => $force_display,
1522
		) );
1523
	}
1524
1525
	/**
1526
	 * jetpack_updates is saved in the following schema:
1527
	 *
1528
	 * array (
1529
	 *      'plugins'                       => (int) Number of plugin updates available.
1530
	 *      'themes'                        => (int) Number of theme updates available.
1531
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1532
	 *      'translations'                  => (int) Number of translation updates available.
1533
	 *      'total'                         => (int) Total of all available updates.
1534
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1535
	 * )
1536
	 * @return array
1537
	 */
1538
	public static function get_updates() {
1539
		$update_data = wp_get_update_data();
1540
1541
		// Stores the individual update counts as well as the total count.
1542
		if ( isset( $update_data['counts'] ) ) {
1543
			$updates = $update_data['counts'];
1544
		}
1545
1546
		// If we need to update WordPress core, let's find the latest version number.
1547 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1548
			$cur = get_preferred_from_update_core();
1549
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1550
				$updates['wp_update_version'] = $cur->current;
1551
			}
1552
		}
1553
		return isset( $updates ) ? $updates : array();
1554
	}
1555
1556
	public static function get_update_details() {
1557
		$update_details = array(
1558
			'update_core' => get_site_transient( 'update_core' ),
1559
			'update_plugins' => get_site_transient( 'update_plugins' ),
1560
			'update_themes' => get_site_transient( 'update_themes' ),
1561
		);
1562
		return $update_details;
1563
	}
1564
1565
	public static function refresh_update_data() {
1566
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1567
1568
	}
1569
1570
	public static function refresh_theme_data() {
1571
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1572
	}
1573
1574
	/**
1575
	 * Is Jetpack active?
1576
	 */
1577
	public static function is_active() {
1578
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1579
	}
1580
1581
	/**
1582
	 * Make an API call to WordPress.com for plan status
1583
	 *
1584
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1585
	 *
1586
	 * @return bool True if plan is updated, false if no update
1587
	 */
1588
	public static function refresh_active_plan_from_wpcom() {
1589
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1590
		return Jetpack_Plan::refresh_from_wpcom();
1591
	}
1592
1593
	/**
1594
	 * Get the plan that this Jetpack site is currently using
1595
	 *
1596
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1597
	 * @return array Active Jetpack plan details.
1598
	 */
1599
	public static function get_active_plan() {
1600
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1601
		return Jetpack_Plan::get();
1602
	}
1603
1604
	/**
1605
	 * Determine whether the active plan supports a particular feature
1606
	 *
1607
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1608
	 * @return bool True if plan supports feature, false if not.
1609
	 */
1610
	public static function active_plan_supports( $feature ) {
1611
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1612
		return Jetpack_Plan::supports( $feature );
1613
	}
1614
1615
	/**
1616
	 * Is Jetpack in development (offline) mode?
1617
	 */
1618
	public static function is_development_mode() {
1619
		$development_mode = false;
1620
1621
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1622
			$development_mode = JETPACK_DEV_DEBUG;
1623
		} elseif ( $site_url = site_url() ) {
1624
			$development_mode = false === strpos( $site_url, '.' );
1625
		}
1626
1627
		/**
1628
		 * Filters Jetpack's development mode.
1629
		 *
1630
		 * @see https://jetpack.com/support/development-mode/
1631
		 *
1632
		 * @since 2.2.1
1633
		 *
1634
		 * @param bool $development_mode Is Jetpack's development mode active.
1635
		 */
1636
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1637
		return $development_mode;
1638
	}
1639
1640
	/**
1641
	 * Whether the site is currently onboarding or not.
1642
	 * A site is considered as being onboarded if it currently has an onboarding token.
1643
	 *
1644
	 * @since 5.8
1645
	 *
1646
	 * @access public
1647
	 * @static
1648
	 *
1649
	 * @return bool True if the site is currently onboarding, false otherwise
1650
	 */
1651
	public static function is_onboarding() {
1652
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1653
	}
1654
1655
	/**
1656
	 * Determines reason for Jetpack development mode.
1657
	 */
1658
	public static function development_mode_trigger_text() {
1659
		if ( ! Jetpack::is_development_mode() ) {
1660
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1661
		}
1662
1663
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1664
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1665
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1666
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1667
		} else {
1668
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1669
		}
1670
1671
		return $notice;
1672
1673
	}
1674
	/**
1675
	* Get Jetpack development mode notice text and notice class.
1676
	*
1677
	* Mirrors the checks made in Jetpack::is_development_mode
1678
	*
1679
	*/
1680
	public static function show_development_mode_notice() {
1681 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1682
			$notice = sprintf(
1683
			/* translators: %s is a URL */
1684
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1685
				'https://jetpack.com/support/development-mode/'
1686
			);
1687
1688
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1689
1690
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1691
		}
1692
1693
		// Throw up a notice if using a development version and as for feedback.
1694
		if ( Jetpack::is_development_version() ) {
1695
			/* translators: %s is a URL */
1696
			$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/' );
1697
1698
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1699
		}
1700
		// Throw up a notice if using staging mode
1701
		if ( Jetpack::is_staging_site() ) {
1702
			/* translators: %s is a URL */
1703
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1704
1705
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1706
		}
1707
	}
1708
1709
	/**
1710
	 * Whether Jetpack's version maps to a public release, or a development version.
1711
	 */
1712
	public static function is_development_version() {
1713
		/**
1714
		 * Allows filtering whether this is a development version of Jetpack.
1715
		 *
1716
		 * This filter is especially useful for tests.
1717
		 *
1718
		 * @since 4.3.0
1719
		 *
1720
		 * @param bool $development_version Is this a develoment version of Jetpack?
1721
		 */
1722
		return (bool) apply_filters(
1723
			'jetpack_development_version',
1724
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1725
		);
1726
	}
1727
1728
	/**
1729
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1730
	 */
1731
	public static function is_user_connected( $user_id = false ) {
1732
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1733
		if ( ! $user_id ) {
1734
			return false;
1735
		}
1736
1737
		return (bool) Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1738
	}
1739
1740
	/**
1741
	 * Get the wpcom user data of the current|specified connected user.
1742
	 */
1743
	public static function get_connected_user_data( $user_id = null ) {
1744
		if ( ! $user_id ) {
1745
			$user_id = get_current_user_id();
1746
		}
1747
1748
		$transient_key = "jetpack_connected_user_data_$user_id";
1749
1750
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1751
			return $cached_user_data;
1752
		}
1753
1754
		Jetpack::load_xml_rpc_client();
1755
		$xml = new Jetpack_IXR_Client( array(
1756
			'user_id' => $user_id,
1757
		) );
1758
		$xml->query( 'wpcom.getUser' );
1759
		if ( ! $xml->isError() ) {
1760
			$user_data = $xml->getResponse();
1761
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1762
			return $user_data;
1763
		}
1764
1765
		return false;
1766
	}
1767
1768
	/**
1769
	 * Get the wpcom email of the current|specified connected user.
1770
	 */
1771 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1772
		if ( ! $user_id ) {
1773
			$user_id = get_current_user_id();
1774
		}
1775
		Jetpack::load_xml_rpc_client();
1776
		$xml = new Jetpack_IXR_Client( array(
1777
			'user_id' => $user_id,
1778
		) );
1779
		$xml->query( 'wpcom.getUserEmail' );
1780
		if ( ! $xml->isError() ) {
1781
			return $xml->getResponse();
1782
		}
1783
		return false;
1784
	}
1785
1786
	/**
1787
	 * Get the wpcom email of the master user.
1788
	 */
1789
	public static function get_master_user_email() {
1790
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1791
		if ( $master_user_id ) {
1792
			return self::get_connected_user_email( $master_user_id );
1793
		}
1794
		return '';
1795
	}
1796
1797
	function current_user_is_connection_owner() {
1798
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1799
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1800
	}
1801
1802
	/**
1803
	 * Gets current user IP address.
1804
	 *
1805
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1806
	 *
1807
	 * @return string                  Current user IP address.
1808
	 */
1809
	public static function current_user_ip( $check_all_headers = false ) {
1810
		if ( $check_all_headers ) {
1811
			foreach ( array(
1812
				'HTTP_CF_CONNECTING_IP',
1813
				'HTTP_CLIENT_IP',
1814
				'HTTP_X_FORWARDED_FOR',
1815
				'HTTP_X_FORWARDED',
1816
				'HTTP_X_CLUSTER_CLIENT_IP',
1817
				'HTTP_FORWARDED_FOR',
1818
				'HTTP_FORWARDED',
1819
				'HTTP_VIA',
1820
			) as $key ) {
1821
				if ( ! empty( $_SERVER[ $key ] ) ) {
1822
					return $_SERVER[ $key ];
1823
				}
1824
			}
1825
		}
1826
1827
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1828
	}
1829
1830
	/**
1831
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1832
	 */
1833
	function extra_oembed_providers() {
1834
		// Cloudup: https://dev.cloudup.com/#oembed
1835
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1836
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1837
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1838
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1839
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1840
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1841
	}
1842
1843
	/**
1844
	 * Synchronize connected user role changes
1845
	 */
1846
	function user_role_change( $user_id ) {
1847
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1848
		Jetpack_Sync_Users::user_role_change( $user_id );
1849
	}
1850
1851
	/**
1852
	 * Loads the currently active modules.
1853
	 */
1854
	public static function load_modules() {
1855
		if (
1856
			! self::is_active()
1857
			&& ! self::is_development_mode()
1858
			&& ! self::is_onboarding()
1859
			&& (
1860
				! is_multisite()
1861
				|| ! get_site_option( 'jetpack_protect_active' )
1862
			)
1863
		) {
1864
			return;
1865
		}
1866
1867
		$version = Jetpack_Options::get_option( 'version' );
1868 View Code Duplication
		if ( ! $version ) {
1869
			$version = $old_version = JETPACK__VERSION . ':' . time();
1870
			/** This action is documented in class.jetpack.php */
1871
			do_action( 'updating_jetpack_version', $version, false );
1872
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1873
		}
1874
		list( $version ) = explode( ':', $version );
1875
1876
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1877
1878
		$modules_data = array();
1879
1880
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1881
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1882
			$updated_modules = array();
1883
			foreach ( $modules as $module ) {
1884
				$modules_data[ $module ] = Jetpack::get_module( $module );
1885
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1886
					continue;
1887
				}
1888
1889
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1890
					continue;
1891
				}
1892
1893
				$updated_modules[] = $module;
1894
			}
1895
1896
			$modules = array_diff( $modules, $updated_modules );
1897
		}
1898
1899
		$is_development_mode = Jetpack::is_development_mode();
1900
1901
		foreach ( $modules as $index => $module ) {
1902
			// If we're in dev mode, disable modules requiring a connection
1903
			if ( $is_development_mode ) {
1904
				// Prime the pump if we need to
1905
				if ( empty( $modules_data[ $module ] ) ) {
1906
					$modules_data[ $module ] = Jetpack::get_module( $module );
1907
				}
1908
				// If the module requires a connection, but we're in local mode, don't include it.
1909
				if ( $modules_data[ $module ]['requires_connection'] ) {
1910
					continue;
1911
				}
1912
			}
1913
1914
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1915
				continue;
1916
			}
1917
1918
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1919
				unset( $modules[ $index ] );
1920
				self::update_active_modules( array_values( $modules ) );
1921
				continue;
1922
			}
1923
1924
			/**
1925
			 * Fires when a specific module is loaded.
1926
			 * The dynamic part of the hook, $module, is the module slug.
1927
			 *
1928
			 * @since 1.1.0
1929
			 */
1930
			do_action( 'jetpack_module_loaded_' . $module );
1931
		}
1932
1933
		/**
1934
		 * Fires when all the modules are loaded.
1935
		 *
1936
		 * @since 1.1.0
1937
		 */
1938
		do_action( 'jetpack_modules_loaded' );
1939
1940
		// 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.
1941
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1942
	}
1943
1944
	/**
1945
	 * Check if Jetpack's REST API compat file should be included
1946
	 * @action plugins_loaded
1947
	 * @return null
1948
	 */
1949
	public function check_rest_api_compat() {
1950
		/**
1951
		 * Filters the list of REST API compat files to be included.
1952
		 *
1953
		 * @since 2.2.5
1954
		 *
1955
		 * @param array $args Array of REST API compat files to include.
1956
		 */
1957
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1958
1959
		if ( function_exists( 'bbpress' ) )
1960
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1961
1962
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1963
			require_once $_jetpack_rest_api_compat_include;
1964
	}
1965
1966
	/**
1967
	 * Gets all plugins currently active in values, regardless of whether they're
1968
	 * traditionally activated or network activated.
1969
	 *
1970
	 * @todo Store the result in core's object cache maybe?
1971
	 */
1972
	public static function get_active_plugins() {
1973
		$active_plugins = (array) get_option( 'active_plugins', array() );
1974
1975
		if ( is_multisite() ) {
1976
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1977
			// whereas active_plugins stores them in the values.
1978
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1979
			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...
1980
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1981
			}
1982
		}
1983
1984
		sort( $active_plugins );
1985
1986
		return array_unique( $active_plugins );
1987
	}
1988
1989
	/**
1990
	 * Gets and parses additional plugin data to send with the heartbeat data
1991
	 *
1992
	 * @since 3.8.1
1993
	 *
1994
	 * @return array Array of plugin data
1995
	 */
1996
	public static function get_parsed_plugin_data() {
1997
		if ( ! function_exists( 'get_plugins' ) ) {
1998
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1999
		}
2000
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2001
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2002
		$active_plugins = Jetpack::get_active_plugins();
2003
2004
		$plugins = array();
2005
		foreach ( $all_plugins as $path => $plugin_data ) {
2006
			$plugins[ $path ] = array(
2007
					'is_active' => in_array( $path, $active_plugins ),
2008
					'file'      => $path,
2009
					'name'      => $plugin_data['Name'],
2010
					'version'   => $plugin_data['Version'],
2011
					'author'    => $plugin_data['Author'],
2012
			);
2013
		}
2014
2015
		return $plugins;
2016
	}
2017
2018
	/**
2019
	 * Gets and parses theme data to send with the heartbeat data
2020
	 *
2021
	 * @since 3.8.1
2022
	 *
2023
	 * @return array Array of theme data
2024
	 */
2025
	public static function get_parsed_theme_data() {
2026
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2027
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2028
2029
		$themes = array();
2030
		foreach ( $all_themes as $slug => $theme_data ) {
2031
			$theme_headers = array();
2032
			foreach ( $header_keys as $header_key ) {
2033
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2034
			}
2035
2036
			$themes[ $slug ] = array(
2037
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2038
					'slug' => $slug,
2039
					'theme_root' => $theme_data->get_theme_root_uri(),
2040
					'parent' => $theme_data->parent(),
2041
					'headers' => $theme_headers
2042
			);
2043
		}
2044
2045
		return $themes;
2046
	}
2047
2048
	/**
2049
	 * Checks whether a specific plugin is active.
2050
	 *
2051
	 * We don't want to store these in a static variable, in case
2052
	 * there are switch_to_blog() calls involved.
2053
	 */
2054
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2055
		return in_array( $plugin, self::get_active_plugins() );
2056
	}
2057
2058
	/**
2059
	 * Check if Jetpack's Open Graph tags should be used.
2060
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2061
	 *
2062
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2063
	 * @action plugins_loaded
2064
	 * @return null
2065
	 */
2066
	public function check_open_graph() {
2067
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2068
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2069
		}
2070
2071
		$active_plugins = self::get_active_plugins();
2072
2073
		if ( ! empty( $active_plugins ) ) {
2074
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2075
				if ( in_array( $plugin, $active_plugins ) ) {
2076
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2077
					break;
2078
				}
2079
			}
2080
		}
2081
2082
		/**
2083
		 * Allow the addition of Open Graph Meta Tags to all pages.
2084
		 *
2085
		 * @since 2.0.3
2086
		 *
2087
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2088
		 */
2089
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2090
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2091
		}
2092
	}
2093
2094
	/**
2095
	 * Check if Jetpack's Twitter tags should be used.
2096
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2097
	 *
2098
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2099
	 * @action plugins_loaded
2100
	 * @return null
2101
	 */
2102
	public function check_twitter_tags() {
2103
2104
		$active_plugins = self::get_active_plugins();
2105
2106
		if ( ! empty( $active_plugins ) ) {
2107
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2108
				if ( in_array( $plugin, $active_plugins ) ) {
2109
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2110
					break;
2111
				}
2112
			}
2113
		}
2114
2115
		/**
2116
		 * Allow Twitter Card Meta tags to be disabled.
2117
		 *
2118
		 * @since 2.6.0
2119
		 *
2120
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2121
		 */
2122
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2123
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2124
		}
2125
	}
2126
2127
	/**
2128
	 * Allows plugins to submit security reports.
2129
 	 *
2130
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2131
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2132
	 * @param array   $args         See definitions above
2133
	 */
2134
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2135
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2136
	}
2137
2138
/* Jetpack Options API */
2139
2140
	public static function get_option_names( $type = 'compact' ) {
2141
		return Jetpack_Options::get_option_names( $type );
2142
	}
2143
2144
	/**
2145
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2146
 	 *
2147
	 * @param string $name    Option name
2148
	 * @param mixed  $default (optional)
2149
	 */
2150
	public static function get_option( $name, $default = false ) {
2151
		return Jetpack_Options::get_option( $name, $default );
2152
	}
2153
2154
	/**
2155
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2156
 	 *
2157
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2158
	 * @param string $name  Option name
2159
	 * @param mixed  $value Option value
2160
	 */
2161
	public static function update_option( $name, $value ) {
2162
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2163
		return Jetpack_Options::update_option( $name, $value );
2164
	}
2165
2166
	/**
2167
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2168
 	 *
2169
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2170
	 * @param array $array array( option name => option value, ... )
2171
	 */
2172
	public static function update_options( $array ) {
2173
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2174
		return Jetpack_Options::update_options( $array );
2175
	}
2176
2177
	/**
2178
	 * Deletes the given option.  May be passed multiple option names as an array.
2179
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2180
	 *
2181
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2182
	 * @param string|array $names
2183
	 */
2184
	public static function delete_option( $names ) {
2185
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2186
		return Jetpack_Options::delete_option( $names );
2187
	}
2188
2189
	/**
2190
	 * Enters a user token into the user_tokens option
2191
	 *
2192
	 * @param int $user_id
2193
	 * @param string $token
2194
	 * return bool
2195
	 */
2196
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2197
		// not designed for concurrent updates
2198
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2199
		if ( ! is_array( $user_tokens ) )
2200
			$user_tokens = array();
2201
		$user_tokens[$user_id] = $token;
2202
		if ( $is_master_user ) {
2203
			$master_user = $user_id;
2204
			$options     = compact( 'user_tokens', 'master_user' );
2205
		} else {
2206
			$options = compact( 'user_tokens' );
2207
		}
2208
		return Jetpack_Options::update_options( $options );
2209
	}
2210
2211
	/**
2212
	 * Returns an array of all PHP files in the specified absolute path.
2213
	 * Equivalent to glob( "$absolute_path/*.php" ).
2214
	 *
2215
	 * @param string $absolute_path The absolute path of the directory to search.
2216
	 * @return array Array of absolute paths to the PHP files.
2217
	 */
2218
	public static function glob_php( $absolute_path ) {
2219
		if ( function_exists( 'glob' ) ) {
2220
			return glob( "$absolute_path/*.php" );
2221
		}
2222
2223
		$absolute_path = untrailingslashit( $absolute_path );
2224
		$files = array();
2225
		if ( ! $dir = @opendir( $absolute_path ) ) {
2226
			return $files;
2227
		}
2228
2229
		while ( false !== $file = readdir( $dir ) ) {
2230
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2231
				continue;
2232
			}
2233
2234
			$file = "$absolute_path/$file";
2235
2236
			if ( ! is_file( $file ) ) {
2237
				continue;
2238
			}
2239
2240
			$files[] = $file;
2241
		}
2242
2243
		closedir( $dir );
2244
2245
		return $files;
2246
	}
2247
2248
	public static function activate_new_modules( $redirect = false ) {
2249
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2250
			return;
2251
		}
2252
2253
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2254 View Code Duplication
		if ( ! $jetpack_old_version ) {
2255
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2256
			/** This action is documented in class.jetpack.php */
2257
			do_action( 'updating_jetpack_version', $version, false );
2258
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2259
		}
2260
2261
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2262
2263
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2264
			return;
2265
		}
2266
2267
		$active_modules     = Jetpack::get_active_modules();
2268
		$reactivate_modules = array();
2269
		foreach ( $active_modules as $active_module ) {
2270
			$module = Jetpack::get_module( $active_module );
2271
			if ( ! isset( $module['changed'] ) ) {
2272
				continue;
2273
			}
2274
2275
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2276
				continue;
2277
			}
2278
2279
			$reactivate_modules[] = $active_module;
2280
			Jetpack::deactivate_module( $active_module );
2281
		}
2282
2283
		$new_version = JETPACK__VERSION . ':' . time();
2284
		/** This action is documented in class.jetpack.php */
2285
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2286
		Jetpack_Options::update_options(
2287
			array(
2288
				'version'     => $new_version,
2289
				'old_version' => $jetpack_old_version,
2290
			)
2291
		);
2292
2293
		Jetpack::state( 'message', 'modules_activated' );
2294
		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...
2295
2296
		if ( $redirect ) {
2297
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2298
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2299
				$page = $_GET['page'];
2300
			}
2301
2302
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2303
			exit;
2304
		}
2305
	}
2306
2307
	/**
2308
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2309
	 * Make sure to tuck away module "library" files in a sub-directory.
2310
	 */
2311
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2312
		static $modules = null;
2313
2314
		if ( ! isset( $modules ) ) {
2315
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2316
			// Use the cache if we're on the front-end and it's available...
2317
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2318
				$modules = $available_modules_option[ JETPACK__VERSION ];
2319
			} else {
2320
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2321
2322
				$modules = array();
2323
2324
				foreach ( $files as $file ) {
2325
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2326
						continue;
2327
					}
2328
2329
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2330
				}
2331
2332
				Jetpack_Options::update_option( 'available_modules', array(
2333
					JETPACK__VERSION => $modules,
2334
				) );
2335
			}
2336
		}
2337
2338
		/**
2339
		 * Filters the array of modules available to be activated.
2340
		 *
2341
		 * @since 2.4.0
2342
		 *
2343
		 * @param array $modules Array of available modules.
2344
		 * @param string $min_version Minimum version number required to use modules.
2345
		 * @param string $max_version Maximum version number required to use modules.
2346
		 */
2347
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2348
2349
		if ( ! $min_version && ! $max_version ) {
2350
			return array_keys( $mods );
2351
		}
2352
2353
		$r = array();
2354
		foreach ( $mods as $slug => $introduced ) {
2355
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2356
				continue;
2357
			}
2358
2359
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2360
				continue;
2361
			}
2362
2363
			$r[] = $slug;
2364
		}
2365
2366
		return $r;
2367
	}
2368
2369
	/**
2370
	 * Default modules loaded on activation.
2371
	 */
2372
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2373
		$return = array();
2374
2375
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2376
			$module_data = Jetpack::get_module( $module );
2377
2378
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2379
				case 'yes' :
2380
					$return[] = $module;
2381
					break;
2382
				case 'public' :
2383
					if ( Jetpack_Options::get_option( 'public' ) ) {
2384
						$return[] = $module;
2385
					}
2386
					break;
2387
				case 'no' :
2388
				default :
2389
					break;
2390
			}
2391
		}
2392
		/**
2393
		 * Filters the array of default modules.
2394
		 *
2395
		 * @since 2.5.0
2396
		 *
2397
		 * @param array $return Array of default modules.
2398
		 * @param string $min_version Minimum version number required to use modules.
2399
		 * @param string $max_version Maximum version number required to use modules.
2400
		 */
2401
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2402
	}
2403
2404
	/**
2405
	 * Checks activated modules during auto-activation to determine
2406
	 * if any of those modules are being deprecated.  If so, close
2407
	 * them out, and add any replacement modules.
2408
	 *
2409
	 * Runs at priority 99 by default.
2410
	 *
2411
	 * This is run late, so that it can still activate a module if
2412
	 * the new module is a replacement for another that the user
2413
	 * currently has active, even if something at the normal priority
2414
	 * would kibosh everything.
2415
	 *
2416
	 * @since 2.6
2417
	 * @uses jetpack_get_default_modules filter
2418
	 * @param array $modules
2419
	 * @return array
2420
	 */
2421
	function handle_deprecated_modules( $modules ) {
2422
		$deprecated_modules = array(
2423
			'debug'            => null,  // Closed out and moved to the debugger library.
2424
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2425
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2426
		);
2427
2428
		// Don't activate SSO if they never completed activating WPCC.
2429
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2430
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2431
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2432
				$deprecated_modules['wpcc'] = null;
2433
			}
2434
		}
2435
2436
		foreach ( $deprecated_modules as $module => $replacement ) {
2437
			if ( Jetpack::is_module_active( $module ) ) {
2438
				self::deactivate_module( $module );
2439
				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...
2440
					$modules[] = $replacement;
2441
				}
2442
			}
2443
		}
2444
2445
		return array_unique( $modules );
2446
	}
2447
2448
	/**
2449
	 * Checks activated plugins during auto-activation to determine
2450
	 * if any of those plugins are in the list with a corresponding module
2451
	 * that is not compatible with the plugin. The module will not be allowed
2452
	 * to auto-activate.
2453
	 *
2454
	 * @since 2.6
2455
	 * @uses jetpack_get_default_modules filter
2456
	 * @param array $modules
2457
	 * @return array
2458
	 */
2459
	function filter_default_modules( $modules ) {
2460
2461
		$active_plugins = self::get_active_plugins();
2462
2463
		if ( ! empty( $active_plugins ) ) {
2464
2465
			// For each module we'd like to auto-activate...
2466
			foreach ( $modules as $key => $module ) {
2467
				// If there are potential conflicts for it...
2468
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2469
					// For each potential conflict...
2470
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2471
						// If that conflicting plugin is active...
2472
						if ( in_array( $plugin, $active_plugins ) ) {
2473
							// Remove that item from being auto-activated.
2474
							unset( $modules[ $key ] );
2475
						}
2476
					}
2477
				}
2478
			}
2479
		}
2480
2481
		return $modules;
2482
	}
2483
2484
	/**
2485
	 * Extract a module's slug from its full path.
2486
	 */
2487
	public static function get_module_slug( $file ) {
2488
		return str_replace( '.php', '', basename( $file ) );
2489
	}
2490
2491
	/**
2492
	 * Generate a module's path from its slug.
2493
	 */
2494
	public static function get_module_path( $slug ) {
2495
		/**
2496
		 * Filters the path of a modules.
2497
		 *
2498
		 * @since 7.4.0
2499
		 *
2500
		 * @param array $return The absolute path to a module's root php file
2501
		 * @param string $slug The module slug
2502
		 */
2503
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2504
	}
2505
2506
	/**
2507
	 * Load module data from module file. Headers differ from WordPress
2508
	 * plugin headers to avoid them being identified as standalone
2509
	 * plugins on the WordPress plugins page.
2510
	 */
2511
	public static function get_module( $module ) {
2512
		$headers = array(
2513
			'name'                      => 'Module Name',
2514
			'description'               => 'Module Description',
2515
			'jumpstart_desc'            => 'Jumpstart Description',
2516
			'sort'                      => 'Sort Order',
2517
			'recommendation_order'      => 'Recommendation Order',
2518
			'introduced'                => 'First Introduced',
2519
			'changed'                   => 'Major Changes In',
2520
			'deactivate'                => 'Deactivate',
2521
			'free'                      => 'Free',
2522
			'requires_connection'       => 'Requires Connection',
2523
			'auto_activate'             => 'Auto Activate',
2524
			'module_tags'               => 'Module Tags',
2525
			'feature'                   => 'Feature',
2526
			'additional_search_queries' => 'Additional Search Queries',
2527
			'plan_classes'              => 'Plans',
2528
		);
2529
2530
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2531
2532
		$mod = Jetpack::get_file_data( $file, $headers );
2533
		if ( empty( $mod['name'] ) ) {
2534
			return false;
2535
		}
2536
2537
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2538
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2539
		$mod['deactivate']              = empty( $mod['deactivate'] );
2540
		$mod['free']                    = empty( $mod['free'] );
2541
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2542
2543
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2544
			$mod['auto_activate'] = 'No';
2545
		} else {
2546
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2547
		}
2548
2549
		if ( $mod['module_tags'] ) {
2550
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2551
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2552
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2553
		} else {
2554
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2555
		}
2556
2557 View Code Duplication
		if ( $mod['plan_classes'] ) {
2558
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2559
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2560
		} else {
2561
			$mod['plan_classes'] = array( 'free' );
2562
		}
2563
2564 View Code Duplication
		if ( $mod['feature'] ) {
2565
			$mod['feature'] = explode( ',', $mod['feature'] );
2566
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2567
		} else {
2568
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2569
		}
2570
2571
		/**
2572
		 * Filters the feature array on a module.
2573
		 *
2574
		 * This filter allows you to control where each module is filtered: Recommended,
2575
		 * Jumpstart, and the default "Other" listing.
2576
		 *
2577
		 * @since 3.5.0
2578
		 *
2579
		 * @param array   $mod['feature'] The areas to feature this module:
2580
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2581
		 *     'Recommended' shows on the main Jetpack admin screen.
2582
		 *     'Other' should be the default if no other value is in the array.
2583
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2584
		 * @param array   $mod All the currently assembled module data.
2585
		 */
2586
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2587
2588
		/**
2589
		 * Filter the returned data about a module.
2590
		 *
2591
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2592
		 * so please be careful.
2593
		 *
2594
		 * @since 3.6.0
2595
		 *
2596
		 * @param array   $mod    The details of the requested module.
2597
		 * @param string  $module The slug of the module, e.g. sharedaddy
2598
		 * @param string  $file   The path to the module source file.
2599
		 */
2600
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2601
	}
2602
2603
	/**
2604
	 * Like core's get_file_data implementation, but caches the result.
2605
	 */
2606
	public static function get_file_data( $file, $headers ) {
2607
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2608
		$file_name = basename( $file );
2609
2610
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2611
2612
		$file_data_option = get_transient( $cache_key );
2613
2614
		if ( false === $file_data_option ) {
2615
			$file_data_option = array();
2616
		}
2617
2618
		$key           = md5( $file_name . serialize( $headers ) );
2619
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2620
2621
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2622
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2623
			return $file_data_option[ $key ];
2624
		}
2625
2626
		$data = get_file_data( $file, $headers );
2627
2628
		$file_data_option[ $key ] = $data;
2629
2630
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2631
2632
		return $data;
2633
	}
2634
2635
2636
	/**
2637
	 * Return translated module tag.
2638
	 *
2639
	 * @param string $tag Tag as it appears in each module heading.
2640
	 *
2641
	 * @return mixed
2642
	 */
2643
	public static function translate_module_tag( $tag ) {
2644
		return jetpack_get_module_i18n_tag( $tag );
2645
	}
2646
2647
	/**
2648
	 * Get i18n strings as a JSON-encoded string
2649
	 *
2650
	 * @return string The locale as JSON
2651
	 */
2652
	public static function get_i18n_data_json() {
2653
2654
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2655
		// JSON files with the file they should be included for. This is an md5
2656
		// of '_inc/build/admin.js'.
2657
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2658
2659
		$i18n_json =
2660
				   JETPACK__PLUGIN_DIR
2661
				   . 'languages/json/jetpack-'
2662
				   . get_user_locale()
2663
				   . '-'
2664
				   . $path_md5
2665
				   . '.json';
2666
2667
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2668
			$locale_data = @file_get_contents( $i18n_json );
2669
			if ( $locale_data ) {
2670
				return $locale_data;
2671
			}
2672
		}
2673
2674
		// Return valid empty Jed locale
2675
		return '{ "locale_data": { "messages": { "": {} } } }';
2676
	}
2677
2678
	/**
2679
	 * Add locale data setup to wp-i18n
2680
	 *
2681
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2682
	 *
2683
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2684
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2685
	 *
2686
	 * This method provides a safe way to request the setup multiple times but add the script at
2687
	 * most once.
2688
	 *
2689
	 * @since 6.7.0
2690
	 *
2691
	 * @return void
2692
	 */
2693
	public static function setup_wp_i18n_locale_data() {
2694
		static $script_added = false;
2695
		if ( ! $script_added ) {
2696
			$script_added = true;
2697
			wp_add_inline_script(
2698
				'wp-i18n',
2699
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2700
			);
2701
		}
2702
	}
2703
2704
	/**
2705
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2706
	 *
2707
	 * @since 3.9.2
2708
	 *
2709
	 * @param array $modules
2710
	 *
2711
	 * @return string|void
2712
	 */
2713
	public static function get_translated_modules( $modules ) {
2714
		foreach ( $modules as $index => $module ) {
2715
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2716
			if ( isset( $module['name'] ) ) {
2717
				$modules[ $index ]['name'] = $i18n_module['name'];
2718
			}
2719
			if ( isset( $module['description'] ) ) {
2720
				$modules[ $index ]['description'] = $i18n_module['description'];
2721
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2722
			}
2723
		}
2724
		return $modules;
2725
	}
2726
2727
	/**
2728
	 * Get a list of activated modules as an array of module slugs.
2729
	 */
2730
	public static function get_active_modules() {
2731
		$active = Jetpack_Options::get_option( 'active_modules' );
2732
2733
		if ( ! is_array( $active ) ) {
2734
			$active = array();
2735
		}
2736
2737
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2738
			$active[] = 'vaultpress';
2739
		} else {
2740
			$active = array_diff( $active, array( 'vaultpress' ) );
2741
		}
2742
2743
		//If protect is active on the main site of a multisite, it should be active on all sites.
2744
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2745
			$active[] = 'protect';
2746
		}
2747
2748
		/**
2749
		 * Allow filtering of the active modules.
2750
		 *
2751
		 * Gives theme and plugin developers the power to alter the modules that
2752
		 * are activated on the fly.
2753
		 *
2754
		 * @since 5.8.0
2755
		 *
2756
		 * @param array $active Array of active module slugs.
2757
		 */
2758
		$active = apply_filters( 'jetpack_active_modules', $active );
2759
2760
		return array_unique( $active );
2761
	}
2762
2763
	/**
2764
	 * Check whether or not a Jetpack module is active.
2765
	 *
2766
	 * @param string $module The slug of a Jetpack module.
2767
	 * @return bool
2768
	 *
2769
	 * @static
2770
	 */
2771
	public static function is_module_active( $module ) {
2772
		return in_array( $module, self::get_active_modules() );
2773
	}
2774
2775
	public static function is_module( $module ) {
2776
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2777
	}
2778
2779
	/**
2780
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2781
	 *
2782
	 * @param bool $catch True to start catching, False to stop.
2783
	 *
2784
	 * @static
2785
	 */
2786
	public static function catch_errors( $catch ) {
2787
		static $display_errors, $error_reporting;
2788
2789
		if ( $catch ) {
2790
			$display_errors  = @ini_set( 'display_errors', 1 );
2791
			$error_reporting = @error_reporting( E_ALL );
2792
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2793
		} else {
2794
			@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...
2795
			@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...
2796
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2797
		}
2798
	}
2799
2800
	/**
2801
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2802
	 */
2803
	public static function catch_errors_on_shutdown() {
2804
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2805
	}
2806
2807
	/**
2808
	 * Rewrite any string to make paths easier to read.
2809
	 *
2810
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2811
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2812
	 *
2813
	 * @param $string
2814
	 * @return mixed
2815
	 */
2816
	public static function alias_directories( $string ) {
2817
		// ABSPATH has a trailing slash.
2818
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2819
		// WP_CONTENT_DIR does not have a trailing slash.
2820
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2821
2822
		return $string;
2823
	}
2824
2825
	public static function activate_default_modules(
2826
		$min_version = false,
2827
		$max_version = false,
2828
		$other_modules = array(),
2829
		$redirect = true,
2830
		$send_state_messages = true
2831
	) {
2832
		$jetpack = Jetpack::init();
2833
2834
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2835
		$modules = array_merge( $other_modules, $modules );
2836
2837
		// Look for standalone plugins and disable if active.
2838
2839
		$to_deactivate = array();
2840
		foreach ( $modules as $module ) {
2841
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2842
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2843
			}
2844
		}
2845
2846
		$deactivated = array();
2847
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2848
			list( $probable_file, $probable_title ) = $deactivate_me;
2849
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2850
				$deactivated[] = $module;
2851
			}
2852
		}
2853
2854
		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...
2855
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2856
2857
			$url = add_query_arg(
2858
				array(
2859
					'action'   => 'activate_default_modules',
2860
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2861
				),
2862
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2863
			);
2864
			wp_safe_redirect( $url );
2865
			exit;
2866
		}
2867
2868
		/**
2869
		 * Fires before default modules are activated.
2870
		 *
2871
		 * @since 1.9.0
2872
		 *
2873
		 * @param string $min_version Minimum version number required to use modules.
2874
		 * @param string $max_version Maximum version number required to use modules.
2875
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2876
		 */
2877
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2878
2879
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2880
		if ( $send_state_messages ) {
2881
			Jetpack::restate();
2882
			Jetpack::catch_errors( true );
2883
		}
2884
2885
		$active = Jetpack::get_active_modules();
2886
2887
		foreach ( $modules as $module ) {
2888
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2889
				$active[] = $module;
2890
				self::update_active_modules( $active );
2891
				continue;
2892
			}
2893
2894
			if ( $send_state_messages && in_array( $module, $active ) ) {
2895
				$module_info = Jetpack::get_module( $module );
2896 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2897
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2898
					if ( $active_state = Jetpack::state( $state ) ) {
2899
						$active_state = explode( ',', $active_state );
2900
					} else {
2901
						$active_state = array();
2902
					}
2903
					$active_state[] = $module;
2904
					Jetpack::state( $state, implode( ',', $active_state ) );
2905
				}
2906
				continue;
2907
			}
2908
2909
			$file = Jetpack::get_module_path( $module );
2910
			if ( ! file_exists( $file ) ) {
2911
				continue;
2912
			}
2913
2914
			// we'll override this later if the plugin can be included without fatal error
2915
			if ( $redirect ) {
2916
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2917
			}
2918
2919
			if ( $send_state_messages ) {
2920
				Jetpack::state( 'error', 'module_activation_failed' );
2921
				Jetpack::state( 'module', $module );
2922
			}
2923
2924
			ob_start();
2925
			require_once $file;
2926
2927
			$active[] = $module;
2928
2929 View Code Duplication
			if ( $send_state_messages ) {
2930
2931
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2932
				if ( $active_state = Jetpack::state( $state ) ) {
2933
					$active_state = explode( ',', $active_state );
2934
				} else {
2935
					$active_state = array();
2936
				}
2937
				$active_state[] = $module;
2938
				Jetpack::state( $state, implode( ',', $active_state ) );
2939
			}
2940
2941
			Jetpack::update_active_modules( $active );
2942
2943
			ob_end_clean();
2944
		}
2945
2946
		if ( $send_state_messages ) {
2947
			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...
2948
			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...
2949
		}
2950
2951
		Jetpack::catch_errors( false );
2952
		/**
2953
		 * Fires when default modules are activated.
2954
		 *
2955
		 * @since 1.9.0
2956
		 *
2957
		 * @param string $min_version Minimum version number required to use modules.
2958
		 * @param string $max_version Maximum version number required to use modules.
2959
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2960
		 */
2961
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2962
	}
2963
2964
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2965
		/**
2966
		 * Fires before a module is activated.
2967
		 *
2968
		 * @since 2.6.0
2969
		 *
2970
		 * @param string $module Module slug.
2971
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2972
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2973
		 */
2974
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2975
2976
		$jetpack = Jetpack::init();
2977
2978
		if ( ! strlen( $module ) )
2979
			return false;
2980
2981
		if ( ! Jetpack::is_module( $module ) )
2982
			return false;
2983
2984
		// If it's already active, then don't do it again
2985
		$active = Jetpack::get_active_modules();
2986
		foreach ( $active as $act ) {
2987
			if ( $act == $module )
2988
				return true;
2989
		}
2990
2991
		$module_data = Jetpack::get_module( $module );
2992
2993
		if ( ! Jetpack::is_active() ) {
2994
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2995
				return false;
2996
2997
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2998
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2999
				return false;
3000
		}
3001
3002
		// Check and see if the old plugin is active
3003
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3004
			// Deactivate the old plugin
3005
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3006
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3007
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3008
				Jetpack::state( 'deactivated_plugins', $module );
3009
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3010
				exit;
3011
			}
3012
		}
3013
3014
		// Protect won't work with mis-configured IPs
3015
		if ( 'protect' === $module ) {
3016
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3017
			if ( ! jetpack_protect_get_ip() ) {
3018
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
3019
				return false;
3020
			}
3021
		}
3022
3023
		if ( ! Jetpack_Plan::supports( $module ) ) {
3024
			return false;
3025
		}
3026
3027
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3028
		Jetpack::state( 'module', $module );
3029
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3030
3031
		Jetpack::catch_errors( true );
3032
		ob_start();
3033
		require Jetpack::get_module_path( $module );
3034
		/** This action is documented in class.jetpack.php */
3035
		do_action( 'jetpack_activate_module', $module );
3036
		$active[] = $module;
3037
		Jetpack::update_active_modules( $active );
3038
3039
		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...
3040
		ob_end_clean();
3041
		Jetpack::catch_errors( false );
3042
3043
		if ( $redirect ) {
3044
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3045
		}
3046
		if ( $exit ) {
3047
			exit;
3048
		}
3049
		return true;
3050
	}
3051
3052
	function activate_module_actions( $module ) {
3053
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3054
	}
3055
3056
	public static function deactivate_module( $module ) {
3057
		/**
3058
		 * Fires when a module is deactivated.
3059
		 *
3060
		 * @since 1.9.0
3061
		 *
3062
		 * @param string $module Module slug.
3063
		 */
3064
		do_action( 'jetpack_pre_deactivate_module', $module );
3065
3066
		$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...
3067
3068
		$active = Jetpack::get_active_modules();
3069
		$new    = array_filter( array_diff( $active, (array) $module ) );
3070
3071
		return self::update_active_modules( $new );
3072
	}
3073
3074
	public static function enable_module_configurable( $module ) {
3075
		$module = Jetpack::get_module_slug( $module );
3076
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3077
	}
3078
3079
	/**
3080
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3081
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3082
	 *
3083
	 * @param string $module Module slug
3084
	 * @return string $url module configuration URL
3085
	 */
3086
	public static function module_configuration_url( $module ) {
3087
		$module = Jetpack::get_module_slug( $module );
3088
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3089
		/**
3090
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3091
		 *
3092
		 * @since 6.9.0
3093
		 *
3094
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3095
		 */
3096
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3097
3098
		return $url;
3099
	}
3100
3101
/* Installation */
3102
	public static function bail_on_activation( $message, $deactivate = true ) {
3103
?>
3104
<!doctype html>
3105
<html>
3106
<head>
3107
<meta charset="<?php bloginfo( 'charset' ); ?>">
3108
<style>
3109
* {
3110
	text-align: center;
3111
	margin: 0;
3112
	padding: 0;
3113
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3114
}
3115
p {
3116
	margin-top: 1em;
3117
	font-size: 18px;
3118
}
3119
</style>
3120
<body>
3121
<p><?php echo esc_html( $message ); ?></p>
3122
</body>
3123
</html>
3124
<?php
3125
		if ( $deactivate ) {
3126
			$plugins = get_option( 'active_plugins' );
3127
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3128
			$update  = false;
3129
			foreach ( $plugins as $i => $plugin ) {
3130
				if ( $plugin === $jetpack ) {
3131
					$plugins[$i] = false;
3132
					$update = true;
3133
				}
3134
			}
3135
3136
			if ( $update ) {
3137
				update_option( 'active_plugins', array_filter( $plugins ) );
3138
			}
3139
		}
3140
		exit;
3141
	}
3142
3143
	/**
3144
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3145
	 * @static
3146
	 */
3147
	public static function plugin_activation( $network_wide ) {
3148
		Jetpack_Options::update_option( 'activated', 1 );
3149
3150
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3151
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3152
		}
3153
3154
		if ( $network_wide )
3155
			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...
3156
3157
		// For firing one-off events (notices) immediately after activation
3158
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3159
3160
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3161
3162
		Jetpack::plugin_initialize();
3163
	}
3164
3165
	public static function get_activation_source( $referer_url ) {
3166
3167
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3168
			return array( 'wp-cli', null );
3169
		}
3170
3171
		$referer = parse_url( $referer_url );
3172
3173
		$source_type = 'unknown';
3174
		$source_query = null;
3175
3176
		if ( ! is_array( $referer ) ) {
3177
			return array( $source_type, $source_query );
3178
		}
3179
3180
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3181
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3182
3183
		if ( isset( $referer['query'] ) ) {
3184
			parse_str( $referer['query'], $query_parts );
3185
		} else {
3186
			$query_parts = array();
3187
		}
3188
3189
		if ( $plugins_path === $referer['path'] ) {
3190
			$source_type = 'list';
3191
		} elseif ( $plugins_install_path === $referer['path'] ) {
3192
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3193
			switch( $tab ) {
3194
				case 'popular':
3195
					$source_type = 'popular';
3196
					break;
3197
				case 'recommended':
3198
					$source_type = 'recommended';
3199
					break;
3200
				case 'favorites':
3201
					$source_type = 'favorites';
3202
					break;
3203
				case 'search':
3204
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3205
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3206
					break;
3207
				default:
3208
					$source_type = 'featured';
3209
			}
3210
		}
3211
3212
		return array( $source_type, $source_query );
3213
	}
3214
3215
	/**
3216
	 * Runs before bumping version numbers up to a new version
3217
	 * @param  string $version    Version:timestamp
3218
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3219
	 * @return null              [description]
3220
	 */
3221
	public static function do_version_bump( $version, $old_version ) {
3222
		if ( ! $old_version ) { // For new sites
3223
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3224
		}
3225
	}
3226
3227
	/**
3228
	 * Sets the internal version number and activation state.
3229
	 * @static
3230
	 */
3231
	public static function plugin_initialize() {
3232
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3233
			Jetpack_Options::update_option( 'activated', 2 );
3234
		}
3235
3236 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3237
			$version = $old_version = JETPACK__VERSION . ':' . time();
3238
			/** This action is documented in class.jetpack.php */
3239
			do_action( 'updating_jetpack_version', $version, false );
3240
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3241
		}
3242
3243
		Jetpack::load_modules();
3244
3245
		Jetpack_Options::delete_option( 'do_activate' );
3246
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3247
	}
3248
3249
	/**
3250
	 * Removes all connection options
3251
	 * @static
3252
	 */
3253
	public static function plugin_deactivation( ) {
3254
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3255
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3256
			Jetpack_Network::init()->deactivate();
3257
		} else {
3258
			Jetpack::disconnect( false );
3259
			//Jetpack_Heartbeat::init()->deactivate();
3260
		}
3261
	}
3262
3263
	/**
3264
	 * Disconnects from the Jetpack servers.
3265
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3266
	 * @static
3267
	 */
3268
	public static function disconnect( $update_activated_state = true ) {
3269
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3270
		Jetpack::clean_nonces( true );
3271
3272
		// If the site is in an IDC because sync is not allowed,
3273
		// let's make sure to not disconnect the production site.
3274
		if ( ! self::validate_sync_error_idc_option() ) {
3275
		    $tracking = new Tracking();
3276
			$tracking->record_user_event( 'disconnect_site', array() );
3277
			Jetpack::load_xml_rpc_client();
3278
			$xml = new Jetpack_IXR_Client();
3279
			$xml->query( 'jetpack.deregister' );
3280
		}
3281
3282
		Jetpack_Options::delete_option(
3283
			array(
3284
				'blog_token',
3285
				'user_token',
3286
				'user_tokens',
3287
				'master_user',
3288
				'time_diff',
3289
				'fallback_no_verify_ssl_certs',
3290
			)
3291
		);
3292
3293
		Jetpack_IDC::clear_all_idc_options();
3294
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3295
3296
		if ( $update_activated_state ) {
3297
			Jetpack_Options::update_option( 'activated', 4 );
3298
		}
3299
3300
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3301
			// Check then record unique disconnection if site has never been disconnected previously
3302
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3303
				$jetpack_unique_connection['disconnected'] = 1;
3304
			} else {
3305
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3306
					//track unique disconnect
3307
					$jetpack = Jetpack::init();
3308
3309
					$jetpack->stat( 'connections', 'unique-disconnect' );
3310
					$jetpack->do_stats( 'server_side' );
3311
				}
3312
				// increment number of times disconnected
3313
				$jetpack_unique_connection['disconnected'] += 1;
3314
			}
3315
3316
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3317
		}
3318
3319
		// Delete cached connected user data
3320
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3321
		delete_transient( $transient_key );
3322
3323
		// Delete all the sync related data. Since it could be taking up space.
3324
		Jetpack_Sync_Sender::get_instance()->uninstall();
3325
3326
		// Disable the Heartbeat cron
3327
		Jetpack_Heartbeat::init()->deactivate();
3328
	}
3329
3330
	/**
3331
	 * Unlinks the current user from the linked WordPress.com user
3332
	 */
3333
	public static function unlink_user( $user_id = null ) {
3334
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3335
			return false;
3336
3337
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3338
3339
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3340
			return false;
3341
3342
		if ( ! isset( $tokens[ $user_id ] ) )
3343
			return false;
3344
3345
		Jetpack::load_xml_rpc_client();
3346
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3347
		$xml->query( 'jetpack.unlink_user', $user_id );
3348
3349
		unset( $tokens[ $user_id ] );
3350
3351
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3352
3353
		/**
3354
		 * Fires after the current user has been unlinked from WordPress.com.
3355
		 *
3356
		 * @since 4.1.0
3357
		 *
3358
		 * @param int $user_id The current user's ID.
3359
		 */
3360
		do_action( 'jetpack_unlinked_user', $user_id );
3361
3362
		return true;
3363
	}
3364
3365
	/**
3366
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3367
	 */
3368
	public static function try_registration() {
3369
		// The user has agreed to the TOS at some point by now.
3370
		Jetpack_Options::update_option( 'tos_agreed', true );
3371
3372
		// Let's get some testing in beta versions and such.
3373
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3374
			// Before attempting to connect, let's make sure that the domains are viable.
3375
			$domains_to_check = array_unique( array(
3376
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3377
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3378
			) );
3379
			foreach ( $domains_to_check as $domain ) {
3380
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3379 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3381
				if ( is_wp_error( $result ) ) {
3382
					return $result;
3383
				}
3384
			}
3385
		}
3386
3387
		$result = Jetpack::register();
3388
3389
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3390
		if ( ! $result || is_wp_error( $result ) ) {
3391
			return $result;
3392
		} else {
3393
			return true;
3394
		}
3395
	}
3396
3397
	/**
3398
	 * Tracking an internal event log. Try not to put too much chaff in here.
3399
	 *
3400
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3401
	 */
3402
	public static function log( $code, $data = null ) {
3403
		// only grab the latest 200 entries
3404
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3405
3406
		// Append our event to the log
3407
		$log_entry = array(
3408
			'time'    => time(),
3409
			'user_id' => get_current_user_id(),
3410
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3411
			'code'    => $code,
3412
		);
3413
		// Don't bother storing it unless we've got some.
3414
		if ( ! is_null( $data ) ) {
3415
			$log_entry['data'] = $data;
3416
		}
3417
		$log[] = $log_entry;
3418
3419
		// Try add_option first, to make sure it's not autoloaded.
3420
		// @todo: Add an add_option method to Jetpack_Options
3421
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3422
			Jetpack_Options::update_option( 'log', $log );
3423
		}
3424
3425
		/**
3426
		 * Fires when Jetpack logs an internal event.
3427
		 *
3428
		 * @since 3.0.0
3429
		 *
3430
		 * @param array $log_entry {
3431
		 *	Array of details about the log entry.
3432
		 *
3433
		 *	@param string time Time of the event.
3434
		 *	@param int user_id ID of the user who trigerred the event.
3435
		 *	@param int blog_id Jetpack Blog ID.
3436
		 *	@param string code Unique name for the event.
3437
		 *	@param string data Data about the event.
3438
		 * }
3439
		 */
3440
		do_action( 'jetpack_log_entry', $log_entry );
3441
	}
3442
3443
	/**
3444
	 * Get the internal event log.
3445
	 *
3446
	 * @param $event (string) - only return the specific log events
3447
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3448
	 *
3449
	 * @return array of log events || WP_Error for invalid params
3450
	 */
3451
	public static function get_log( $event = false, $num = false ) {
3452
		if ( $event && ! is_string( $event ) ) {
3453
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3454
		}
3455
3456
		if ( $num && ! is_numeric( $num ) ) {
3457
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3458
		}
3459
3460
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3461
3462
		// If nothing set - act as it did before, otherwise let's start customizing the output
3463
		if ( ! $num && ! $event ) {
3464
			return $entire_log;
3465
		} else {
3466
			$entire_log = array_reverse( $entire_log );
3467
		}
3468
3469
		$custom_log_output = array();
3470
3471
		if ( $event ) {
3472
			foreach ( $entire_log as $log_event ) {
3473
				if ( $event == $log_event[ 'code' ] ) {
3474
					$custom_log_output[] = $log_event;
3475
				}
3476
			}
3477
		} else {
3478
			$custom_log_output = $entire_log;
3479
		}
3480
3481
		if ( $num ) {
3482
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3483
		}
3484
3485
		return $custom_log_output;
3486
	}
3487
3488
	/**
3489
	 * Log modification of important settings.
3490
	 */
3491
	public static function log_settings_change( $option, $old_value, $value ) {
3492
		switch( $option ) {
3493
			case 'jetpack_sync_non_public_post_stati':
3494
				self::log( $option, $value );
3495
				break;
3496
		}
3497
	}
3498
3499
	/**
3500
	 * Return stat data for WPCOM sync
3501
	 */
3502
	public static function get_stat_data( $encode = true, $extended = true ) {
3503
		$data = Jetpack_Heartbeat::generate_stats_array();
3504
3505
		if ( $extended ) {
3506
			$additional_data = self::get_additional_stat_data();
3507
			$data = array_merge( $data, $additional_data );
3508
		}
3509
3510
		if ( $encode ) {
3511
			return json_encode( $data );
3512
		}
3513
3514
		return $data;
3515
	}
3516
3517
	/**
3518
	 * Get additional stat data to sync to WPCOM
3519
	 */
3520
	public static function get_additional_stat_data( $prefix = '' ) {
3521
		$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...
3522
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3523
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3524
		$return["{$prefix}site-count"]     = 0;
3525
3526
		if ( function_exists( 'get_blog_count' ) ) {
3527
			$return["{$prefix}site-count"] = get_blog_count();
3528
		}
3529
		return $return;
3530
	}
3531
3532
	private static function get_site_user_count() {
3533
		global $wpdb;
3534
3535
		if ( function_exists( 'wp_is_large_network' ) ) {
3536
			if ( wp_is_large_network( 'users' ) ) {
3537
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3538
			}
3539
		}
3540 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3541
			// It wasn't there, so regenerate the data and save the transient
3542
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3543
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3544
		}
3545
		return $user_count;
3546
	}
3547
3548
	/* Admin Pages */
3549
3550
	function admin_init() {
3551
		// If the plugin is not connected, display a connect message.
3552
		if (
3553
			// the plugin was auto-activated and needs its candy
3554
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3555
		||
3556
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3557
			! Jetpack_Options::get_option( 'activated' )
3558
		) {
3559
			Jetpack::plugin_initialize();
3560
		}
3561
3562
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3563
			Jetpack_Connection_Banner::init();
3564
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3565
			// Upgrade: 1.1 -> 1.1.1
3566
			// Check and see if host can verify the Jetpack servers' SSL certificate
3567
			$args = array();
3568
			Jetpack_Client::_wp_remote_request(
3569
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3570
				$args,
3571
				true
3572
			);
3573
		}
3574
3575
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3576
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3577
		}
3578
3579
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3580
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3581
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3582
3583
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3584
			// Artificially throw errors in certain whitelisted cases during plugin activation
3585
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3586
		}
3587
3588
		// Add custom column in wp-admin/users.php to show whether user is linked.
3589
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3590
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3591
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3592
	}
3593
3594
	function admin_body_class( $admin_body_class = '' ) {
3595
		$classes = explode( ' ', trim( $admin_body_class ) );
3596
3597
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3598
3599
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3600
		return " $admin_body_class ";
3601
	}
3602
3603
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3604
		return $admin_body_class . ' jetpack-pagestyles ';
3605
	}
3606
3607
	/**
3608
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3609
	 * This function artificially throws errors for such cases (whitelisted).
3610
	 *
3611
	 * @param string $plugin The activated plugin.
3612
	 */
3613
	function throw_error_on_activate_plugin( $plugin ) {
3614
		$active_modules = Jetpack::get_active_modules();
3615
3616
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3617
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3618
			$throw = false;
3619
3620
			// Try and make sure it really was the stats plugin
3621
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3622
				if ( 'stats.php' == basename( $plugin ) ) {
3623
					$throw = true;
3624
				}
3625
			} else {
3626
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3627
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3628
					$throw = true;
3629
				}
3630
			}
3631
3632
			if ( $throw ) {
3633
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3634
			}
3635
		}
3636
	}
3637
3638
	function intercept_plugin_error_scrape_init() {
3639
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3640
	}
3641
3642
	function intercept_plugin_error_scrape( $action, $result ) {
3643
		if ( ! $result ) {
3644
			return;
3645
		}
3646
3647
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3648
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3649
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3650
			}
3651
		}
3652
	}
3653
3654
	function add_remote_request_handlers() {
3655
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3656
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3657
	}
3658
3659
	function remote_request_handlers() {
3660
		$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...
3661
3662
		switch ( current_filter() ) {
3663
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3664
			$response = $this->upload_handler();
3665
			break;
3666
3667
		case 'wp_ajax_nopriv_jetpack_update_file' :
3668
			$response = $this->upload_handler( true );
3669
			break;
3670
		default :
3671
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3672
			break;
3673
		}
3674
3675
		if ( ! $response ) {
3676
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3677
		}
3678
3679
		if ( is_wp_error( $response ) ) {
3680
			$status_code       = $response->get_error_data();
3681
			$error             = $response->get_error_code();
3682
			$error_description = $response->get_error_message();
3683
3684
			if ( ! is_int( $status_code ) ) {
3685
				$status_code = 400;
3686
			}
3687
3688
			status_header( $status_code );
3689
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3690
		}
3691
3692
		status_header( 200 );
3693
		if ( true === $response ) {
3694
			exit;
3695
		}
3696
3697
		die( json_encode( (object) $response ) );
3698
	}
3699
3700
	/**
3701
	 * Uploads a file gotten from the global $_FILES.
3702
	 * If `$update_media_item` is true and `post_id` is defined
3703
	 * the attachment file of the media item (gotten through of the post_id)
3704
	 * will be updated instead of add a new one.
3705
	 *
3706
	 * @param  boolean $update_media_item - update media attachment
3707
	 * @return array - An array describing the uploadind files process
3708
	 */
3709
	function upload_handler( $update_media_item = false ) {
3710
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3711
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3712
		}
3713
3714
		$user = wp_authenticate( '', '' );
3715
		if ( ! $user || is_wp_error( $user ) ) {
3716
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3717
		}
3718
3719
		wp_set_current_user( $user->ID );
3720
3721
		if ( ! current_user_can( 'upload_files' ) ) {
3722
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3723
		}
3724
3725
		if ( empty( $_FILES ) ) {
3726
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3727
		}
3728
3729
		foreach ( array_keys( $_FILES ) as $files_key ) {
3730
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3731
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3732
			}
3733
		}
3734
3735
		$media_keys = array_keys( $_FILES['media'] );
3736
3737
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3738
		if ( ! $token || is_wp_error( $token ) ) {
3739
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3740
		}
3741
3742
		$uploaded_files = array();
3743
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3744
		unset( $GLOBALS['post'] );
3745
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3746
			$file = array();
3747
			foreach ( $media_keys as $media_key ) {
3748
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3749
			}
3750
3751
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3752
3753
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3754
			if ( $hmac_provided !== $hmac_file ) {
3755
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3756
				continue;
3757
			}
3758
3759
			$_FILES['.jetpack.upload.'] = $file;
3760
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3761
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3762
				$post_id = 0;
3763
			}
3764
3765
			if ( $update_media_item ) {
3766
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3767
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3768
				}
3769
3770
				$media_array = $_FILES['media'];
3771
3772
				$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...
3773
				$file_array['type'] = $media_array['type'][0];
3774
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3775
				$file_array['error'] = $media_array['error'][0];
3776
				$file_array['size'] = $media_array['size'][0];
3777
3778
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3779
3780
				if ( is_wp_error( $edited_media_item ) ) {
3781
					return $edited_media_item;
3782
				}
3783
3784
				$response = (object) array(
3785
					'id'   => (string) $post_id,
3786
					'file' => (string) $edited_media_item->post_title,
3787
					'url'  => (string) wp_get_attachment_url( $post_id ),
3788
					'type' => (string) $edited_media_item->post_mime_type,
3789
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3790
				);
3791
3792
				return (array) array( $response );
3793
			}
3794
3795
			$attachment_id = media_handle_upload(
3796
				'.jetpack.upload.',
3797
				$post_id,
3798
				array(),
3799
				array(
3800
					'action' => 'jetpack_upload_file',
3801
				)
3802
			);
3803
3804
			if ( ! $attachment_id ) {
3805
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3806
			} elseif ( is_wp_error( $attachment_id ) ) {
3807
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3808
			} else {
3809
				$attachment = get_post( $attachment_id );
3810
				$uploaded_files[$index] = (object) array(
3811
					'id'   => (string) $attachment_id,
3812
					'file' => $attachment->post_title,
3813
					'url'  => wp_get_attachment_url( $attachment_id ),
3814
					'type' => $attachment->post_mime_type,
3815
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3816
				);
3817
				// Zip files uploads are not supported unless they are done for installation purposed
3818
				// lets delete them in case something goes wrong in this whole process
3819
				if ( 'application/zip' === $attachment->post_mime_type ) {
3820
					// Schedule a cleanup for 2 hours from now in case of failed install.
3821
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3822
				}
3823
			}
3824
		}
3825
		if ( ! is_null( $global_post ) ) {
3826
			$GLOBALS['post'] = $global_post;
3827
		}
3828
3829
		return $uploaded_files;
3830
	}
3831
3832
	/**
3833
	 * Add help to the Jetpack page
3834
	 *
3835
	 * @since Jetpack (1.2.3)
3836
	 * @return false if not the Jetpack page
3837
	 */
3838
	function admin_help() {
3839
		$current_screen = get_current_screen();
3840
3841
		// Overview
3842
		$current_screen->add_help_tab(
3843
			array(
3844
				'id'		=> 'home',
3845
				'title'		=> __( 'Home', 'jetpack' ),
3846
				'content'	=>
3847
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3848
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3849
					'<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>',
3850
			)
3851
		);
3852
3853
		// Screen Content
3854
		if ( current_user_can( 'manage_options' ) ) {
3855
			$current_screen->add_help_tab(
3856
				array(
3857
					'id'		=> 'settings',
3858
					'title'		=> __( 'Settings', 'jetpack' ),
3859
					'content'	=>
3860
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3861
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3862
						'<ol>' .
3863
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3864
							'<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>' .
3865
						'</ol>' .
3866
						'<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>'
3867
				)
3868
			);
3869
		}
3870
3871
		// Help Sidebar
3872
		$current_screen->set_help_sidebar(
3873
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3874
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3875
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3876
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3877
		);
3878
	}
3879
3880
	function admin_menu_css() {
3881
		wp_enqueue_style( 'jetpack-icons' );
3882
	}
3883
3884
	function admin_menu_order() {
3885
		return true;
3886
	}
3887
3888 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3889
		$jp_menu_order = array();
3890
3891
		foreach ( $menu_order as $index => $item ) {
3892
			if ( $item != 'jetpack' ) {
3893
				$jp_menu_order[] = $item;
3894
			}
3895
3896
			if ( $index == 0 ) {
3897
				$jp_menu_order[] = 'jetpack';
3898
			}
3899
		}
3900
3901
		return $jp_menu_order;
3902
	}
3903
3904
	function admin_banner_styles() {
3905
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3906
3907
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3908
			wp_register_style(
3909
				'jetpack-dops-style',
3910
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3911
				array(),
3912
				JETPACK__VERSION
3913
			);
3914
		}
3915
3916
		wp_enqueue_style(
3917
			'jetpack',
3918
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3919
			array( 'jetpack-dops-style' ),
3920
			 JETPACK__VERSION . '-20121016'
3921
		);
3922
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3923
		wp_style_add_data( 'jetpack', 'suffix', $min );
3924
	}
3925
3926
	function plugin_action_links( $actions ) {
3927
3928
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3929
3930
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3931
			return array_merge(
3932
				$jetpack_home,
3933
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3934
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3935
				$actions
3936
				);
3937
			}
3938
3939
		return array_merge( $jetpack_home, $actions );
3940
	}
3941
3942
	/*
3943
	 * Registration flow:
3944
	 * 1 - ::admin_page_load() action=register
3945
	 * 2 - ::try_registration()
3946
	 * 3 - ::register()
3947
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3948
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3949
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3950
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3951
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3952
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3953
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3954
	 *       jetpack_id, jetpack_secret, jetpack_public
3955
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3956
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3957
	 * 5 - user logs in with WP.com account
3958
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3959
	 *		- Jetpack_Client_Server::authorize()
3960
	 *		- Jetpack_Client_Server::get_token()
3961
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3962
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3963
	 *			- which responds with access_token, token_type, scope
3964
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3965
	 *		- Jetpack::activate_default_modules()
3966
	 *     		- Deactivates deprecated plugins
3967
	 *     		- Activates all default modules
3968
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3969
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3970
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3971
	 *     Done!
3972
	 */
3973
3974
	/**
3975
	 * Handles the page load events for the Jetpack admin page
3976
	 */
3977
	function admin_page_load() {
3978
		$error = false;
3979
3980
		// Make sure we have the right body class to hook stylings for subpages off of.
3981
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3982
3983
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3984
			// Should only be used in intermediate redirects to preserve state across redirects
3985
			Jetpack::restate();
3986
		}
3987
3988
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3989
			// @todo: Add validation against a known whitelist
3990
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3991
			// User clicked in the iframe to link their accounts
3992
			if ( ! Jetpack::is_user_connected() ) {
3993
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3994
3995
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3996
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3997
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3998
3999
				if ( isset( $_GET['notes_iframe'] ) )
4000
					$connect_url .= '&notes_iframe';
4001
				wp_redirect( $connect_url );
4002
				exit;
4003
			} else {
4004
				if ( ! isset( $_GET['calypso_env'] ) ) {
4005
					Jetpack::state( 'message', 'already_authorized' );
4006
					wp_safe_redirect( Jetpack::admin_url() );
4007
					exit;
4008
				} else {
4009
					$connect_url = $this->build_connect_url( true, false, $from );
4010
					$connect_url .= '&already_authorized=true';
4011
					wp_redirect( $connect_url );
4012
					exit;
4013
				}
4014
			}
4015
		}
4016
4017
4018
		if ( isset( $_GET['action'] ) ) {
4019
			switch ( $_GET['action'] ) {
4020
			case 'authorize':
4021
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4022
					Jetpack::state( 'message', 'already_authorized' );
4023
					wp_safe_redirect( Jetpack::admin_url() );
4024
					exit;
4025
				}
4026
				Jetpack::log( 'authorize' );
4027
				$client_server = new Jetpack_Client_Server;
4028
				$client_server->client_authorize();
4029
				exit;
4030
			case 'register' :
4031
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4032
					$error = 'cheatin';
4033
					break;
4034
				}
4035
				check_admin_referer( 'jetpack-register' );
4036
				Jetpack::log( 'register' );
4037
				Jetpack::maybe_set_version_option();
4038
				$registered = Jetpack::try_registration();
4039
				if ( is_wp_error( $registered ) ) {
4040
					$error = $registered->get_error_code();
4041
					Jetpack::state( 'error', $error );
4042
					Jetpack::state( 'error', $registered->get_error_message() );
4043
					$this->tracking->record_user_event( 'jpc_register_fail', array(
4044
						'error_code' => $error,
4045
						'error_message' => $registered->get_error_message()
4046
					) );
4047
					break;
4048
				}
4049
4050
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4051
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4052
4053
				$this->tracking->record_user_event( 'jpc_register_success', array(
4054
					'from' => $from
4055
				) );
4056
4057
				$url = $this->build_connect_url( true, $redirect, $from );
4058
4059
				if ( ! empty( $_GET['onboarding'] ) ) {
4060
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4061
				}
4062
4063
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4064
					$url = add_query_arg( 'auth_approved', 'true', $url );
4065
				}
4066
4067
				wp_redirect( $url );
4068
				exit;
4069
			case 'activate' :
4070
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4071
					$error = 'cheatin';
4072
					break;
4073
				}
4074
4075
				$module = stripslashes( $_GET['module'] );
4076
				check_admin_referer( "jetpack_activate-$module" );
4077
				Jetpack::log( 'activate', $module );
4078
				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...
4079
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4080
				}
4081
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4082
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4083
				exit;
4084
			case 'activate_default_modules' :
4085
				check_admin_referer( 'activate_default_modules' );
4086
				Jetpack::log( 'activate_default_modules' );
4087
				Jetpack::restate();
4088
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4089
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4090
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4091
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4092
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4093
				exit;
4094
			case 'disconnect' :
4095
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4096
					$error = 'cheatin';
4097
					break;
4098
				}
4099
4100
				check_admin_referer( 'jetpack-disconnect' );
4101
				Jetpack::log( 'disconnect' );
4102
				Jetpack::disconnect();
4103
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4104
				exit;
4105
			case 'reconnect' :
4106
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4107
					$error = 'cheatin';
4108
					break;
4109
				}
4110
4111
				check_admin_referer( 'jetpack-reconnect' );
4112
				Jetpack::log( 'reconnect' );
4113
				$this->disconnect();
4114
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4115
				exit;
4116 View Code Duplication
			case 'deactivate' :
4117
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4118
					$error = 'cheatin';
4119
					break;
4120
				}
4121
4122
				$modules = stripslashes( $_GET['module'] );
4123
				check_admin_referer( "jetpack_deactivate-$modules" );
4124
				foreach ( explode( ',', $modules ) as $module ) {
4125
					Jetpack::log( 'deactivate', $module );
4126
					Jetpack::deactivate_module( $module );
4127
					Jetpack::state( 'message', 'module_deactivated' );
4128
				}
4129
				Jetpack::state( 'module', $modules );
4130
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4131
				exit;
4132
			case 'unlink' :
4133
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4134
				check_admin_referer( 'jetpack-unlink' );
4135
				Jetpack::log( 'unlink' );
4136
				$this->unlink_user();
4137
				Jetpack::state( 'message', 'unlinked' );
4138
				if ( 'sub-unlink' == $redirect ) {
4139
					wp_safe_redirect( admin_url() );
4140
				} else {
4141
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4142
				}
4143
				exit;
4144
			case 'onboard' :
4145
				if ( ! current_user_can( 'manage_options' ) ) {
4146
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4147
				} else {
4148
					Jetpack::create_onboarding_token();
4149
					$url = $this->build_connect_url( true );
4150
4151
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4152
						$url = add_query_arg( 'onboarding', $token, $url );
4153
					}
4154
4155
					$calypso_env = $this->get_calypso_env();
4156
					if ( ! empty( $calypso_env ) ) {
4157
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4158
					}
4159
4160
					wp_redirect( $url );
4161
					exit;
4162
				}
4163
				exit;
4164
			default:
4165
				/**
4166
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4167
				 *
4168
				 * @since 2.6.0
4169
				 *
4170
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4171
				 */
4172
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4173
			}
4174
		}
4175
4176
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4177
			self::activate_new_modules( true );
4178
		}
4179
4180
		$message_code = Jetpack::state( 'message' );
4181
		if ( Jetpack::state( 'optin-manage' ) ) {
4182
			$activated_manage = $message_code;
4183
			$message_code = 'jetpack-manage';
4184
		}
4185
4186
		switch ( $message_code ) {
4187
		case 'jetpack-manage':
4188
			$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>';
4189
			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...
4190
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4191
			}
4192
			break;
4193
4194
		}
4195
4196
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4197
4198
		if ( ! empty( $deactivated_plugins ) ) {
4199
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4200
			$deactivated_titles  = array();
4201
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4202
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4203
					continue;
4204
				}
4205
4206
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4207
			}
4208
4209
			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...
4210
				if ( $this->message ) {
4211
					$this->message .= "<br /><br />\n";
4212
				}
4213
4214
				$this->message .= wp_sprintf(
4215
					_n(
4216
						'Jetpack contains the most recent version of the old %l plugin.',
4217
						'Jetpack contains the most recent versions of the old %l plugins.',
4218
						count( $deactivated_titles ),
4219
						'jetpack'
4220
					),
4221
					$deactivated_titles
4222
				);
4223
4224
				$this->message .= "<br />\n";
4225
4226
				$this->message .= _n(
4227
					'The old version has been deactivated and can be removed from your site.',
4228
					'The old versions have been deactivated and can be removed from your site.',
4229
					count( $deactivated_titles ),
4230
					'jetpack'
4231
				);
4232
			}
4233
		}
4234
4235
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4236
4237
		if ( $this->message || $this->error || $this->privacy_checks ) {
4238
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4239
		}
4240
4241
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4242
	}
4243
4244
	function admin_notices() {
4245
4246
		if ( $this->error ) {
4247
?>
4248
<div id="message" class="jetpack-message jetpack-err">
4249
	<div class="squeezer">
4250
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4251
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4252
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4253
<?php	endif; ?>
4254
	</div>
4255
</div>
4256
<?php
4257
		}
4258
4259
		if ( $this->message ) {
4260
?>
4261
<div id="message" class="jetpack-message">
4262
	<div class="squeezer">
4263
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4264
	</div>
4265
</div>
4266
<?php
4267
		}
4268
4269
		if ( $this->privacy_checks ) :
4270
			$module_names = $module_slugs = array();
4271
4272
			$privacy_checks = explode( ',', $this->privacy_checks );
4273
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4274
			foreach ( $privacy_checks as $module_slug ) {
4275
				$module = Jetpack::get_module( $module_slug );
4276
				if ( ! $module ) {
4277
					continue;
4278
				}
4279
4280
				$module_slugs[] = $module_slug;
4281
				$module_names[] = "<strong>{$module['name']}</strong>";
4282
			}
4283
4284
			$module_slugs = join( ',', $module_slugs );
4285
?>
4286
<div id="message" class="jetpack-message jetpack-err">
4287
	<div class="squeezer">
4288
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4289
		<p><?php
4290
			echo wp_kses(
4291
				wptexturize(
4292
					wp_sprintf(
4293
						_nx(
4294
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4295
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4296
							count( $privacy_checks ),
4297
							'%l = list of Jetpack module/feature names',
4298
							'jetpack'
4299
						),
4300
						$module_names
4301
					)
4302
				),
4303
				array( 'strong' => true )
4304
			);
4305
4306
			echo "\n<br />\n";
4307
4308
			echo wp_kses(
4309
				sprintf(
4310
					_nx(
4311
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4312
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4313
						count( $privacy_checks ),
4314
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4315
						'jetpack'
4316
					),
4317
					wp_nonce_url(
4318
						Jetpack::admin_url(
4319
							array(
4320
								'page'   => 'jetpack',
4321
								'action' => 'deactivate',
4322
								'module' => urlencode( $module_slugs ),
4323
							)
4324
						),
4325
						"jetpack_deactivate-$module_slugs"
4326
					),
4327
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4328
				),
4329
				array( 'a' => array( 'href' => true, 'title' => true ) )
4330
			);
4331
		?></p>
4332
	</div>
4333
</div>
4334
<?php endif;
4335
	}
4336
4337
	/**
4338
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4339
	 */
4340
	function stat( $group, $detail ) {
4341
		if ( ! isset( $this->stats[ $group ] ) )
4342
			$this->stats[ $group ] = array();
4343
		$this->stats[ $group ][] = $detail;
4344
	}
4345
4346
	/**
4347
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4348
	 */
4349
	function do_stats( $method = '' ) {
4350
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4351
			foreach ( $this->stats as $group => $stats ) {
4352
				if ( is_array( $stats ) && count( $stats ) ) {
4353
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4354
					if ( 'server_side' === $method ) {
4355
						self::do_server_side_stat( $args );
4356
					} else {
4357
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4358
					}
4359
				}
4360
				unset( $this->stats[ $group ] );
4361
			}
4362
		}
4363
	}
4364
4365
	/**
4366
	 * Runs stats code for a one-off, server-side.
4367
	 *
4368
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4369
	 *
4370
	 * @return bool If it worked.
4371
	 */
4372
	static function do_server_side_stat( $args ) {
4373
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4374
		if ( is_wp_error( $response ) )
4375
			return false;
4376
4377
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4378
			return false;
4379
4380
		return true;
4381
	}
4382
4383
	/**
4384
	 * Builds the stats url.
4385
	 *
4386
	 * @param $args array|string The arguments to append to the URL.
4387
	 *
4388
	 * @return string The URL to be pinged.
4389
	 */
4390
	static function build_stats_url( $args ) {
4391
		$defaults = array(
4392
			'v'    => 'wpcom2',
4393
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4394
		);
4395
		$args     = wp_parse_args( $args, $defaults );
4396
		/**
4397
		 * Filter the URL used as the Stats tracking pixel.
4398
		 *
4399
		 * @since 2.3.2
4400
		 *
4401
		 * @param string $url Base URL used as the Stats tracking pixel.
4402
		 */
4403
		$base_url = apply_filters(
4404
			'jetpack_stats_base_url',
4405
			'https://pixel.wp.com/g.gif'
4406
		);
4407
		$url      = add_query_arg( $args, $base_url );
4408
		return $url;
4409
	}
4410
4411
	static function translate_current_user_to_role() {
4412
		foreach ( self::$capability_translations as $role => $cap ) {
4413
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4414
				return $role;
4415
			}
4416
		}
4417
4418
		return false;
4419
	}
4420
4421
	static function translate_user_to_role( $user ) {
4422
		foreach ( self::$capability_translations as $role => $cap ) {
4423
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4424
				return $role;
4425
			}
4426
		}
4427
4428
		return false;
4429
    }
4430
4431
	static function translate_role_to_cap( $role ) {
4432
		if ( ! isset( self::$capability_translations[$role] ) ) {
4433
			return false;
4434
		}
4435
4436
		return self::$capability_translations[$role];
4437
	}
4438
4439
	static function sign_role( $role, $user_id = null ) {
4440
		if ( empty( $user_id ) ) {
4441
			$user_id = (int) get_current_user_id();
4442
		}
4443
4444
		if ( ! $user_id  ) {
4445
			return false;
4446
		}
4447
4448
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4449
		if ( ! $token || is_wp_error( $token ) ) {
4450
			return false;
4451
		}
4452
4453
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4454
	}
4455
4456
4457
	/**
4458
	 * Builds a URL to the Jetpack connection auth page
4459
	 *
4460
	 * @since 3.9.5
4461
	 *
4462
	 * @param bool $raw If true, URL will not be escaped.
4463
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4464
	 *                              If string, will be a custom redirect.
4465
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4466
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4467
	 *
4468
	 * @return string Connect URL
4469
	 */
4470
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4471
		$site_id = Jetpack_Options::get_option( 'id' );
4472
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4473
4474
		if ( $register || ! $blog_token || ! $site_id ) {
4475
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4476
4477
			if ( ! empty( $redirect ) ) {
4478
				$url = add_query_arg(
4479
					'redirect',
4480
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4481
					$url
4482
				);
4483
			}
4484
4485
			if( is_network_admin() ) {
4486
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4487
			}
4488
		} else {
4489
4490
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4491
			// because otherwise this logic can get us in to a loop.
4492
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4493
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4494
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4495
4496
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4497
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4498
					'1.1'
4499
				);
4500
4501
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4502
4503
					// Generating a register URL instead to refresh the existing token
4504
					return $this->build_connect_url( $raw, $redirect, $from, true );
4505
				}
4506
			}
4507
4508
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4509
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4510
			}
4511
4512
			$role = self::translate_current_user_to_role();
4513
			$signed_role = self::sign_role( $role );
4514
4515
			$user = wp_get_current_user();
4516
4517
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4518
			$redirect = $redirect
4519
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4520
				: $jetpack_admin_page;
4521
4522
			if( isset( $_REQUEST['is_multisite'] ) ) {
4523
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4524
			}
4525
4526
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4527
4528
			/**
4529
			 * Filter the type of authorization.
4530
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4531
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4532
			 *
4533
			 * @since 4.3.3
4534
			 *
4535
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4536
			 */
4537
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4538
4539
4540
			$tracks = new Tracking();
4541
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4542
4543
			$args = urlencode_deep(
4544
				array(
4545
					'response_type' => 'code',
4546
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4547
					'redirect_uri'  => add_query_arg(
4548
						array(
4549
							'action'   => 'authorize',
4550
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4551
							'redirect' => urlencode( $redirect ),
4552
						),
4553
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4554
					),
4555
					'state'         => $user->ID,
4556
					'scope'         => $signed_role,
4557
					'user_email'    => $user->user_email,
4558
					'user_login'    => $user->user_login,
4559
					'is_active'     => Jetpack::is_active(),
4560
					'jp_version'    => JETPACK__VERSION,
4561
					'auth_type'     => $auth_type,
4562
					'secret'        => $secrets['secret_1'],
4563
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4564
					'blogname'      => get_option( 'blogname' ),
4565
					'site_url'      => site_url(),
4566
					'home_url'      => home_url(),
4567
					'site_icon'     => get_site_icon_url(),
4568
					'site_lang'     => get_locale(),
4569
					'_ui'           => $tracks_identity['_ui'],
4570
					'_ut'           => $tracks_identity['_ut'],
4571
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4572
				)
4573
			);
4574
4575
			self::apply_activation_source_to_args( $args );
4576
4577
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4578
		}
4579
4580
		if ( $from ) {
4581
			$url = add_query_arg( 'from', $from, $url );
4582
		}
4583
4584
		// Ensure that class to get the affiliate code is loaded
4585
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4586
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4587
		}
4588
		// Get affiliate code and add it to the URL
4589
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4590
4591
		$calypso_env = $this->get_calypso_env();
4592
4593
		if ( ! empty( $calypso_env ) ) {
4594
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4595
		}
4596
4597
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4598
	}
4599
4600
	/**
4601
	 * Get our assumed site creation date.
4602
	 * Calculated based on the earlier date of either:
4603
	 * - Earliest admin user registration date.
4604
	 * - Earliest date of post of any post type.
4605
	 *
4606
	 * @since 7.2.0
4607
	 *
4608
	 * @return string Assumed site creation date and time.
4609
	 */
4610
	public static function get_assumed_site_creation_date() {
4611
		$earliest_registered_users = get_users( array(
4612
			'role'    => 'administrator',
4613
			'orderby' => 'user_registered',
4614
			'order'   => 'ASC',
4615
			'fields'  => array( 'user_registered' ),
4616
			'number'  => 1,
4617
		) );
4618
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4619
4620
		$earliest_posts = get_posts( array(
4621
			'posts_per_page' => 1,
4622
			'post_type'      => 'any',
4623
			'post_status'    => 'any',
4624
			'orderby'        => 'date',
4625
			'order'          => 'ASC',
4626
		) );
4627
4628
		// If there are no posts at all, we'll count only on user registration date.
4629
		if ( $earliest_posts ) {
4630
			$earliest_post_date = $earliest_posts[0]->post_date;
4631
		} else {
4632
			$earliest_post_date = PHP_INT_MAX;
4633
		}
4634
4635
		return min( $earliest_registration_date, $earliest_post_date );
4636
	}
4637
4638
	public static function apply_activation_source_to_args( &$args ) {
4639
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4640
4641
		if ( $activation_source_name ) {
4642
			$args['_as'] = urlencode( $activation_source_name );
4643
		}
4644
4645
		if ( $activation_source_keyword ) {
4646
			$args['_ak'] = urlencode( $activation_source_keyword );
4647
		}
4648
	}
4649
4650
	function build_reconnect_url( $raw = false ) {
4651
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4652
		return $raw ? $url : esc_url( $url );
4653
	}
4654
4655
	public static function admin_url( $args = null ) {
4656
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4657
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4658
		return $url;
4659
	}
4660
4661
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4662
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4663
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4664
	}
4665
4666
	function dismiss_jetpack_notice() {
4667
4668
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4669
			return;
4670
		}
4671
4672
		switch( $_GET['jetpack-notice'] ) {
4673
			case 'dismiss':
4674
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4675
4676
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4677
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4678
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4679
				}
4680
				break;
4681
			case 'jetpack-protect-multisite-opt-out':
4682
4683
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4684
					// Don't show the banner again
4685
4686
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4687
					// redirect back to the page that had the notice
4688
					if ( wp_get_referer() ) {
4689
						wp_safe_redirect( wp_get_referer() );
4690
					} else {
4691
						// Take me to Jetpack
4692
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4693
					}
4694
				}
4695
				break;
4696
		}
4697
	}
4698
4699
	public static function sort_modules( $a, $b ) {
4700
		if ( $a['sort'] == $b['sort'] )
4701
			return 0;
4702
4703
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4704
	}
4705
4706
	function ajax_recheck_ssl() {
4707
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4708
		$result = Jetpack::permit_ssl( true );
4709
		wp_send_json( array(
4710
			'enabled' => $result,
4711
			'message' => get_transient( 'jetpack_https_test_message' )
4712
		) );
4713
	}
4714
4715
/* Client API */
4716
4717
	/**
4718
	 * Returns the requested Jetpack API URL
4719
	 *
4720
	 * @return string
4721
	 */
4722
	public static function api_url( $relative_url ) {
4723
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4724
	}
4725
4726
	/**
4727
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4728
	 */
4729
	public static function fix_url_for_bad_hosts( $url ) {
4730
		if ( 0 !== strpos( $url, 'https://' ) ) {
4731
			return $url;
4732
		}
4733
4734
		switch ( JETPACK_CLIENT__HTTPS ) {
4735
			case 'ALWAYS' :
4736
				return $url;
4737
			case 'NEVER' :
4738
				return set_url_scheme( $url, 'http' );
4739
			// default : case 'AUTO' :
4740
		}
4741
4742
		// we now return the unmodified SSL URL by default, as a security precaution
4743
		return $url;
4744
	}
4745
4746
	/**
4747
	 * Create a random secret for validating onboarding payload
4748
	 *
4749
	 * @return string Secret token
4750
	 */
4751
	public static function create_onboarding_token() {
4752
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4753
			$token = wp_generate_password( 32, false );
4754
			Jetpack_Options::update_option( 'onboarding', $token );
4755
		}
4756
4757
		return $token;
4758
	}
4759
4760
	/**
4761
	 * Remove the onboarding token
4762
	 *
4763
	 * @return bool True on success, false on failure
4764
	 */
4765
	public static function invalidate_onboarding_token() {
4766
		return Jetpack_Options::delete_option( 'onboarding' );
4767
	}
4768
4769
	/**
4770
	 * Validate an onboarding token for a specific action
4771
	 *
4772
	 * @return boolean True if token/action pair is accepted, false if not
4773
	 */
4774
	public static function validate_onboarding_token_action( $token, $action ) {
4775
		// Compare tokens, bail if tokens do not match
4776
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4777
			return false;
4778
		}
4779
4780
		// List of valid actions we can take
4781
		$valid_actions = array(
4782
			'/jetpack/v4/settings',
4783
		);
4784
4785
		// Whitelist the action
4786
		if ( ! in_array( $action, $valid_actions ) ) {
4787
			return false;
4788
		}
4789
4790
		return true;
4791
	}
4792
4793
	/**
4794
	 * Checks to see if the URL is using SSL to connect with Jetpack
4795
	 *
4796
	 * @since 2.3.3
4797
	 * @return boolean
4798
	 */
4799
	public static function permit_ssl( $force_recheck = false ) {
4800
		// Do some fancy tests to see if ssl is being supported
4801
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4802
			$message = '';
4803
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4804
				$ssl = 0;
4805
			} else {
4806
				switch ( JETPACK_CLIENT__HTTPS ) {
4807
					case 'NEVER':
4808
						$ssl = 0;
4809
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4810
						break;
4811
					case 'ALWAYS':
4812
					case 'AUTO':
4813
					default:
4814
						$ssl = 1;
4815
						break;
4816
				}
4817
4818
				// If it's not 'NEVER', test to see
4819
				if ( $ssl ) {
4820
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4821
						$ssl = 0;
4822
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4823
					} else {
4824
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4825
						if ( is_wp_error( $response ) ) {
4826
							$ssl = 0;
4827
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4828
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4829
							$ssl = 0;
4830
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4831
						}
4832
					}
4833
				}
4834
			}
4835
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4836
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4837
		}
4838
4839
		return (bool) $ssl;
4840
	}
4841
4842
	/*
4843
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4844
	 */
4845
	public function alert_auto_ssl_fail() {
4846
		if ( ! current_user_can( 'manage_options' ) )
4847
			return;
4848
4849
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4850
		?>
4851
4852
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4853
			<div class="jp-banner__content">
4854
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4855
				<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>
4856
				<p>
4857
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4858
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4859
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4860
				</p>
4861
				<p>
4862
					<?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' ),
4863
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4864
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4865
				</p>
4866
			</div>
4867
		</div>
4868
		<style>
4869
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4870
		</style>
4871
		<script type="text/javascript">
4872
			jQuery( document ).ready( function( $ ) {
4873
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4874
					var $this = $( this );
4875
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4876
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4877
					e.preventDefault();
4878
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4879
					$.post( ajaxurl, data )
4880
					  .done( function( response ) {
4881
					  	if ( response.enabled ) {
4882
					  		$( '#jetpack-ssl-warning' ).hide();
4883
					  	} else {
4884
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4885
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4886
					  	}
4887
					  }.bind( $this ) );
4888
				} );
4889
			} );
4890
		</script>
4891
4892
		<?php
4893
	}
4894
4895
	/**
4896
	 * Returns the Jetpack XML-RPC API
4897
	 *
4898
	 * @return string
4899
	 */
4900
	public static function xmlrpc_api_url() {
4901
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4902
		return untrailingslashit( $base ) . '/xmlrpc.php';
4903
	}
4904
4905
	public static function connection() {
4906
		return self::init()->connection_manager;
4907
	}
4908
4909
	/**
4910
	 * Creates two secret tokens and the end of life timestamp for them.
4911
	 *
4912
	 * Note these tokens are unique per call, NOT static per site for connecting.
4913
	 *
4914
	 * @since 2.6
4915
	 * @return array
4916
	 */
4917
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4918
		if ( false === $user_id ) {
4919
			$user_id = get_current_user_id();
4920
		}
4921
4922
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4923
	}
4924
4925
	public static function get_secrets( $action, $user_id ) {
4926
		$secrets = self::connection()->get_secrets( $action, $user_id );
4927
4928
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4929
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
4930
		}
4931
4932
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4933
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
4934
		}
4935
4936
		return $secrets;
4937
	}
4938
4939
	/**
4940
	 * @deprecated 7.5 Use Connection_Manager instead.
4941
	 *
4942
	 * @param $action
4943
	 * @param $user_id
4944
	 */
4945
	public static function delete_secrets( $action, $user_id ) {
4946
		return self::connection()->delete_secrets( $action, $user_id );
4947
	}
4948
4949
	/**
4950
	 * Builds the timeout limit for queries talking with the wpcom servers.
4951
	 *
4952
	 * Based on local php max_execution_time in php.ini
4953
	 *
4954
	 * @since 2.6
4955
	 * @return int
4956
	 * @deprecated
4957
	 **/
4958
	public function get_remote_query_timeout_limit() {
4959
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4960
		return Jetpack::get_max_execution_time();
4961
	}
4962
4963
	/**
4964
	 * Builds the timeout limit for queries talking with the wpcom servers.
4965
	 *
4966
	 * Based on local php max_execution_time in php.ini
4967
	 *
4968
	 * @since 5.4
4969
	 * @return int
4970
	 **/
4971
	public static function get_max_execution_time() {
4972
		$timeout = (int) ini_get( 'max_execution_time' );
4973
4974
		// Ensure exec time set in php.ini
4975
		if ( ! $timeout ) {
4976
			$timeout = 30;
4977
		}
4978
		return $timeout;
4979
	}
4980
4981
	/**
4982
	 * Sets a minimum request timeout, and returns the current timeout
4983
	 *
4984
	 * @since 5.4
4985
	 **/
4986
	public static function set_min_time_limit( $min_timeout ) {
4987
		$timeout = self::get_max_execution_time();
4988
		if ( $timeout < $min_timeout ) {
4989
			$timeout = $min_timeout;
4990
			set_time_limit( $timeout );
4991
		}
4992
		return $timeout;
4993
	}
4994
4995
4996
	/**
4997
	 * Takes the response from the Jetpack register new site endpoint and
4998
	 * verifies it worked properly.
4999
	 *
5000
	 * @since 2.6
5001
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5002
	 **/
5003
	public function validate_remote_register_response( $response ) {
5004
	  if ( is_wp_error( $response ) ) {
5005
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5006
		}
5007
5008
		$code   = wp_remote_retrieve_response_code( $response );
5009
		$entity = wp_remote_retrieve_body( $response );
5010
		if ( $entity )
5011
			$registration_response = json_decode( $entity );
5012
		else
5013
			$registration_response = false;
5014
5015
		$code_type = intval( $code / 100 );
5016
		if ( 5 == $code_type ) {
5017
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5018
		} elseif ( 408 == $code ) {
5019
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5020
		} elseif ( ! empty( $registration_response->error ) ) {
5021
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5022
				$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' );
5023
			} else {
5024
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5025
			}
5026
5027
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5028
		} elseif ( 200 != $code ) {
5029
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5030
		}
5031
5032
		// Jetpack ID error block
5033
		if ( empty( $registration_response->jetpack_id ) ) {
5034
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5035
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5036
			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 );
5037
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5038
			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 );
5039
		}
5040
5041
	    return $registration_response;
5042
	}
5043
	/**
5044
	 * @return bool|WP_Error
5045
	 */
5046
	public static function register() {
5047
		$tracking = new Tracking();
5048
		$tracking->record_user_event( 'jpc_register_begin' );
5049
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5050
		$secrets = Jetpack::generate_secrets( 'register' );
5051
5052 View Code Duplication
		if (
5053
			empty( $secrets['secret_1'] ) ||
5054
			empty( $secrets['secret_2'] ) ||
5055
			empty( $secrets['exp'] )
5056
		) {
5057
			return new Jetpack_Error( 'missing_secrets' );
5058
		}
5059
5060
		// better to try (and fail) to set a higher timeout than this system
5061
		// supports than to have register fail for more users than it should
5062
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5063
5064
		$gmt_offset = get_option( 'gmt_offset' );
5065
		if ( ! $gmt_offset ) {
5066
			$gmt_offset = 0;
5067
		}
5068
5069
		$stats_options = get_option( 'stats_options' );
5070
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5071
5072
		$tracks = new Tracking();
5073
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5074
5075
		$args = array(
5076
			'method'  => 'POST',
5077
			'body'    => array(
5078
				'siteurl'         => site_url(),
5079
				'home'            => home_url(),
5080
				'gmt_offset'      => $gmt_offset,
5081
				'timezone_string' => (string) get_option( 'timezone_string' ),
5082
				'site_name'       => (string) get_option( 'blogname' ),
5083
				'secret_1'        => $secrets['secret_1'],
5084
				'secret_2'        => $secrets['secret_2'],
5085
				'site_lang'       => get_locale(),
5086
				'timeout'         => $timeout,
5087
				'stats_id'        => $stats_id,
5088
				'state'           => get_current_user_id(),
5089
				'_ui'             => $tracks_identity['_ui'],
5090
				'_ut'             => $tracks_identity['_ut'],
5091
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5092
				'jetpack_version' => JETPACK__VERSION
5093
			),
5094
			'headers' => array(
5095
				'Accept' => 'application/json',
5096
			),
5097
			'timeout' => $timeout,
5098
		);
5099
5100
		self::apply_activation_source_to_args( $args['body'] );
5101
5102
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5103
5104
		// Make sure the response is valid and does not contain any Jetpack errors
5105
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5106
		if ( is_wp_error( $registration_details ) ) {
5107
			return $registration_details;
5108
		} elseif ( ! $registration_details ) {
5109
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5110
		}
5111
5112 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5113
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5114
		}
5115
5116
		if ( isset( $registration_details->jetpack_public ) ) {
5117
			$jetpack_public = (int) $registration_details->jetpack_public;
5118
		} else {
5119
			$jetpack_public = false;
5120
		}
5121
5122
		Jetpack_Options::update_options(
5123
			array(
5124
				'id'         => (int)    $registration_details->jetpack_id,
5125
				'blog_token' => (string) $registration_details->jetpack_secret,
5126
				'public'     => $jetpack_public,
5127
			)
5128
		);
5129
5130
		/**
5131
		 * Fires when a site is registered on WordPress.com.
5132
		 *
5133
		 * @since 3.7.0
5134
		 *
5135
		 * @param int $json->jetpack_id Jetpack Blog ID.
5136
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5137
		 * @param int|bool $jetpack_public Is the site public.
5138
		 */
5139
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5140
5141
		// Initialize Jump Start for the first and only time.
5142
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5143
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5144
5145
			$jetpack = Jetpack::init();
5146
5147
			$jetpack->stat( 'jumpstart', 'unique-views' );
5148
			$jetpack->do_stats( 'server_side' );
5149
		};
5150
5151
		return true;
5152
	}
5153
5154
	/**
5155
	 * If the db version is showing something other that what we've got now, bump it to current.
5156
	 *
5157
	 * @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...
5158
	 */
5159
	public static function maybe_set_version_option() {
5160
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5161
		if ( JETPACK__VERSION != $version ) {
5162
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5163
5164
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5165
				/** This action is documented in class.jetpack.php */
5166
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5167
			}
5168
5169
			return true;
5170
		}
5171
		return false;
5172
	}
5173
5174
/* Client Server API */
5175
5176
	/**
5177
	 * Loads the Jetpack XML-RPC client
5178
	 */
5179
	public static function load_xml_rpc_client() {
5180
		require_once ABSPATH . WPINC . '/class-IXR.php';
5181
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5182
	}
5183
5184
	/**
5185
	 * Resets the saved authentication state in between testing requests.
5186
	 */
5187
	public function reset_saved_auth_state() {
5188
		$this->xmlrpc_verification = null;
5189
		$this->rest_authentication_status = null;
5190
	}
5191
5192
	function verify_xml_rpc_signature() {
5193
		if ( $this->xmlrpc_verification ) {
5194
			return $this->xmlrpc_verification;
5195
		}
5196
5197
		// It's not for us
5198
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5199
			return false;
5200
		}
5201
5202
		@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...
5203
		if (
5204
			empty( $token_key )
5205
		||
5206
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5207
		) {
5208
			return false;
5209
		}
5210
5211
		if ( '0' === $user_id ) {
5212
			$token_type = 'blog';
5213
			$user_id = 0;
5214
		} else {
5215
			$token_type = 'user';
5216
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5217
				return false;
5218
			}
5219
			$user_id = (int) $user_id;
5220
5221
			$user = new WP_User( $user_id );
5222
			if ( ! $user || ! $user->exists() ) {
5223
				return false;
5224
			}
5225
		}
5226
5227
		$token = Jetpack_Data::get_access_token( $user_id, $token_key );
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...
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5228
		if ( ! $token ) {
5229
			return false;
5230
		}
5231
5232
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5233
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5234
			$post_data   = $_POST;
5235
			$file_hashes = array();
5236
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5237
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5238
					continue;
5239
				}
5240
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5241
				$file_hashes[$post_data_key] = $post_data_value;
5242
			}
5243
5244
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5245
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5246
				$post_data[$post_data_key] = $post_data_value;
5247
			}
5248
5249
			ksort( $post_data );
5250
5251
			$body = http_build_query( stripslashes_deep( $post_data ) );
5252
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5253
			$body = file_get_contents( 'php://input' );
5254
		} else {
5255
			$body = null;
5256
		}
5257
5258
		$signature = $jetpack_signature->sign_current_request(
5259
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5260
		);
5261
5262
		if ( ! $signature ) {
5263
			return false;
5264
		} else if ( is_wp_error( $signature ) ) {
5265
			return $signature;
5266
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5267
			return false;
5268
		}
5269
5270
		$timestamp = (int) $_GET['timestamp'];
5271
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5272
5273
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5274
			return false;
5275
		}
5276
5277
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5278
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5279
			if ( ! empty( $_GET['onboarding'] ) ) {
5280
				$jpo = $_GET;
5281
			} else {
5282
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5283
			}
5284
5285
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5286
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5287
5288
			if (
5289
				isset( $jpo_user ) && isset( $jpo_token ) &&
5290
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5291
				isset( $_GET['rest_route'] ) &&
5292
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5293
			) {
5294
				$jpUser = get_user_by( 'email', $jpo_user );
5295
				if ( is_a( $jpUser, 'WP_User' ) ) {
5296
					wp_set_current_user( $jpUser->ID );
5297
					$user_can = is_multisite()
5298
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5299
						: current_user_can( 'manage_options' );
5300
					if ( $user_can ) {
5301
						$token_type = 'user';
5302
						$token->external_user_id = $jpUser->ID;
5303
					}
5304
				}
5305
			}
5306
		}
5307
5308
		$this->xmlrpc_verification = array(
5309
			'type'      => $token_type,
5310
			'token_key' => $token_key,
5311
			'user_id'   => $token->external_user_id,
5312
		);
5313
5314
		return $this->xmlrpc_verification;
5315
	}
5316
5317
	/**
5318
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5319
	 */
5320
	function authenticate_jetpack( $user, $username, $password ) {
5321
		if ( is_a( $user, 'WP_User' ) ) {
5322
			return $user;
5323
		}
5324
5325
		$token_details = $this->verify_xml_rpc_signature();
5326
5327
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5328
			return $user;
5329
		}
5330
5331
		if ( 'user' !== $token_details['type'] ) {
5332
			return $user;
5333
		}
5334
5335
		if ( ! $token_details['user_id'] ) {
5336
			return $user;
5337
		}
5338
5339
		nocache_headers();
5340
5341
		return new WP_User( $token_details['user_id'] );
5342
	}
5343
5344
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5345
	// Uses the existing XMLRPC request signing implementation.
5346
	function wp_rest_authenticate( $user ) {
5347
		if ( ! empty( $user ) ) {
5348
			// Another authentication method is in effect.
5349
			return $user;
5350
		}
5351
5352
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5353
			// Nothing to do for this authentication method.
5354
			return null;
5355
		}
5356
5357
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5358
			// Nothing to do for this authentication method.
5359
			return null;
5360
		}
5361
5362
		// Ensure that we always have the request body available.  At this
5363
		// point, the WP REST API code to determine the request body has not
5364
		// run yet.  That code may try to read from 'php://input' later, but
5365
		// this can only be done once per request in PHP versions prior to 5.6.
5366
		// So we will go ahead and perform this read now if needed, and save
5367
		// the request body where both the Jetpack signature verification code
5368
		// and the WP REST API code can see it.
5369
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5370
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5371
		}
5372
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5373
5374
		// Only support specific request parameters that have been tested and
5375
		// are known to work with signature verification.  A different method
5376
		// can be passed to the WP REST API via the '?_method=' parameter if
5377
		// needed.
5378
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5379
			$this->rest_authentication_status = new WP_Error(
5380
				'rest_invalid_request',
5381
				__( 'This request method is not supported.', 'jetpack' ),
5382
				array( 'status' => 400 )
5383
			);
5384
			return null;
5385
		}
5386
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5387
			$this->rest_authentication_status = new WP_Error(
5388
				'rest_invalid_request',
5389
				__( 'This request method does not support body parameters.', 'jetpack' ),
5390
				array( 'status' => 400 )
5391
			);
5392
			return null;
5393
		}
5394
5395
		$verified = $this->verify_xml_rpc_signature();
5396
5397
		if ( is_wp_error( $verified ) ) {
5398
			$this->rest_authentication_status = $verified;
5399
			return null;
5400
		}
5401
5402
		if (
5403
			$verified &&
5404
			isset( $verified['type'] ) &&
5405
			'user' === $verified['type'] &&
5406
			! empty( $verified['user_id'] )
5407
		) {
5408
			// Authentication successful.
5409
			$this->rest_authentication_status = true;
5410
			return $verified['user_id'];
5411
		}
5412
5413
		// Something else went wrong.  Probably a signature error.
5414
		$this->rest_authentication_status = new WP_Error(
5415
			'rest_invalid_signature',
5416
			__( 'The request is not signed correctly.', 'jetpack' ),
5417
			array( 'status' => 400 )
5418
		);
5419
		return null;
5420
	}
5421
5422
	/**
5423
	 * Report authentication status to the WP REST API.
5424
	 *
5425
	 * @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...
5426
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5427
	 */
5428
	public function wp_rest_authentication_errors( $value ) {
5429
		if ( $value !== null ) {
5430
			return $value;
5431
		}
5432
		return $this->rest_authentication_status;
5433
	}
5434
5435
	function add_nonce( $timestamp, $nonce ) {
5436
		global $wpdb;
5437
		static $nonces_used_this_request = array();
5438
5439
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5440
			return $nonces_used_this_request["$timestamp:$nonce"];
5441
		}
5442
5443
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5444
		$timestamp = (int) $timestamp;
5445
		$nonce     = esc_sql( $nonce );
5446
5447
		// Raw query so we can avoid races: add_option will also update
5448
		$show_errors = $wpdb->show_errors( false );
5449
5450
		$old_nonce = $wpdb->get_row(
5451
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5452
		);
5453
5454
		if ( is_null( $old_nonce ) ) {
5455
			$return = $wpdb->query(
5456
				$wpdb->prepare(
5457
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5458
					"jetpack_nonce_{$timestamp}_{$nonce}",
5459
					time(),
5460
					'no'
5461
				)
5462
			);
5463
		} else {
5464
			$return = false;
5465
		}
5466
5467
		$wpdb->show_errors( $show_errors );
5468
5469
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5470
5471
		return $return;
5472
	}
5473
5474
	/**
5475
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5476
	 * Capture it here so we can verify the signature later.
5477
	 */
5478
	function xmlrpc_methods( $methods ) {
5479
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5480
		return $methods;
5481
	}
5482
5483
	function public_xmlrpc_methods( $methods ) {
5484
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5485
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5486
		}
5487
		return $methods;
5488
	}
5489
5490
	function jetpack_getOptions( $args ) {
5491
		global $wp_xmlrpc_server;
5492
5493
		$wp_xmlrpc_server->escape( $args );
5494
5495
		$username	= $args[1];
5496
		$password	= $args[2];
5497
5498
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5499
			return $wp_xmlrpc_server->error;
5500
		}
5501
5502
		$options = array();
5503
		$user_data = $this->get_connected_user_data();
5504
		if ( is_array( $user_data ) ) {
5505
			$options['jetpack_user_id'] = array(
5506
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5507
				'readonly'      => true,
5508
				'value'         => $user_data['ID'],
5509
			);
5510
			$options['jetpack_user_login'] = array(
5511
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5512
				'readonly'      => true,
5513
				'value'         => $user_data['login'],
5514
			);
5515
			$options['jetpack_user_email'] = array(
5516
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5517
				'readonly'      => true,
5518
				'value'         => $user_data['email'],
5519
			);
5520
			$options['jetpack_user_site_count'] = array(
5521
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5522
				'readonly'      => true,
5523
				'value'         => $user_data['site_count'],
5524
			);
5525
		}
5526
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5527
		$args = stripslashes_deep( $args );
5528
		return $wp_xmlrpc_server->wp_getOptions( $args );
5529
	}
5530
5531
	function xmlrpc_options( $options ) {
5532
		$jetpack_client_id = false;
5533
		if ( self::is_active() ) {
5534
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5535
		}
5536
		$options['jetpack_version'] = array(
5537
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5538
				'readonly'      => true,
5539
				'value'         => JETPACK__VERSION,
5540
		);
5541
5542
		$options['jetpack_client_id'] = array(
5543
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5544
				'readonly'      => true,
5545
				'value'         => $jetpack_client_id,
5546
		);
5547
		return $options;
5548
	}
5549
5550
	public static function clean_nonces( $all = false ) {
5551
		global $wpdb;
5552
5553
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5554
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5555
5556
		if ( true !== $all ) {
5557
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5558
			$sql_args[] = time() - 3600;
5559
		}
5560
5561
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5562
5563
		$sql = $wpdb->prepare( $sql, $sql_args );
5564
5565
		for ( $i = 0; $i < 1000; $i++ ) {
5566
			if ( ! $wpdb->query( $sql ) ) {
5567
				break;
5568
			}
5569
		}
5570
	}
5571
5572
	/**
5573
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5574
	 * SET: state( $key, $value );
5575
	 * GET: $value = state( $key );
5576
	 *
5577
	 * @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...
5578
	 * @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...
5579
	 * @param bool $restate private
5580
	 */
5581
	public static function state( $key = null, $value = null, $restate = false ) {
5582
		static $state = array();
5583
		static $path, $domain;
5584
		if ( ! isset( $path ) ) {
5585
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5586
			$admin_url = Jetpack::admin_url();
5587
			$bits      = wp_parse_url( $admin_url );
5588
5589
			if ( is_array( $bits ) ) {
5590
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5591
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5592
			} else {
5593
				$path = $domain = null;
5594
			}
5595
		}
5596
5597
		// Extract state from cookies and delete cookies
5598
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5599
			$yum = $_COOKIE[ 'jetpackState' ];
5600
			unset( $_COOKIE[ 'jetpackState' ] );
5601
			foreach ( $yum as $k => $v ) {
5602
				if ( strlen( $v ) )
5603
					$state[ $k ] = $v;
5604
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5605
			}
5606
		}
5607
5608
		if ( $restate ) {
5609
			foreach ( $state as $k => $v ) {
5610
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5611
			}
5612
			return;
5613
		}
5614
5615
		// Get a state variable
5616
		if ( isset( $key ) && ! isset( $value ) ) {
5617
			if ( array_key_exists( $key, $state ) )
5618
				return $state[ $key ];
5619
			return null;
5620
		}
5621
5622
		// Set a state variable
5623
		if ( isset ( $key ) && isset( $value ) ) {
5624
			if( is_array( $value ) && isset( $value[0] ) ) {
5625
				$value = $value[0];
5626
			}
5627
			$state[ $key ] = $value;
5628
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5629
		}
5630
	}
5631
5632
	public static function restate() {
5633
		Jetpack::state( null, null, true );
5634
	}
5635
5636
	public static function check_privacy( $file ) {
5637
		static $is_site_publicly_accessible = null;
5638
5639
		if ( is_null( $is_site_publicly_accessible ) ) {
5640
			$is_site_publicly_accessible = false;
5641
5642
			Jetpack::load_xml_rpc_client();
5643
			$rpc = new Jetpack_IXR_Client();
5644
5645
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5646
			if ( $success ) {
5647
				$response = $rpc->getResponse();
5648
				if ( $response ) {
5649
					$is_site_publicly_accessible = true;
5650
				}
5651
			}
5652
5653
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5654
		}
5655
5656
		if ( $is_site_publicly_accessible ) {
5657
			return;
5658
		}
5659
5660
		$module_slug = self::get_module_slug( $file );
5661
5662
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5663
		if ( ! $privacy_checks ) {
5664
			$privacy_checks = $module_slug;
5665
		} else {
5666
			$privacy_checks .= ",$module_slug";
5667
		}
5668
5669
		Jetpack::state( 'privacy_checks', $privacy_checks );
5670
	}
5671
5672
	/**
5673
	 * Helper method for multicall XMLRPC.
5674
	 */
5675
	public static function xmlrpc_async_call() {
5676
		global $blog_id;
5677
		static $clients = array();
5678
5679
		$client_blog_id = is_multisite() ? $blog_id : 0;
5680
5681
		if ( ! isset( $clients[$client_blog_id] ) ) {
5682
			Jetpack::load_xml_rpc_client();
5683
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5684
			if ( function_exists( 'ignore_user_abort' ) ) {
5685
				ignore_user_abort( true );
5686
			}
5687
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5688
		}
5689
5690
		$args = func_get_args();
5691
5692
		if ( ! empty( $args[0] ) ) {
5693
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5694
		} elseif ( is_multisite() ) {
5695
			foreach ( $clients as $client_blog_id => $client ) {
5696
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5697
					continue;
5698
				}
5699
5700
				$switch_success = switch_to_blog( $client_blog_id, true );
5701
				if ( ! $switch_success ) {
5702
					continue;
5703
				}
5704
5705
				flush();
5706
				$client->query();
5707
5708
				restore_current_blog();
5709
			}
5710
		} else {
5711
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5712
				flush();
5713
				$clients[0]->query();
5714
			}
5715
		}
5716
	}
5717
5718
	public static function staticize_subdomain( $url ) {
5719
5720
		// Extract hostname from URL
5721
		$host = parse_url( $url, PHP_URL_HOST );
5722
5723
		// Explode hostname on '.'
5724
		$exploded_host = explode( '.', $host );
5725
5726
		// Retrieve the name and TLD
5727
		if ( count( $exploded_host ) > 1 ) {
5728
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5729
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5730
			// Rebuild domain excluding subdomains
5731
			$domain = $name . '.' . $tld;
5732
		} else {
5733
			$domain = $host;
5734
		}
5735
		// Array of Automattic domains
5736
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5737
5738
		// Return $url if not an Automattic domain
5739
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5740
			return $url;
5741
		}
5742
5743
		if ( is_ssl() ) {
5744
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5745
		}
5746
5747
		srand( crc32( basename( $url ) ) );
5748
		$static_counter = rand( 0, 2 );
5749
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5750
5751
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5752
	}
5753
5754
/* JSON API Authorization */
5755
5756
	/**
5757
	 * Handles the login action for Authorizing the JSON API
5758
	 */
5759
	function login_form_json_api_authorization() {
5760
		$this->verify_json_api_authorization_request();
5761
5762
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5763
5764
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5765
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5766
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5767
	}
5768
5769
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5770
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5771
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5772
			return $url;
5773
		}
5774
5775
		$parsed_url = parse_url( $url );
5776
		$url = strtok( $url, '?' );
5777
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5778
		if ( ! empty( $parsed_url['query'] ) )
5779
			$url .= "&{$parsed_url['query']}";
5780
5781
		return $url;
5782
	}
5783
5784
	// Make sure the POSTed request is handled by the same action
5785
	function preserve_action_in_login_form_for_json_api_authorization() {
5786
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5787
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5788
	}
5789
5790
	// If someone logs in to approve API access, store the Access Code in usermeta
5791
	function store_json_api_authorization_token( $user_login, $user ) {
5792
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5793
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5794
		$token = wp_generate_password( 32, false );
5795
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5796
	}
5797
5798
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5799
	function allow_wpcom_public_api_domain( $domains ) {
5800
		$domains[] = 'public-api.wordpress.com';
5801
		return $domains;
5802
	}
5803
5804
	static function is_redirect_encoded( $redirect_url ) {
5805
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5806
	}
5807
5808
	// Add all wordpress.com environments to the safe redirect whitelist
5809
	function allow_wpcom_environments( $domains ) {
5810
		$domains[] = 'wordpress.com';
5811
		$domains[] = 'wpcalypso.wordpress.com';
5812
		$domains[] = 'horizon.wordpress.com';
5813
		$domains[] = 'calypso.localhost';
5814
		return $domains;
5815
	}
5816
5817
	// Add the Access Code details to the public-api.wordpress.com redirect
5818
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5819
		return add_query_arg(
5820
			urlencode_deep(
5821
				array(
5822
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5823
					'jetpack-user-id' => (int) $user->ID,
5824
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5825
				)
5826
			),
5827
			$redirect_to
5828
		);
5829
	}
5830
5831
5832
	/**
5833
	 * Verifies the request by checking the signature
5834
	 *
5835
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5836
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5837
	 *
5838
	 * @param null|array $environment
5839
	 */
5840
	function verify_json_api_authorization_request( $environment = null ) {
5841
		$environment = is_null( $environment )
5842
			? $_REQUEST
5843
			: $environment;
5844
5845
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
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...
5846
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5847
		if ( ! $token || empty( $token->secret ) ) {
5848
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5849
		}
5850
5851
		$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' );
5852
5853
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5854
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5855
			$this->tracking->record_user_event( 'error_double_encode' );
5856
5857
			$die_error = sprintf(
5858
				/* translators: %s is a URL */
5859
				__( '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' ),
5860
				'https://jetpack.com/support/double-encoding/'
5861
			);
5862
		}
5863
5864
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5865
5866
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5867
			$signature = $jetpack_signature->sign_request(
5868
				$environment['token'],
5869
				$environment['timestamp'],
5870
				$environment['nonce'],
5871
				'',
5872
				'GET',
5873
				$environment['jetpack_json_api_original_query'],
5874
				null,
5875
				true
5876
			);
5877
		} else {
5878
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5879
		}
5880
5881
		if ( ! $signature ) {
5882
			wp_die( $die_error );
5883
		} else if ( is_wp_error( $signature ) ) {
5884
			wp_die( $die_error );
5885
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5886
			if ( is_ssl() ) {
5887
				// 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
5888
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5889
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5890
					wp_die( $die_error );
5891
				}
5892
			} else {
5893
				wp_die( $die_error );
5894
			}
5895
		}
5896
5897
		$timestamp = (int) $environment['timestamp'];
5898
		$nonce     = stripslashes( (string) $environment['nonce'] );
5899
5900
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5901
			// De-nonce the nonce, at least for 5 minutes.
5902
			// 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)
5903
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5904
			if ( $old_nonce_time < time() - 300 ) {
5905
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5906
			}
5907
		}
5908
5909
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5910
		$data_filters = array(
5911
			'state'        => 'opaque',
5912
			'client_id'    => 'int',
5913
			'client_title' => 'string',
5914
			'client_image' => 'url',
5915
		);
5916
5917
		foreach ( $data_filters as $key => $sanitation ) {
5918
			if ( ! isset( $data->$key ) ) {
5919
				wp_die( $die_error );
5920
			}
5921
5922
			switch ( $sanitation ) {
5923
			case 'int' :
5924
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5925
				break;
5926
			case 'opaque' :
5927
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5928
				break;
5929
			case 'string' :
5930
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5931
				break;
5932
			case 'url' :
5933
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5934
				break;
5935
			}
5936
		}
5937
5938
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5939
			wp_die( $die_error );
5940
		}
5941
	}
5942
5943
	function login_message_json_api_authorization( $message ) {
5944
		return '<p class="message">' . sprintf(
5945
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5946
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5947
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5948
	}
5949
5950
	/**
5951
	 * Get $content_width, but with a <s>twist</s> filter.
5952
	 */
5953
	public static function get_content_width() {
5954
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5955
			? $GLOBALS['content_width']
5956
			: false;
5957
		/**
5958
		 * Filter the Content Width value.
5959
		 *
5960
		 * @since 2.2.3
5961
		 *
5962
		 * @param string $content_width Content Width value.
5963
		 */
5964
		return apply_filters( 'jetpack_content_width', $content_width );
5965
	}
5966
5967
	/**
5968
	 * Pings the WordPress.com Mirror Site for the specified options.
5969
	 *
5970
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5971
	 *
5972
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5973
	 */
5974
	public function get_cloud_site_options( $option_names ) {
5975
		$option_names = array_filter( (array) $option_names, 'is_string' );
5976
5977
		Jetpack::load_xml_rpc_client();
5978
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5979
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5980
		if ( $xml->isError() ) {
5981
			return array(
5982
				'error_code' => $xml->getErrorCode(),
5983
				'error_msg'  => $xml->getErrorMessage(),
5984
			);
5985
		}
5986
		$cloud_site_options = $xml->getResponse();
5987
5988
		return $cloud_site_options;
5989
	}
5990
5991
	/**
5992
	 * Checks if the site is currently in an identity crisis.
5993
	 *
5994
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5995
	 */
5996
	public static function check_identity_crisis() {
5997
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5998
			return false;
5999
		}
6000
6001
		return Jetpack_Options::get_option( 'sync_error_idc' );
6002
	}
6003
6004
	/**
6005
	 * Checks whether the home and siteurl specifically are whitelisted
6006
	 * Written so that we don't have re-check $key and $value params every time
6007
	 * we want to check if this site is whitelisted, for example in footer.php
6008
	 *
6009
	 * @since  3.8.0
6010
	 * @return bool True = already whitelisted False = not whitelisted
6011
	 */
6012
	public static function is_staging_site() {
6013
		$is_staging = false;
6014
6015
		$known_staging = array(
6016
			'urls' => array(
6017
				'#\.staging\.wpengine\.com$#i', // WP Engine
6018
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6019
				'#\.stage\.site$#i'             // DreamPress
6020
			),
6021
			'constants' => array(
6022
				'IS_WPE_SNAPSHOT',      // WP Engine
6023
				'KINSTA_DEV_ENV',       // Kinsta.com
6024
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6025
				'JETPACK_STAGING_MODE', // Generic
6026
			)
6027
		);
6028
		/**
6029
		 * Filters the flags of known staging sites.
6030
		 *
6031
		 * @since 3.9.0
6032
		 *
6033
		 * @param array $known_staging {
6034
		 *     An array of arrays that each are used to check if the current site is staging.
6035
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6036
		 *     @type array $constants PHP constants of known staging/developement environments.
6037
		 *  }
6038
		 */
6039
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6040
6041
		if ( isset( $known_staging['urls'] ) ) {
6042
			foreach ( $known_staging['urls'] as $url ){
6043
				if ( preg_match( $url, site_url() ) ) {
6044
					$is_staging = true;
6045
					break;
6046
				}
6047
			}
6048
		}
6049
6050
		if ( isset( $known_staging['constants'] ) ) {
6051
			foreach ( $known_staging['constants'] as $constant ) {
6052
				if ( defined( $constant ) && constant( $constant ) ) {
6053
					$is_staging = true;
6054
				}
6055
			}
6056
		}
6057
6058
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6059
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6060
			$is_staging = true;
6061
		}
6062
6063
		/**
6064
		 * Filters is_staging_site check.
6065
		 *
6066
		 * @since 3.9.0
6067
		 *
6068
		 * @param bool $is_staging If the current site is a staging site.
6069
		 */
6070
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6071
	}
6072
6073
	/**
6074
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6075
	 *
6076
	 * @since 4.4.0
6077
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6078
	 *
6079
	 * @return bool
6080
	 */
6081
	public static function validate_sync_error_idc_option() {
6082
		$is_valid = false;
6083
6084
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6085
		if ( false === $idc_allowed ) {
6086
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6087
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6088
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6089
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6090
				$transient_duration = HOUR_IN_SECONDS;
6091
			} else {
6092
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6093
				$idc_allowed = '1';
6094
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6095
			}
6096
6097
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6098
		}
6099
6100
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6101
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6102
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6103
			$local_options = self::get_sync_error_idc_option();
6104
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6105
				$is_valid = true;
6106
			}
6107
		}
6108
6109
		/**
6110
		 * Filters whether the sync_error_idc option is valid.
6111
		 *
6112
		 * @since 4.4.0
6113
		 *
6114
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6115
		 */
6116
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6117
6118
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6119
			// Since the option exists, and did not validate, delete it
6120
			Jetpack_Options::delete_option( 'sync_error_idc' );
6121
		}
6122
6123
		return $is_valid;
6124
	}
6125
6126
	/**
6127
	 * Normalizes a url by doing three things:
6128
	 *  - Strips protocol
6129
	 *  - Strips www
6130
	 *  - Adds a trailing slash
6131
	 *
6132
	 * @since 4.4.0
6133
	 * @param string $url
6134
	 * @return WP_Error|string
6135
	 */
6136
	public static function normalize_url_protocol_agnostic( $url ) {
6137
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6138
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6139
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6140
		}
6141
6142
		// Strip www and protocols
6143
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6144
		return $url;
6145
	}
6146
6147
	/**
6148
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6149
	 *
6150
	 * @since 4.4.0
6151
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6152
	 *
6153
	 * @param array $response
6154
	 * @return array Array of the local urls, wpcom urls, and error code
6155
	 */
6156
	public static function get_sync_error_idc_option( $response = array() ) {
6157
		// Since the local options will hit the database directly, store the values
6158
		// in a transient to allow for autoloading and caching on subsequent views.
6159
		$local_options = get_transient( 'jetpack_idc_local' );
6160
		if ( false === $local_options ) {
6161
			$local_options = array(
6162
				'home'    => Jetpack_Sync_Functions::home_url(),
6163
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6164
			);
6165
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6166
		}
6167
6168
		$options = array_merge( $local_options, $response );
6169
6170
		$returned_values = array();
6171
		foreach( $options as $key => $option ) {
6172
			if ( 'error_code' === $key ) {
6173
				$returned_values[ $key ] = $option;
6174
				continue;
6175
			}
6176
6177
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6178
				continue;
6179
			}
6180
6181
			$returned_values[ $key ] = $normalized_url;
6182
		}
6183
6184
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6185
6186
		return $returned_values;
6187
	}
6188
6189
	/**
6190
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6191
	 * If set to true, the site will be put into staging mode.
6192
	 *
6193
	 * @since 4.3.2
6194
	 * @return bool
6195
	 */
6196
	public static function sync_idc_optin() {
6197
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6198
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6199
		} else {
6200
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6201
		}
6202
6203
		/**
6204
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6205
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6206
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6207
		 *
6208
		 * @since 4.3.2
6209
		 *
6210
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6211
		 */
6212
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6213
	}
6214
6215
	/**
6216
	 * Maybe Use a .min.css stylesheet, maybe not.
6217
	 *
6218
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6219
	 */
6220
	public static function maybe_min_asset( $url, $path, $plugin ) {
6221
		// Short out on things trying to find actual paths.
6222
		if ( ! $path || empty( $plugin ) ) {
6223
			return $url;
6224
		}
6225
6226
		$path = ltrim( $path, '/' );
6227
6228
		// Strip out the abspath.
6229
		$base = dirname( plugin_basename( $plugin ) );
6230
6231
		// Short out on non-Jetpack assets.
6232
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6233
			return $url;
6234
		}
6235
6236
		// File name parsing.
6237
		$file              = "{$base}/{$path}";
6238
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6239
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6240
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6241
		$extension         = array_shift( $file_name_parts_r );
6242
6243
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6244
			// Already pointing at the minified version.
6245
			if ( 'min' === $file_name_parts_r[0] ) {
6246
				return $url;
6247
			}
6248
6249
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6250
			if ( file_exists( $min_full_path ) ) {
6251
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6252
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6253
				if ( 'css' === $extension ) {
6254
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6255
					self::$min_assets[ $key ] = $path;
6256
				}
6257
			}
6258
		}
6259
6260
		return $url;
6261
	}
6262
6263
	/**
6264
	 * If the asset is minified, let's flag .min as the suffix.
6265
	 *
6266
	 * Attached to `style_loader_src` filter.
6267
	 *
6268
	 * @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...
6269
	 * @param string $handle The registered handle of the script in question.
6270
	 * @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...
6271
	 */
6272
	public static function set_suffix_on_min( $src, $handle ) {
6273
		if ( false === strpos( $src, '.min.css' ) ) {
6274
			return $src;
6275
		}
6276
6277
		if ( ! empty( self::$min_assets ) ) {
6278
			foreach ( self::$min_assets as $file => $path ) {
6279
				if ( false !== strpos( $src, $file ) ) {
6280
					wp_style_add_data( $handle, 'suffix', '.min' );
6281
					return $src;
6282
				}
6283
			}
6284
		}
6285
6286
		return $src;
6287
	}
6288
6289
	/**
6290
	 * Maybe inlines a stylesheet.
6291
	 *
6292
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6293
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6294
	 *
6295
	 * Attached to `style_loader_tag` filter.
6296
	 *
6297
	 * @param string $tag The tag that would link to the external asset.
6298
	 * @param string $handle The registered handle of the script in question.
6299
	 *
6300
	 * @return string
6301
	 */
6302
	public static function maybe_inline_style( $tag, $handle ) {
6303
		global $wp_styles;
6304
		$item = $wp_styles->registered[ $handle ];
6305
6306
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6307
			return $tag;
6308
		}
6309
6310
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6311
			$href = $matches[1];
6312
			// Strip off query string
6313
			if ( $pos = strpos( $href, '?' ) ) {
6314
				$href = substr( $href, 0, $pos );
6315
			}
6316
			// Strip off fragment
6317
			if ( $pos = strpos( $href, '#' ) ) {
6318
				$href = substr( $href, 0, $pos );
6319
			}
6320
		} else {
6321
			return $tag;
6322
		}
6323
6324
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6325
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6326
			return $tag;
6327
		}
6328
6329
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6330
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6331
			// And this isn't the pass that actually deals with the RTL version...
6332
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6333
				// Short out, as the RTL version will deal with it in a moment.
6334
				return $tag;
6335
			}
6336
		}
6337
6338
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6339
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6340
		if ( $css ) {
6341
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6342
			if ( empty( $item->extra['after'] ) ) {
6343
				wp_add_inline_style( $handle, $css );
6344
			} else {
6345
				array_unshift( $item->extra['after'], $css );
6346
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6347
			}
6348
		}
6349
6350
		return $tag;
6351
	}
6352
6353
	/**
6354
	 * Loads a view file from the views
6355
	 *
6356
	 * Data passed in with the $data parameter will be available in the
6357
	 * template file as $data['value']
6358
	 *
6359
	 * @param string $template - Template file to load
6360
	 * @param array $data - Any data to pass along to the template
6361
	 * @return boolean - If template file was found
6362
	 **/
6363
	public function load_view( $template, $data = array() ) {
6364
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6365
6366
		if( file_exists( $views_dir . $template ) ) {
6367
			require_once( $views_dir . $template );
6368
			return true;
6369
		}
6370
6371
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6372
		return false;
6373
	}
6374
6375
	/**
6376
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6377
	 */
6378
	public function deprecated_hooks() {
6379
		global $wp_filter;
6380
6381
		/*
6382
		 * Format:
6383
		 * deprecated_filter_name => replacement_name
6384
		 *
6385
		 * If there is no replacement, use null for replacement_name
6386
		 */
6387
		$deprecated_list = array(
6388
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6389
			'wpl_sharing_2014_1'                                     => null,
6390
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6391
			'jetpack_identity_crisis_options_to_check'               => null,
6392
			'update_option_jetpack_single_user_site'                 => null,
6393
			'audio_player_default_colors'                            => null,
6394
			'add_option_jetpack_featured_images_enabled'             => null,
6395
			'add_option_jetpack_update_details'                      => null,
6396
			'add_option_jetpack_updates'                             => null,
6397
			'add_option_jetpack_network_name'                        => null,
6398
			'add_option_jetpack_network_allow_new_registrations'     => null,
6399
			'add_option_jetpack_network_add_new_users'               => null,
6400
			'add_option_jetpack_network_site_upload_space'           => null,
6401
			'add_option_jetpack_network_upload_file_types'           => null,
6402
			'add_option_jetpack_network_enable_administration_menus' => null,
6403
			'add_option_jetpack_is_multi_site'                       => null,
6404
			'add_option_jetpack_is_main_network'                     => null,
6405
			'add_option_jetpack_main_network_site'                   => null,
6406
			'jetpack_sync_all_registered_options'                    => null,
6407
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6408
			'jetpack_is_post_mailable'                               => null,
6409
			'jetpack_seo_site_host'                                  => null,
6410
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6411
			'jetpack_holiday_snow_option_name'                       => null,
6412
			'jetpack_holiday_chance_of_snow'                         => null,
6413
			'jetpack_holiday_snow_js_url'                            => null,
6414
			'jetpack_is_holiday_snow_season'                         => null,
6415
			'jetpack_holiday_snow_option_updated'                    => null,
6416
			'jetpack_holiday_snowing'                                => null,
6417
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6418
			'jetpack_cache_plans'                                    => null,
6419
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6420
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6421
			'jetpack_enable_site_verification'                       => null,
6422
			'can_display_jetpack_manage_notice'                      => null,
6423
			// Removed in Jetpack 7.3.0
6424
			'atd_load_scripts'                                       => null,
6425
			'atd_http_post_timeout'                                  => null,
6426
			'atd_http_post_error'                                    => null,
6427
			'atd_service_domain'                                     => null,
6428
		);
6429
6430
		// This is a silly loop depth. Better way?
6431
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6432
			if ( has_action( $hook ) ) {
6433
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6434
					foreach( $values AS $hooked ) {
6435
						if ( is_callable( $hooked['function'] ) ) {
6436
							$function_name = 'an anonymous function';
6437
						} else {
6438
							$function_name = $hooked['function'];
6439
						}
6440
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6441
					}
6442
				}
6443
			}
6444
		}
6445
	}
6446
6447
	/**
6448
	 * Converts any url in a stylesheet, to the correct absolute url.
6449
	 *
6450
	 * Considerations:
6451
	 *  - Normal, relative URLs     `feh.png`
6452
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6453
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6454
	 *  - Absolute URLs             `http://domain.com/feh.png`
6455
	 *  - Domain root relative URLs `/feh.png`
6456
	 *
6457
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6458
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6459
	 *
6460
	 * @return mixed|string
6461
	 */
6462
	public static function absolutize_css_urls( $css, $css_file_url ) {
6463
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6464
		$css_dir = dirname( $css_file_url );
6465
		$p       = parse_url( $css_dir );
6466
		$domain  = sprintf(
6467
					'%1$s//%2$s%3$s%4$s',
6468
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6469
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6470
					$p['host'],
6471
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6472
				);
6473
6474
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6475
			$find = $replace = array();
6476
			foreach ( $matches as $match ) {
6477
				$url = trim( $match['path'], "'\" \t" );
6478
6479
				// If this is a data url, we don't want to mess with it.
6480
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6481
					continue;
6482
				}
6483
6484
				// If this is an absolute or protocol-agnostic url,
6485
				// we don't want to mess with it.
6486
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6487
					continue;
6488
				}
6489
6490
				switch ( substr( $url, 0, 1 ) ) {
6491
					case '/':
6492
						$absolute = $domain . $url;
6493
						break;
6494
					default:
6495
						$absolute = $css_dir . '/' . $url;
6496
				}
6497
6498
				$find[]    = $match[0];
6499
				$replace[] = sprintf( 'url("%s")', $absolute );
6500
			}
6501
			$css = str_replace( $find, $replace, $css );
6502
		}
6503
6504
		return $css;
6505
	}
6506
6507
	/**
6508
	 * This methods removes all of the registered css files on the front end
6509
	 * from Jetpack in favor of using a single file. In effect "imploding"
6510
	 * all the files into one file.
6511
	 *
6512
	 * Pros:
6513
	 * - Uses only ONE css asset connection instead of 15
6514
	 * - Saves a minimum of 56k
6515
	 * - Reduces server load
6516
	 * - Reduces time to first painted byte
6517
	 *
6518
	 * Cons:
6519
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6520
	 *		should not cause any issues with themes.
6521
	 * - Plugins/themes dequeuing styles no longer do anything. See
6522
	 *		jetpack_implode_frontend_css filter for a workaround
6523
	 *
6524
	 * For some situations developers may wish to disable css imploding and
6525
	 * instead operate in legacy mode where each file loads seperately and
6526
	 * can be edited individually or dequeued. This can be accomplished with
6527
	 * the following line:
6528
	 *
6529
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6530
	 *
6531
	 * @since 3.2
6532
	 **/
6533
	public function implode_frontend_css( $travis_test = false ) {
6534
		$do_implode = true;
6535
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6536
			$do_implode = false;
6537
		}
6538
6539
		// Do not implode CSS when the page loads via the AMP plugin.
6540
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6541
			$do_implode = false;
6542
		}
6543
6544
		/**
6545
		 * Allow CSS to be concatenated into a single jetpack.css file.
6546
		 *
6547
		 * @since 3.2.0
6548
		 *
6549
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6550
		 */
6551
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6552
6553
		// Do not use the imploded file when default behavior was altered through the filter
6554
		if ( ! $do_implode ) {
6555
			return;
6556
		}
6557
6558
		// We do not want to use the imploded file in dev mode, or if not connected
6559
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6560
			if ( ! $travis_test ) {
6561
				return;
6562
			}
6563
		}
6564
6565
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6566
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6567
			return;
6568
		}
6569
6570
		/*
6571
		 * Now we assume Jetpack is connected and able to serve the single
6572
		 * file.
6573
		 *
6574
		 * In the future there will be a check here to serve the file locally
6575
		 * or potentially from the Jetpack CDN
6576
		 *
6577
		 * For now:
6578
		 * - Enqueue a single imploded css file
6579
		 * - Zero out the style_loader_tag for the bundled ones
6580
		 * - Be happy, drink scotch
6581
		 */
6582
6583
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6584
6585
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6586
6587
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6588
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6589
	}
6590
6591
	function concat_remove_style_loader_tag( $tag, $handle ) {
6592
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6593
			$tag = '';
6594
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6595
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6596
			}
6597
		}
6598
6599
		return $tag;
6600
	}
6601
6602
	/*
6603
	 * Check the heartbeat data
6604
	 *
6605
	 * Organizes the heartbeat data by severity.  For example, if the site
6606
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6607
	 *
6608
	 * Data will be added to "caution" array, if it either:
6609
	 *  - Out of date Jetpack version
6610
	 *  - Out of date WP version
6611
	 *  - Out of date PHP version
6612
	 *
6613
	 * $return array $filtered_data
6614
	 */
6615
	public static function jetpack_check_heartbeat_data() {
6616
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6617
6618
		$good    = array();
6619
		$caution = array();
6620
		$bad     = array();
6621
6622
		foreach ( $raw_data as $stat => $value ) {
6623
6624
			// Check jetpack version
6625
			if ( 'version' == $stat ) {
6626
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6627
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6628
					continue;
6629
				}
6630
			}
6631
6632
			// Check WP version
6633
			if ( 'wp-version' == $stat ) {
6634
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6635
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6636
					continue;
6637
				}
6638
			}
6639
6640
			// Check PHP version
6641
			if ( 'php-version' == $stat ) {
6642
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6643
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6644
					continue;
6645
				}
6646
			}
6647
6648
			// Check ID crisis
6649
			if ( 'identitycrisis' == $stat ) {
6650
				if ( 'yes' == $value ) {
6651
					$bad[ $stat ] = $value;
6652
					continue;
6653
				}
6654
			}
6655
6656
			// The rest are good :)
6657
			$good[ $stat ] = $value;
6658
		}
6659
6660
		$filtered_data = array(
6661
			'good'    => $good,
6662
			'caution' => $caution,
6663
			'bad'     => $bad
6664
		);
6665
6666
		return $filtered_data;
6667
	}
6668
6669
6670
	/*
6671
	 * This method is used to organize all options that can be reset
6672
	 * without disconnecting Jetpack.
6673
	 *
6674
	 * It is used in class.jetpack-cli.php to reset options
6675
	 *
6676
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6677
	 *
6678
	 * @return array of options to delete.
6679
	 */
6680
	public static function get_jetpack_options_for_reset() {
6681
		return Jetpack_Options::get_options_for_reset();
6682
	}
6683
6684
	/*
6685
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6686
	 * so we can bring them directly to their site in calypso.
6687
	 *
6688
	 * @param string | url
6689
	 * @return string | url without the guff
6690
	 */
6691
	public static function build_raw_urls( $url ) {
6692
		$strip_http = '/.*?:\/\//i';
6693
		$url = preg_replace( $strip_http, '', $url  );
6694
		$url = str_replace( '/', '::', $url );
6695
		return $url;
6696
	}
6697
6698
	/**
6699
	 * Stores and prints out domains to prefetch for page speed optimization.
6700
	 *
6701
	 * @param mixed $new_urls
6702
	 */
6703
	public static function dns_prefetch( $new_urls = null ) {
6704
		static $prefetch_urls = array();
6705
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6706
			echo "\r\n";
6707
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6708
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6709
			}
6710
		} elseif ( ! empty( $new_urls ) ) {
6711
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6712
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6713
			}
6714
			foreach ( (array) $new_urls as $this_new_url ) {
6715
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6716
			}
6717
			$prefetch_urls = array_unique( $prefetch_urls );
6718
		}
6719
	}
6720
6721
	public function wp_dashboard_setup() {
6722
		if ( self::is_active() ) {
6723
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6724
		}
6725
6726
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6727
			$jetpack_logo = new Jetpack_Logo();
6728
			$widget_title = sprintf(
6729
				wp_kses(
6730
					/* translators: Placeholder is a Jetpack logo. */
6731
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6732
					array( 'span' => array() )
6733
				),
6734
				$jetpack_logo->get_jp_emblem( true )
6735
			);
6736
6737
			wp_add_dashboard_widget(
6738
				'jetpack_summary_widget',
6739
				$widget_title,
6740
				array( __CLASS__, 'dashboard_widget' )
6741
			);
6742
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6743
6744
			// If we're inactive and not in development mode, sort our box to the top.
6745
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6746
				global $wp_meta_boxes;
6747
6748
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6749
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6750
6751
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6752
			}
6753
		}
6754
	}
6755
6756
	/**
6757
	 * @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...
6758
	 * @return mixed
6759
	 */
6760
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6761
		if ( ! is_array( $sorted ) ) {
6762
			return $sorted;
6763
		}
6764
6765
		foreach ( $sorted as $box_context => $ids ) {
6766
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6767
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6768
				continue;
6769
			}
6770
6771
			$ids_array = explode( ',', $ids );
6772
			$key = array_search( 'dashboard_stats', $ids_array );
6773
6774
			if ( false !== $key ) {
6775
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6776
				$ids_array[ $key ] = 'jetpack_summary_widget';
6777
				$sorted[ $box_context ] = implode( ',', $ids_array );
6778
				// We've found it, stop searching, and just return.
6779
				break;
6780
			}
6781
		}
6782
6783
		return $sorted;
6784
	}
6785
6786
	public static function dashboard_widget() {
6787
		/**
6788
		 * Fires when the dashboard is loaded.
6789
		 *
6790
		 * @since 3.4.0
6791
		 */
6792
		do_action( 'jetpack_dashboard_widget' );
6793
	}
6794
6795
	public static function dashboard_widget_footer() {
6796
		?>
6797
		<footer>
6798
6799
		<div class="protect">
6800
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6801
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6802
				<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>
6803
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6804
				<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' ); ?>">
6805
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6806
				</a>
6807
			<?php else : ?>
6808
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6809
			<?php endif; ?>
6810
		</div>
6811
6812
		<div class="akismet">
6813
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6814
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6815
				<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>
6816
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6817
				<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">
6818
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6819
				</a>
6820
			<?php else : ?>
6821
				<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>
6822
			<?php endif; ?>
6823
		</div>
6824
6825
		</footer>
6826
		<?php
6827
	}
6828
6829
	/*
6830
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6831
	 */
6832
	function jetpack_icon_user_connected( $columns ) {
6833
		$columns['user_jetpack'] = '';
6834
		return $columns;
6835
	}
6836
6837
	/*
6838
	 * Show Jetpack icon if the user is linked.
6839
	 */
6840
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6841
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6842
			$jetpack_logo = new Jetpack_Logo();
6843
			$emblem_html = sprintf(
6844
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6845
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6846
				$jetpack_logo->get_jp_emblem()
6847
			);
6848
			return $emblem_html;
6849
		}
6850
6851
		return $val;
6852
	}
6853
6854
	/*
6855
	 * Style the Jetpack user column
6856
	 */
6857
	function jetpack_user_col_style() {
6858
		global $current_screen;
6859
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6860
			<style>
6861
				.fixed .column-user_jetpack {
6862
					width: 21px;
6863
				}
6864
				.jp-emblem-user-admin svg {
6865
					width: 20px;
6866
					height: 20px;
6867
				}
6868
				.jp-emblem-user-admin path {
6869
					fill: #00BE28;
6870
				}
6871
			</style>
6872
		<?php }
6873
	}
6874
6875
	/**
6876
	 * Checks if Akismet is active and working.
6877
	 *
6878
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6879
	 * that implied usage of methods present since more recent version.
6880
	 * See https://github.com/Automattic/jetpack/pull/9585
6881
	 *
6882
	 * @since  5.1.0
6883
	 *
6884
	 * @return bool True = Akismet available. False = Aksimet not available.
6885
	 */
6886
	public static function is_akismet_active() {
6887
		static $status = null;
6888
6889
		if ( ! is_null( $status ) ) {
6890
			return $status;
6891
		}
6892
6893
		// Check if a modern version of Akismet is active.
6894
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6895
			$status = false;
6896
			return $status;
6897
		}
6898
6899
		// Make sure there is a key known to Akismet at all before verifying key.
6900
		$akismet_key = Akismet::get_api_key();
6901
		if ( ! $akismet_key ) {
6902
			$status = false;
6903
			return $status;
6904
		}
6905
6906
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6907
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6908
6909
		// 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.
6910
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6911
		// We cache the result of the Akismet key verification for ten minutes.
6912
		if ( ! $akismet_key_state || $recheck ) {
6913
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6914
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6915
		}
6916
6917
		$status = 'valid' === $akismet_key_state;
6918
6919
		return $status;
6920
	}
6921
6922
	/**
6923
	 * Checks if one or more function names is in debug_backtrace
6924
	 *
6925
	 * @param $names Mixed string name of function or array of string names of functions
6926
	 *
6927
	 * @return bool
6928
	 */
6929
	public static function is_function_in_backtrace( $names ) {
6930
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6931
		if ( ! is_array( $names ) ) {
6932
			$names = array( $names );
6933
		}
6934
		$names_as_keys = array_flip( $names );
6935
6936
		//Do check in constant O(1) time for PHP5.5+
6937
		if ( function_exists( 'array_column' ) ) {
6938
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6939
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6940
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6941
			return ! empty ( $intersection );
6942
		}
6943
6944
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6945
		foreach ( $backtrace as $call ) {
6946
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6947
				return true;
6948
			}
6949
		}
6950
		return false;
6951
	}
6952
6953
	/**
6954
	 * Given a minified path, and a non-minified path, will return
6955
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6956
	 *
6957
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6958
	 * root Jetpack directory.
6959
	 *
6960
	 * @since 5.6.0
6961
	 *
6962
	 * @param string $min_path
6963
	 * @param string $non_min_path
6964
	 * @return string The URL to the file
6965
	 */
6966
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6967
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6968
			? $non_min_path
6969
			: $min_path;
6970
6971
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6972
	}
6973
6974
	/**
6975
	 * Checks for whether Jetpack Backup & Scan is enabled.
6976
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6977
	 * @return bool|int|mixed
6978
	 */
6979
	public static function is_rewind_enabled() {
6980
		if ( ! Jetpack::is_active() ) {
6981
			return false;
6982
		}
6983
6984
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6985
		if ( false === $rewind_enabled ) {
6986
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6987
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6988
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6989
				&& ! empty( $rewind_data['state'] )
6990
				&& 'active' === $rewind_data['state'] )
6991
				? 1
6992
				: 0;
6993
6994
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6995
		}
6996
		return $rewind_enabled;
6997
	}
6998
6999
	/**
7000
	 * Return Calypso environment value; used for developing Jetpack and pairing
7001
	 * it with different Calypso enrionments, such as localhost.
7002
	 *
7003
	 * @since 7.4.0
7004
	 *
7005
	 * @return string Calypso environment
7006
	 */
7007
	public static function get_calypso_env() {
7008
		if ( isset( $_GET['calypso_env'] ) ) {
7009
			return sanitize_key( $_GET['calypso_env'] );
7010
		}
7011
7012
		if ( getenv( 'CALYPSO_ENV' ) ) {
7013
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7014
		}
7015
7016
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7017
			return sanitize_key( CALYPSO_ENV );
7018
		}
7019
7020
		return '';
7021
	}
7022
7023
	/**
7024
	 * Checks whether or not TOS has been agreed upon.
7025
	 * Will return true if a user has clicked to register, or is already connected.
7026
	 */
7027
	public static function jetpack_tos_agreed() {
7028
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7029
	}
7030
7031
	/**
7032
	 * Handles activating default modules as well general cleanup for the new connection.
7033
	 *
7034
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7035
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7036
	 * @param boolean $send_state_messages          Whether to send state messages.
7037
	 * @return void
7038
	 */
7039
	public static function handle_post_authorization_actions(
7040
		$activate_sso = false,
7041
		$redirect_on_activation_error = false,
7042
		$send_state_messages = true
7043
	) {
7044
		$other_modules = $activate_sso
7045
			? array( 'sso' )
7046
			: array();
7047
7048
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7049
			Jetpack::delete_active_modules();
7050
7051
			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...
7052
		} else {
7053
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7054
		}
7055
7056
		// Since this is a fresh connection, be sure to clear out IDC options
7057
		Jetpack_IDC::clear_all_idc_options();
7058
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7059
7060
		// Start nonce cleaner
7061
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7062
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7063
7064
		if ( $send_state_messages ) {
7065
			Jetpack::state( 'message', 'authorized' );
7066
		}
7067
	}
7068
7069
	/**
7070
	 * Returns a boolean for whether backups UI should be displayed or not.
7071
	 *
7072
	 * @return bool Should backups UI be displayed?
7073
	 */
7074
	public static function show_backups_ui() {
7075
		/**
7076
		 * Whether UI for backups should be displayed.
7077
		 *
7078
		 * @since 6.5.0
7079
		 *
7080
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7081
		 */
7082
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7083
	}
7084
7085
	/*
7086
	 * Deprecated manage functions
7087
	 */
7088
	function prepare_manage_jetpack_notice() {
7089
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7090
	}
7091
	function manage_activate_screen() {
7092
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7093
	}
7094
	function admin_jetpack_manage_notice() {
7095
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7096
	}
7097
	function opt_out_jetpack_manage_url() {
7098
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7099
	}
7100
	function opt_in_jetpack_manage_url() {
7101
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7102
	}
7103
	function opt_in_jetpack_manage_notice() {
7104
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7105
	}
7106
	function can_display_jetpack_manage_notice() {
7107
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7108
	}
7109
7110
	/**
7111
	 * Clean leftoveruser meta.
7112
	 *
7113
	 * Delete Jetpack-related user meta when it is no longer needed.
7114
	 *
7115
	 * @since 7.3.0
7116
	 *
7117
	 * @param int $user_id User ID being updated.
7118
	 */
7119
	public static function user_meta_cleanup( $user_id ) {
7120
		$meta_keys = array(
7121
			// AtD removed from Jetpack 7.3
7122
			'AtD_options',
7123
			'AtD_check_when',
7124
			'AtD_guess_lang',
7125
			'AtD_ignored_phrases',
7126
		);
7127
7128
		foreach ( $meta_keys as $meta_key ) {
7129
			if ( get_user_meta( $user_id, $meta_key ) ) {
7130
				delete_user_meta( $user_id, $meta_key );
7131
			}
7132
		}
7133
	}
7134
7135
	function is_active_and_not_development_mode( $maybe ) {
7136
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7137
			return false;
7138
		}
7139
		return true;
7140
	}
7141
7142
	/* Activated module */
7143
	function track_activate_module( $module ) {
7144
		$this->tracking->record_user_event( 'module_activated', array( 'module' => $module ) );
7145
	}
7146
7147
	/* Deactivated module */
7148
	function track_deactivate_module( $module ) {
7149
		$this->tracking->record_user_event( 'module_deactivated', array( 'module' => $module ) );
7150
	}
7151
7152
	/* User has linked their account */
7153
	function track_user_linked() {
7154
		$user_id = get_current_user_id();
7155
		$anon_id = get_user_meta( $user_id, 'jetpack_tracks_anon_id', true );
7156
7157
		if ( $anon_id ) {
7158
			$this->tracking->record_user_event( '_aliasUser', array( 'anonId' => $anon_id ) );
7159
			delete_user_meta( $user_id, 'jetpack_tracks_anon_id' );
7160
			if ( ! headers_sent() ) {
7161
				setcookie( 'tk_ai', 'expired', time() - 1000 );
7162
			}
7163
		}
7164
7165
		$wpcom_user_data = self::get_connected_user_data( $user_id );
7166
		update_user_meta( $user_id, 'jetpack_tracks_wpcom_id', $wpcom_user_data['ID'] );
7167
7168
		$this->tracking->record_user_event( 'wpa_user_linked', array() );
7169
	}
7170
7171
	/**
7172
	 * Track that we've begun verifying the secrets.
7173
	 *
7174
	 * @access public
7175
	 *
7176
	 * @param string   $action Type of secret (one of 'register', 'authorize', 'publicize').
7177
	 * @param \WP_User $user   The user object.
7178
	 */
7179
	public function track_jetpack_verify_secrets_begin( $action, $user ) {
7180
		$this->tracking->record_user_event( "jpc_verify_{$action}_begin", array(), $user );
7181
	}
7182
7183
	/**
7184
	 * Track that we've succeeded in verifying the secrets.
7185
	 *
7186
	 * @access public
7187
	 *
7188
	 * @param string   $action Type of secret (one of 'register', 'authorize', 'publicize').
7189
	 * @param \WP_User $user   The user object.
7190
	 */
7191
	public function track_jetpack_verify_secrets_success( $action, $user ) {
7192
		$this->tracking->record_user_event( "jpc_verify_{$action}_success", array(), $user );
7193
	}
7194
7195
	/**
7196
	 * Track that we've failed verifying the secrets.
7197
	 *
7198
	 * @access public
7199
	 *
7200
	 * @param string    $action Type of secret (one of 'register', 'authorize', 'publicize').
7201
	 * @param \WP_User  $user   The user object.
7202
	 * @param \WP_Error $error  Error object.
7203
	 */
7204
	public function track_jetpack_verify_secrets_fail( $action, $user, $error ) {
7205
		$this->tracking->record_user_event(
7206
			"jpc_verify_{$action}_fail",
7207
			array(
7208
				'error_code'    => $error->get_error_code(),
7209
				'error_message' => $error->get_error_message(),
7210
			),
7211
			$user
7212
		);
7213
	}
7214
7215
	/* Failed login attempts */
7216
	function track_failed_login_attempts( $login ) {
7217
		require_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
7218
		$this->tracking->record_user_event(
7219
			'failed_login',
7220
			array(
7221
				'origin_ip' => jetpack_protect_get_ip(),
7222
				'login'     => $login,
7223
			)
7224
		);
7225
	}
7226
7227
	function track_jetpack_usage() {
7228
		if ( ! self::jetpack_tos_agreed() ) {
7229
			return;
7230
		}
7231
7232
		// For tracking stuff via js/ajax
7233
		add_action( 'admin_enqueue_scripts', array( $this->tracking, 'enqueue_tracks_scripts' ) );
7234
7235
		add_action( 'jetpack_activate_module', array( $this, 'track_activate_module' ), 1, 1 );
7236
		add_action( 'jetpack_deactivate_module', array( $this, 'track_deactivate_module' ), 1, 1 );
7237
		add_action( 'jetpack_user_authorized', array( $this, 'track_user_linked' ) );
7238
		add_action( 'wp_login_failed', array( $this, 'track_failed_login_attempts' ) );
7239
	}
7240
7241
7242
}
7243