Completed
Push — fix/unlinked-user-plans-13415 ( 2492f2...f4e658 )
by Jeremy
23:38 queued 16:15
created

Jetpack::jetpack_track_last_sync_callback()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 1
dl 0
loc 22
rs 9.2568
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * The handles of scripts that can be loaded asynchronously.
86
	 *
87
	 * @var array
88
	 */
89
	public $async_script_handles = array(
90
		'woocommerce-analytics',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
115
	);
116
117
	/**
118
	 * Map of roles we care about, and their corresponding minimum capabilities.
119
	 *
120
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
121
	 *
122
	 * @access public
123
	 * @static
124
	 *
125
	 * @var array
126
	 */
127
	public static $capability_translations = array(
128
		'administrator' => 'manage_options',
129
		'editor'        => 'edit_others_posts',
130
		'author'        => 'publish_posts',
131
		'contributor'   => 'edit_posts',
132
		'subscriber'    => 'read',
133
	);
134
135
	/**
136
	 * Map of modules that have conflicts with plugins and should not be auto-activated
137
	 * if the plugins are active.  Used by filter_default_modules
138
	 *
139
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
140
	 * change `module-slug` and add this to your plugin:
141
	 *
142
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
143
	 * function my_jetpack_get_default_modules( $modules ) {
144
	 *     return array_diff( $modules, array( 'module-slug' ) );
145
	 * }
146
	 *
147
	 * @var array
148
	 */
149
	private $conflicting_plugins = array(
150
		'comments'          => array(
151
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
152
			'Disqus'                               => 'disqus-comment-system/disqus.php',
153
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
154
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
155
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
156
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
157
		),
158
		'comment-likes' => array(
159
			'Epoch'                                => 'epoch/plugincore.php',
160
		),
161
		'contact-form'      => array(
162
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
163
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
164
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
165
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
166
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
167
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
168
		),
169
		'minileven'         => array(
170
			'WPtouch'                              => 'wptouch/wptouch.php',
171
		),
172
		'latex'             => array(
173
			'LaTeX for WordPress'                  => 'latex/latex.php',
174
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
175
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
176
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
177
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
178
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
179
		),
180
		'protect'           => array(
181
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
182
			'Captcha'                              => 'captcha/captcha.php',
183
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
184
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
185
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
186
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
187
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
188
			'Security-protection'                  => 'security-protection/security-protection.php',
189
			'Login Security'                       => 'login-security/login-security.php',
190
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
191
			'Wordfence Security'                   => 'wordfence/wordfence.php',
192
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
193
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
194
		),
195
		'random-redirect'   => array(
196
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
197
		),
198
		'related-posts'     => array(
199
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
200
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
201
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
202
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
203
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
204
			'outbrain'                             => 'outbrain/outbrain.php',
205
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
206
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
207
		),
208
		'sharedaddy'        => array(
209
			'AddThis'                              => 'addthis/addthis_social_widget.php',
210
			'Add To Any'                           => 'add-to-any/add-to-any.php',
211
			'ShareThis'                            => 'share-this/sharethis.php',
212
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
213
		),
214
		'seo-tools' => array(
215
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'                    => 'autodescription/autodescription.php',
220
		),
221
		'verification-tools' => array(
222
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
223
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
224
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
225
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
226
			'The SEO Framework'                    => 'autodescription/autodescription.php',
227
		),
228
		'widget-visibility' => array(
229
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
230
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
231
		),
232
		'sitemaps' => array(
233
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
234
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
235
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
236
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
237
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
238
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
239
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
240
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242
			'The SEO Framework'                    => 'autodescription/autodescription.php',
243
			'Sitemap'                              => 'sitemap/sitemap.php',
244
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
245
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
246
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
247
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
248
		),
249
		'lazy-images' => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		                                                         // 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		                                                         // Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		                                                         // Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		                                                         // Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		                                                         // Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		                                                         // NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		                                                         // Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		                                                         // Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		                                                         // WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
	//	'twitter/twitter.php',                       // The official one handles this on its own.
321
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 * @var string
342
	 */
343
	public $error = '';
344
345
	/**
346
	 * Modules that need more privacy description.
347
	 * @var string
348
	 */
349
	public $privacy_checks = '';
350
351
	/**
352
	 * Stats to record once the page loads
353
	 *
354
	 * @var array
355
	 */
356
	public $stats = array();
357
358
	/**
359
	 * Jetpack_Sync object
360
	 */
361
	public $sync;
362
363
	/**
364
	 * Verified data for JSON authorization request
365
	 */
366
	public $json_api_authorization_request = array();
367
368
	/**
369
	 * @var \Automattic\Jetpack\Connection\Manager
370
	 */
371
	protected $connection_manager;
372
373
	/**
374
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
375
	 */
376
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
377
378
	/**
379
	 * Holds the singleton instance of this class
380
	 * @since 2.3.3
381
	 * @var Jetpack
382
	 */
383
	static $instance = false;
384
385
	/**
386
	 * Singleton
387
	 * @static
388
	 */
389
	public static function init() {
390
		if ( ! self::$instance ) {
391
			self::$instance = new Jetpack;
392
393
			self::$instance->plugin_upgrade();
394
		}
395
396
		return self::$instance;
397
	}
398
399
	/**
400
	 * Must never be called statically
401
	 */
402
	function plugin_upgrade() {
403
		if ( Jetpack::is_active() ) {
404
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
405
			if ( JETPACK__VERSION != $version ) {
406
				// Prevent multiple upgrades at once - only a single process should trigger
407
				// an upgrade to avoid stampedes
408
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
409
					return;
410
				}
411
412
				// Set a short lock to prevent multiple instances of the upgrade
413
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
414
415
				// check which active modules actually exist and remove others from active_modules list
416
				$unfiltered_modules = Jetpack::get_active_modules();
417
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
418
				if ( array_diff( $unfiltered_modules, $modules ) ) {
419
					Jetpack::update_active_modules( $modules );
420
				}
421
422
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
423
424
				// Upgrade to 4.3.0
425
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
426
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
427
				}
428
429
				// Make sure Markdown for posts gets turned back on
430
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
431
					update_option( 'wpcom_publish_posts_with_markdown', true );
432
				}
433
434
				if ( did_action( 'wp_loaded' ) ) {
435
					self::upgrade_on_load();
436
				} else {
437
					add_action(
438
						'wp_loaded',
439
						array( __CLASS__, 'upgrade_on_load' )
440
					);
441
				}
442
			}
443
		}
444
	}
445
446
	/**
447
	 * Runs upgrade routines that need to have modules loaded.
448
	 */
449
	static function upgrade_on_load() {
450
451
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
452
		// This can happen in case Jetpack has been just upgraded and is
453
		// being initialized late during the page load. In this case we wait
454
		// until the next proper admin page load with Jetpack active.
455
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
456
			delete_transient( self::$plugin_upgrade_lock_key );
457
458
			return;
459
		}
460
461
		Jetpack::maybe_set_version_option();
462
463
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
464
			Jetpack_Widget_Conditions::migrate_post_type_rules();
465
		}
466
467
		if (
468
			class_exists( 'Jetpack_Sitemap_Manager' )
469
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
470
		) {
471
			do_action( 'jetpack_sitemaps_purge_data' );
472
		}
473
474
		// Delete old stats cache
475
		delete_option( 'jetpack_restapi_stats_cache' );
476
477
		delete_transient( self::$plugin_upgrade_lock_key );
478
	}
479
480
	/**
481
	 * Saves all the currently active modules to options.
482
	 * Also fires Action hooks for each newly activated and deactivated module.
483
	 *
484
	 * @param $modules Array Array of active modules to be saved in options.
485
	 *
486
	 * @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...
487
	 */
488
	static function update_active_modules( $modules ) {
489
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
490
		$active_modules       = Jetpack::get_active_modules();
491
		$new_active_modules   = array_diff( $modules, $current_modules );
492
		$new_inactive_modules = array_diff( $active_modules, $modules );
493
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
494
		$reindexed_modules    = array_values( $new_current_modules );
495
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
496
497
		foreach ( $new_active_modules as $module ) {
498
			/**
499
			 * Fires when a specific module is activated.
500
			 *
501
			 * @since 1.9.0
502
			 *
503
			 * @param string $module Module slug.
504
			 * @param boolean $success whether the module was activated. @since 4.2
505
			 */
506
			do_action( 'jetpack_activate_module', $module, $success );
507
			/**
508
			 * Fires when a module is activated.
509
			 * The dynamic part of the filter, $module, is the module slug.
510
			 *
511
			 * @since 1.9.0
512
			 *
513
			 * @param string $module Module slug.
514
			 */
515
			do_action( "jetpack_activate_module_$module", $module );
516
		}
517
518
		foreach ( $new_inactive_modules as $module ) {
519
			/**
520
			 * Fired after a module has been deactivated.
521
			 *
522
			 * @since 4.2.0
523
			 *
524
			 * @param string $module Module slug.
525
			 * @param boolean $success whether the module was deactivated.
526
			 */
527
			do_action( 'jetpack_deactivate_module', $module, $success );
528
			/**
529
			 * Fires when a module is deactivated.
530
			 * The dynamic part of the filter, $module, is the module slug.
531
			 *
532
			 * @since 1.9.0
533
			 *
534
			 * @param string $module Module slug.
535
			 */
536
			do_action( "jetpack_deactivate_module_$module", $module );
537
		}
538
539
		return $success;
540
	}
541
542
	static function delete_active_modules() {
543
		self::update_active_modules( array() );
544
	}
545
546
	/**
547
	 * Constructor.  Initializes WordPress hooks
548
	 */
549
	private function __construct() {
550
		/*
551
		 * Check for and alert any deprecated hooks
552
		 */
553
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
554
555
		/*
556
		 * Enable enhanced handling of previewing sites in Calypso
557
		 */
558
		if ( Jetpack::is_active() ) {
559
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
560
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
561
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
562
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
563
		}
564
565
		if ( self::jetpack_tos_agreed() ) {
566
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
567
			add_action( 'init', array( $tracking, 'init' ) );
568
		}
569
570
571
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
572
			return function() {
573
				return wp_generate_password( 32, false );
574
			};
575
		} );
576
577
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
578
579
		$this->connection_manager = new Connection_Manager();
580
		$this->connection_manager->init();
581
582
		/*
583
		 * Load things that should only be in Network Admin.
584
		 *
585
		 * For now blow away everything else until a more full
586
		 * understanding of what is needed at the network level is
587
		 * available
588
		 */
589
		if ( is_multisite() ) {
590
			$network = Jetpack_Network::init();
591
			$network->set_connection( $this->connection_manager );
592
		}
593
594
		add_filter(
595
			'jetpack_signature_check_token',
596
			array( __CLASS__, 'verify_onboarding_token' ),
597
			10,
598
			3
599
		);
600
601
		/**
602
		 * Prepare Gutenberg Editor functionality
603
		 */
604
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
605
		Jetpack_Gutenberg::init();
606
		Jetpack_Gutenberg::load_independent_blocks();
607
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
608
609
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
610
611
		// Unlink user before deleting the user from WP.com.
612
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
613
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
614
615
		// Initialize remote file upload request handlers.
616
		$this->add_remote_request_handlers();
617
618
		if ( Jetpack::is_active() ) {
619
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
620
621
			Jetpack_Heartbeat::init();
622
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
623
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
624
				Jetpack_Search_Performance_Logger::init();
625
			}
626
		}
627
628
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
629
630
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
631
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
632
633
		add_action( 'admin_init', array( $this, 'admin_init' ) );
634
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
635
636
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
637
638
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
639
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
640
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
641
642
		// returns HTTPS support status
643
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
644
645
		// JITM AJAX callback function
646
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
647
648
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
649
650
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
651
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
652
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
653
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
654
655
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
656
657
		/**
658
		 * These actions run checks to load additional files.
659
		 * They check for external files or plugins, so they need to run as late as possible.
660
		 */
661
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
662
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
663
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
664
665
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
666
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
667
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
668
669
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
670
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
671
672
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
673
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
674
675
		// A filter to control all just in time messages
676
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
677
678
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
679
680
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
681
		// We should make sure to only do this for front end links.
682
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
683
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
684
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
685
686
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
687
			//so they point moderation links on emails to Calypso
688
			jetpack_require_lib( 'functions.wp-notify' );
689
		}
690
691
		// Hide edit post link if mobile app.
692
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
693
			add_filter( 'edit_post_link', '__return_empty_string' );
694
		}
695
696
		// Update the Jetpack plan from API on heartbeats
697
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
698
699
		/**
700
		 * This is the hack to concatenate all css files into one.
701
		 * For description and reasoning see the implode_frontend_css method
702
		 *
703
		 * Super late priority so we catch all the registered styles
704
		 */
705
		if( !is_admin() ) {
706
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
707
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
708
		}
709
710
711
		/**
712
		 * These are sync actions that we need to keep track of for jitms
713
		 */
714
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
715
716
		// Actually push the stats on shutdown.
717
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
718
			add_action( 'shutdown', array( $this, 'push_stats' ) );
719
		}
720
721
		/*
722
		 * Load some scripts asynchronously.
723
		 */
724
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
725
	}
726
727
	/**
728
	 * Sets up the XMLRPC request handlers.
729
	 *
730
	 * @deprecated since 7.7.0
731
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
732
	 *
733
	 * @param Array                 $request_params Incoming request parameters.
734
	 * @param Boolean               $is_active      Whether the connection is currently active.
735
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
736
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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...
737
	 */
738
	public function setup_xmlrpc_handlers(
739
		$request_params,
740
		$is_active,
741
		$is_signed,
742
		Jetpack_XMLRPC_Server $xmlrpc_server = null
743
	) {
744
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
745
		return $this->connection_manager->setup_xmlrpc_handlers(
746
			$request_params,
747
			$is_active,
748
			$is_signed,
749
			$xmlrpc_server
750
		);
751
	}
752
753
	/**
754
	 * Initialize REST API registration connector.
755
	 *
756
	 * @deprecated since 7.7.0
757
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
758
	 */
759
	public function initialize_rest_api_registration_connector() {
760
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
761
		$this->connection_manager->initialize_rest_api_registration_connector();
762
	}
763
764
	/**
765
	 * This is ported over from the manage module, which has been deprecated and baked in here.
766
	 *
767
	 * @param $domains
768
	 */
769
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
770
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
771
	}
772
773
	/**
774
	 * Return $domains, with 'wordpress.com' appended.
775
	 * This is ported over from the manage module, which has been deprecated and baked in here.
776
	 *
777
	 * @param $domains
778
	 * @return array
779
	 */
780
	function allow_wpcom_domain( $domains ) {
781
		if ( empty( $domains ) ) {
782
			$domains = array();
783
		}
784
		$domains[] = 'wordpress.com';
785
		return array_unique( $domains );
786
	}
787
788
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
789
		$post = get_post( $post_id );
790
791
		if ( empty( $post ) ) {
792
			return $default_url;
793
		}
794
795
		$post_type = $post->post_type;
796
797
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
798
		// https://en.support.wordpress.com/custom-post-types/
799
		$allowed_post_types = array(
800
			'post' => 'post',
801
			'page' => 'page',
802
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
803
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
804
		);
805
806
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
807
			return $default_url;
808
		}
809
810
		$path_prefix = $allowed_post_types[ $post_type ];
811
812
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
813
814
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
815
	}
816
817
	function point_edit_comment_links_to_calypso( $url ) {
818
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
819
		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...
820
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
821
			Jetpack::build_raw_urls( get_home_url() ),
822
			$query_args['amp;c']
823
		) );
824
	}
825
826
	function jetpack_track_last_sync_callback( $params ) {
827
		/**
828
		 * Filter to turn off jitm caching
829
		 *
830
		 * @since 5.4.0
831
		 *
832
		 * @param bool false Whether to cache just in time messages
833
		 */
834
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
835
			return $params;
836
		}
837
838
		if ( is_array( $params ) && isset( $params[0] ) ) {
839
			$option = $params[0];
840
			if ( 'active_plugins' === $option ) {
841
				// use the cache if we can, but not terribly important if it gets evicted
842
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
843
			}
844
		}
845
846
		return $params;
847
	}
848
849
	function jetpack_connection_banner_callback() {
850
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
851
852
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
853
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
854
			wp_send_json_success();
855
		}
856
857
		wp_die();
858
	}
859
860
	/**
861
	 * Removes all XML-RPC methods that are not `jetpack.*`.
862
	 * Only used in our alternate XML-RPC endpoint, where we want to
863
	 * ensure that Core and other plugins' methods are not exposed.
864
	 *
865
	 * @deprecated since 7.7.0
866
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
867
	 *
868
	 * @param array $methods A list of registered WordPress XMLRPC methods.
869
	 * @return array Filtered $methods
870
	 */
871
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
872
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
873
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
874
	}
875
876
	/**
877
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
878
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
879
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
880
	 * which is accessible via a different URI. Most of the below is copied directly
881
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
882
	 *
883
	 * @deprecated since 7.7.0
884
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
885
	 */
886
	public function alternate_xmlrpc() {
887
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
888
		$this->connection_manager->alternate_xmlrpc();
889
	}
890
891
	/**
892
	 * The callback for the JITM ajax requests.
893
	 */
894
	function jetpack_jitm_ajax_callback() {
895
		// Check for nonce
896
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
897
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
898
		}
899
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
900
			$module_slug = $_REQUEST['jitmModule'];
901
			Jetpack::log( 'activate', $module_slug );
902
			Jetpack::activate_module( $module_slug, false, false );
903
			Jetpack::state( 'message', 'no_message' );
904
905
			//A Jetpack module is being activated through a JITM, track it
906
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
907
			$this->do_stats( 'server_side' );
908
909
			wp_send_json_success();
910
		}
911
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
912
			// get the hide_jitm options array
913
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
914
			$module_slug = $_REQUEST['jitmModule'];
915
916
			if( ! $jetpack_hide_jitm ) {
917
				$jetpack_hide_jitm = array(
918
					$module_slug => 'hide'
919
				);
920
			} else {
921
				$jetpack_hide_jitm[$module_slug] = 'hide';
922
			}
923
924
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
925
926
			//jitm is being dismissed forever, track it
927
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
928
			$this->do_stats( 'server_side' );
929
930
			wp_send_json_success();
931
		}
932 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
933
			$module_slug = $_REQUEST['jitmModule'];
934
935
			// User went to WordPress.com, track this
936
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
937
			$this->do_stats( 'server_side' );
938
939
			wp_send_json_success();
940
		}
941 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
942
			$track = $_REQUEST['jitmModule'];
943
944
			// User is viewing JITM, track it.
945
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
946
			$this->do_stats( 'server_side' );
947
948
			wp_send_json_success();
949
		}
950
	}
951
952
	/**
953
	 * If there are any stats that need to be pushed, but haven't been, push them now.
954
	 */
955
	function push_stats() {
956
		if ( ! empty( $this->stats ) ) {
957
			$this->do_stats( 'server_side' );
958
		}
959
	}
960
961
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
962
		switch( $cap ) {
963
			case 'jetpack_connect' :
964
			case 'jetpack_reconnect' :
965
				if ( Jetpack::is_development_mode() ) {
966
					$caps = array( 'do_not_allow' );
967
					break;
968
				}
969
				/**
970
				 * Pass through. If it's not development mode, these should match disconnect.
971
				 * Let users disconnect if it's development mode, just in case things glitch.
972
				 */
973
			case 'jetpack_disconnect' :
974
				/**
975
				 * In multisite, can individual site admins manage their own connection?
976
				 *
977
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
978
				 */
979
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
980
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
981
						/**
982
						 * We need to update the option name -- it's terribly unclear which
983
						 * direction the override goes.
984
						 *
985
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
986
						 */
987
						$caps = array( 'do_not_allow' );
988
						break;
989
					}
990
				}
991
992
				$caps = array( 'manage_options' );
993
				break;
994
			case 'jetpack_manage_modules' :
995
			case 'jetpack_activate_modules' :
996
			case 'jetpack_deactivate_modules' :
997
				$caps = array( 'manage_options' );
998
				break;
999
			case 'jetpack_configure_modules' :
1000
				$caps = array( 'manage_options' );
1001
				break;
1002
			case 'jetpack_manage_autoupdates' :
1003
				$caps = array(
1004
					'manage_options',
1005
					'update_plugins',
1006
				);
1007
				break;
1008
			case 'jetpack_network_admin_page':
1009
			case 'jetpack_network_settings_page':
1010
				$caps = array( 'manage_network_plugins' );
1011
				break;
1012
			case 'jetpack_network_sites_page':
1013
				$caps = array( 'manage_sites' );
1014
				break;
1015
			case 'jetpack_admin_page' :
1016
				if ( Jetpack::is_development_mode() ) {
1017
					$caps = array( 'manage_options' );
1018
					break;
1019
				} else {
1020
					$caps = array( 'read' );
1021
				}
1022
				break;
1023
			case 'jetpack_connect_user' :
1024
				if ( Jetpack::is_development_mode() ) {
1025
					$caps = array( 'do_not_allow' );
1026
					break;
1027
				}
1028
				$caps = array( 'read' );
1029
				break;
1030
		}
1031
		return $caps;
1032
	}
1033
1034
	/**
1035
	 * Require a Jetpack authentication.
1036
	 *
1037
	 * @deprecated since 7.7.0
1038
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1039
	 */
1040
	public function require_jetpack_authentication() {
1041
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1042
		$this->connection_manager->require_jetpack_authentication();
1043
	}
1044
1045
	/**
1046
	 * Load language files
1047
	 * @action plugins_loaded
1048
	 */
1049
	public static function plugin_textdomain() {
1050
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1051
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1052
	}
1053
1054
	/**
1055
	 * Register assets for use in various modules and the Jetpack admin page.
1056
	 *
1057
	 * @uses wp_script_is, wp_register_script, plugins_url
1058
	 * @action wp_loaded
1059
	 * @return null
1060
	 */
1061
	public function register_assets() {
1062
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1063
			wp_register_script(
1064
				'spin',
1065
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1066
				false,
1067
				'1.3'
1068
			);
1069
		}
1070
1071 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1072
			wp_register_script(
1073
				'jquery.spin',
1074
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1075
				array( 'jquery', 'spin' ),
1076
				'1.3'
1077
			);
1078
		}
1079
1080 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1081
			wp_register_script(
1082
				'jetpack-gallery-settings',
1083
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1084
				array( 'media-views' ),
1085
				'20121225'
1086
			);
1087
		}
1088
1089 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1090
			wp_register_script(
1091
				'jetpack-twitter-timeline',
1092
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1093
				array( 'jquery' ),
1094
				'4.0.0',
1095
				true
1096
			);
1097
		}
1098
1099
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1100
			wp_register_script(
1101
				'jetpack-facebook-embed',
1102
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1103
				array( 'jquery' ),
1104
				null,
1105
				true
1106
			);
1107
1108
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1109
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1110
			if ( ! is_numeric( $fb_app_id ) ) {
1111
				$fb_app_id = '';
1112
			}
1113
			wp_localize_script(
1114
				'jetpack-facebook-embed',
1115
				'jpfbembed',
1116
				array(
1117
					'appid' => $fb_app_id,
1118
					'locale' => $this->get_locale(),
1119
				)
1120
			);
1121
		}
1122
1123
		/**
1124
		 * As jetpack_register_genericons is by default fired off a hook,
1125
		 * the hook may have already fired by this point.
1126
		 * So, let's just trigger it manually.
1127
		 */
1128
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1129
		jetpack_register_genericons();
1130
1131
		/**
1132
		 * Register the social logos
1133
		 */
1134
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1135
		jetpack_register_social_logos();
1136
1137 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1138
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1139
	}
1140
1141
	/**
1142
	 * Guess locale from language code.
1143
	 *
1144
	 * @param string $lang Language code.
1145
	 * @return string|bool
1146
	 */
1147 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1148
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1149
			return 'en_US';
1150
		}
1151
1152
		if ( ! class_exists( 'GP_Locales' ) ) {
1153
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1154
				return false;
1155
			}
1156
1157
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1158
		}
1159
1160
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1161
			// WP.com: get_locale() returns 'it'
1162
			$locale = GP_Locales::by_slug( $lang );
1163
		} else {
1164
			// Jetpack: get_locale() returns 'it_IT';
1165
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1166
		}
1167
1168
		if ( ! $locale ) {
1169
			return false;
1170
		}
1171
1172
		if ( empty( $locale->facebook_locale ) ) {
1173
			if ( empty( $locale->wp_locale ) ) {
1174
				return false;
1175
			} else {
1176
				// Facebook SDK is smart enough to fall back to en_US if a
1177
				// locale isn't supported. Since supported Facebook locales
1178
				// can fall out of sync, we'll attempt to use the known
1179
				// wp_locale value and rely on said fallback.
1180
				return $locale->wp_locale;
1181
			}
1182
		}
1183
1184
		return $locale->facebook_locale;
1185
	}
1186
1187
	/**
1188
	 * Get the locale.
1189
	 *
1190
	 * @return string|bool
1191
	 */
1192
	function get_locale() {
1193
		$locale = $this->guess_locale_from_lang( get_locale() );
1194
1195
		if ( ! $locale ) {
1196
			$locale = 'en_US';
1197
		}
1198
1199
		return $locale;
1200
	}
1201
1202
	/**
1203
	 * Device Pixels support
1204
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1205
	 */
1206
	function devicepx() {
1207
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1208
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1209
		}
1210
	}
1211
1212
	/**
1213
	 * Return the network_site_url so that .com knows what network this site is a part of.
1214
	 * @param  bool $option
1215
	 * @return string
1216
	 */
1217
	public function jetpack_main_network_site_option( $option ) {
1218
		return network_site_url();
1219
	}
1220
	/**
1221
	 * Network Name.
1222
	 */
1223
	static function network_name( $option = null ) {
1224
		global $current_site;
1225
		return $current_site->site_name;
1226
	}
1227
	/**
1228
	 * Does the network allow new user and site registrations.
1229
	 * @return string
1230
	 */
1231
	static function network_allow_new_registrations( $option = null ) {
1232
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1233
	}
1234
	/**
1235
	 * Does the network allow admins to add new users.
1236
	 * @return boolian
1237
	 */
1238
	static function network_add_new_users( $option = null ) {
1239
		return (bool) get_site_option( 'add_new_users' );
1240
	}
1241
	/**
1242
	 * File upload psace left per site in MB.
1243
	 *  -1 means NO LIMIT.
1244
	 * @return number
1245
	 */
1246
	static function network_site_upload_space( $option = null ) {
1247
		// value in MB
1248
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1249
	}
1250
1251
	/**
1252
	 * Network allowed file types.
1253
	 * @return string
1254
	 */
1255
	static function network_upload_file_types( $option = null ) {
1256
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1257
	}
1258
1259
	/**
1260
	 * Maximum file upload size set by the network.
1261
	 * @return number
1262
	 */
1263
	static function network_max_upload_file_size( $option = null ) {
1264
		// value in KB
1265
		return get_site_option( 'fileupload_maxk', 300 );
1266
	}
1267
1268
	/**
1269
	 * Lets us know if a site allows admins to manage the network.
1270
	 * @return array
1271
	 */
1272
	static function network_enable_administration_menus( $option = null ) {
1273
		return get_site_option( 'menu_items' );
1274
	}
1275
1276
	/**
1277
	 * If a user has been promoted to or demoted from admin, we need to clear the
1278
	 * jetpack_other_linked_admins transient.
1279
	 *
1280
	 * @since 4.3.2
1281
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1282
	 *
1283
	 * @param int    $user_id   The user ID whose role changed.
1284
	 * @param string $role      The new role.
1285
	 * @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...
1286
	 */
1287
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1288
		if ( 'administrator' == $role
1289
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1290
			|| is_null( $old_roles )
1291
		) {
1292
			delete_transient( 'jetpack_other_linked_admins' );
1293
		}
1294
	}
1295
1296
	/**
1297
	 * Checks to see if there are any other users available to become primary
1298
	 * Users must both:
1299
	 * - Be linked to wpcom
1300
	 * - Be an admin
1301
	 *
1302
	 * @return mixed False if no other users are linked, Int if there are.
1303
	 */
1304
	static function get_other_linked_admins() {
1305
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1306
1307
		if ( false === $other_linked_users ) {
1308
			$admins = get_users( array( 'role' => 'administrator' ) );
1309
			if ( count( $admins ) > 1 ) {
1310
				$available = array();
1311
				foreach ( $admins as $admin ) {
1312
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1313
						$available[] = $admin->ID;
1314
					}
1315
				}
1316
1317
				$count_connected_admins = count( $available );
1318
				if ( count( $available ) > 1 ) {
1319
					$other_linked_users = $count_connected_admins;
1320
				} else {
1321
					$other_linked_users = 0;
1322
				}
1323
			} else {
1324
				$other_linked_users = 0;
1325
			}
1326
1327
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1328
		}
1329
1330
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1331
	}
1332
1333
	/**
1334
	 * Return whether we are dealing with a multi network setup or not.
1335
	 * The reason we are type casting this is because we want to avoid the situation where
1336
	 * the result is false since when is_main_network_option return false it cases
1337
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1338
	 * database which could be set to anything as opposed to what this function returns.
1339
	 * @param  bool  $option
1340
	 *
1341
	 * @return boolean
1342
	 */
1343
	public function is_main_network_option( $option ) {
1344
		// return '1' or ''
1345
		return (string) (bool) Jetpack::is_multi_network();
1346
	}
1347
1348
	/**
1349
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1350
	 *
1351
	 * @param  string  $option
1352
	 * @return boolean
1353
	 */
1354
	public function is_multisite( $option ) {
1355
		return (string) (bool) is_multisite();
1356
	}
1357
1358
	/**
1359
	 * Implemented since there is no core is multi network function
1360
	 * Right now there is no way to tell if we which network is the dominant network on the system
1361
	 *
1362
	 * @since  3.3
1363
	 * @return boolean
1364
	 */
1365 View Code Duplication
	public static function is_multi_network() {
1366
		global  $wpdb;
1367
1368
		// if we don't have a multi site setup no need to do any more
1369
		if ( ! is_multisite() ) {
1370
			return false;
1371
		}
1372
1373
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1374
		if ( $num_sites > 1 ) {
1375
			return true;
1376
		} else {
1377
			return false;
1378
		}
1379
	}
1380
1381
	/**
1382
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1383
	 * @return null
1384
	 */
1385
	function update_jetpack_main_network_site_option() {
1386
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1387
	}
1388
	/**
1389
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1390
	 *
1391
	 */
1392
	function update_jetpack_network_settings() {
1393
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1394
		// Only sync this info for the main network site.
1395
	}
1396
1397
	/**
1398
	 * Get back if the current site is single user site.
1399
	 *
1400
	 * @return bool
1401
	 */
1402 View Code Duplication
	public static function is_single_user_site() {
1403
		global $wpdb;
1404
1405
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1406
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1407
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1408
		}
1409
		return 1 === (int) $some_users;
1410
	}
1411
1412
	/**
1413
	 * Returns true if the site has file write access false otherwise.
1414
	 * @return string ( '1' | '0' )
1415
	 **/
1416
	public static function file_system_write_access() {
1417
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1418
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1419
		}
1420
1421
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1422
1423
		$filesystem_method = get_filesystem_method();
1424
		if ( $filesystem_method === 'direct' ) {
1425
			return 1;
1426
		}
1427
1428
		ob_start();
1429
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1430
		ob_end_clean();
1431
		if ( $filesystem_credentials_are_stored ) {
1432
			return 1;
1433
		}
1434
		return 0;
1435
	}
1436
1437
	/**
1438
	 * Finds out if a site is using a version control system.
1439
	 * @return string ( '1' | '0' )
1440
	 **/
1441
	public static function is_version_controlled() {
1442
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1443
		return (string) (int) Functions::is_version_controlled();
1444
	}
1445
1446
	/**
1447
	 * Determines whether the current theme supports featured images or not.
1448
	 * @return string ( '1' | '0' )
1449
	 */
1450
	public static function featured_images_enabled() {
1451
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1452
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1453
	}
1454
1455
	/**
1456
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1457
	 *
1458
	 * @deprecated 4.7 use get_avatar_url instead.
1459
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1460
	 * @param int $size Size of the avatar image
1461
	 * @param string $default URL to a default image to use if no avatar is available
1462
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1463
	 *
1464
	 * @return array
1465
	 */
1466
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1467
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1468
		return get_avatar_url( $id_or_email, array(
1469
			'size' => $size,
1470
			'default' => $default,
1471
			'force_default' => $force_display,
1472
		) );
1473
	}
1474
1475
	/**
1476
	 * jetpack_updates is saved in the following schema:
1477
	 *
1478
	 * array (
1479
	 *      'plugins'                       => (int) Number of plugin updates available.
1480
	 *      'themes'                        => (int) Number of theme updates available.
1481
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1482
	 *      'translations'                  => (int) Number of translation updates available.
1483
	 *      'total'                         => (int) Total of all available updates.
1484
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1485
	 * )
1486
	 * @return array
1487
	 */
1488
	public static function get_updates() {
1489
		$update_data = wp_get_update_data();
1490
1491
		// Stores the individual update counts as well as the total count.
1492
		if ( isset( $update_data['counts'] ) ) {
1493
			$updates = $update_data['counts'];
1494
		}
1495
1496
		// If we need to update WordPress core, let's find the latest version number.
1497 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1498
			$cur = get_preferred_from_update_core();
1499
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1500
				$updates['wp_update_version'] = $cur->current;
1501
			}
1502
		}
1503
		return isset( $updates ) ? $updates : array();
1504
	}
1505
1506
	public static function get_update_details() {
1507
		$update_details = array(
1508
			'update_core' => get_site_transient( 'update_core' ),
1509
			'update_plugins' => get_site_transient( 'update_plugins' ),
1510
			'update_themes' => get_site_transient( 'update_themes' ),
1511
		);
1512
		return $update_details;
1513
	}
1514
1515
	public static function refresh_update_data() {
1516
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1517
1518
	}
1519
1520
	public static function refresh_theme_data() {
1521
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1522
	}
1523
1524
	/**
1525
	 * Is Jetpack active?
1526
	 */
1527
	public static function is_active() {
1528
		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...
1529
	}
1530
1531
	/**
1532
	 * Make an API call to WordPress.com for plan status
1533
	 *
1534
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1535
	 *
1536
	 * @return bool True if plan is updated, false if no update
1537
	 */
1538
	public static function refresh_active_plan_from_wpcom() {
1539
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1540
		return Jetpack_Plan::refresh_from_wpcom();
1541
	}
1542
1543
	/**
1544
	 * Get the plan that this Jetpack site is currently using
1545
	 *
1546
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1547
	 * @return array Active Jetpack plan details.
1548
	 */
1549
	public static function get_active_plan() {
1550
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1551
		return Jetpack_Plan::get();
1552
	}
1553
1554
	/**
1555
	 * Determine whether the active plan supports a particular feature
1556
	 *
1557
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1558
	 * @return bool True if plan supports feature, false if not.
1559
	 */
1560
	public static function active_plan_supports( $feature ) {
1561
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1562
		return Jetpack_Plan::supports( $feature );
1563
	}
1564
1565
	/**
1566
	 * Is Jetpack in development (offline) mode?
1567
	 */
1568 View Code Duplication
	public static function is_development_mode() {
1569
		$development_mode = false;
1570
1571
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1572
			$development_mode = JETPACK_DEV_DEBUG;
1573
		} elseif ( $site_url = site_url() ) {
1574
			$development_mode = false === strpos( $site_url, '.' );
1575
		}
1576
1577
		/**
1578
		 * Filters Jetpack's development mode.
1579
		 *
1580
		 * @see https://jetpack.com/support/development-mode/
1581
		 *
1582
		 * @since 2.2.1
1583
		 *
1584
		 * @param bool $development_mode Is Jetpack's development mode active.
1585
		 */
1586
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1587
		return $development_mode;
1588
	}
1589
1590
	/**
1591
	 * Whether the site is currently onboarding or not.
1592
	 * A site is considered as being onboarded if it currently has an onboarding token.
1593
	 *
1594
	 * @since 5.8
1595
	 *
1596
	 * @access public
1597
	 * @static
1598
	 *
1599
	 * @return bool True if the site is currently onboarding, false otherwise
1600
	 */
1601
	public static function is_onboarding() {
1602
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1603
	}
1604
1605
	/**
1606
	 * Determines reason for Jetpack development mode.
1607
	 */
1608
	public static function development_mode_trigger_text() {
1609
		if ( ! Jetpack::is_development_mode() ) {
1610
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1611
		}
1612
1613
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1614
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1615
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1616
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1617
		} else {
1618
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1619
		}
1620
1621
		return $notice;
1622
1623
	}
1624
	/**
1625
	* Get Jetpack development mode notice text and notice class.
1626
	*
1627
	* Mirrors the checks made in Jetpack::is_development_mode
1628
	*
1629
	*/
1630
	public static function show_development_mode_notice() {
1631 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1632
			$notice = sprintf(
1633
			/* translators: %s is a URL */
1634
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1635
				'https://jetpack.com/support/development-mode/'
1636
			);
1637
1638
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1639
1640
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1641
		}
1642
1643
		// Throw up a notice if using a development version and as for feedback.
1644
		if ( Jetpack::is_development_version() ) {
1645
			/* translators: %s is a URL */
1646
			$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/' );
1647
1648
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1649
		}
1650
		// Throw up a notice if using staging mode
1651
		if ( Jetpack::is_staging_site() ) {
1652
			/* translators: %s is a URL */
1653
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1654
1655
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1656
		}
1657
	}
1658
1659
	/**
1660
	 * Whether Jetpack's version maps to a public release, or a development version.
1661
	 */
1662
	public static function is_development_version() {
1663
		/**
1664
		 * Allows filtering whether this is a development version of Jetpack.
1665
		 *
1666
		 * This filter is especially useful for tests.
1667
		 *
1668
		 * @since 4.3.0
1669
		 *
1670
		 * @param bool $development_version Is this a develoment version of Jetpack?
1671
		 */
1672
		return (bool) apply_filters(
1673
			'jetpack_development_version',
1674
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1675
		);
1676
	}
1677
1678
	/**
1679
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1680
	 */
1681
	public static function is_user_connected( $user_id = false ) {
1682
		return self::connection()->is_user_connected( $user_id );
1683
	}
1684
1685
	/**
1686
	 * Get the wpcom user data of the current|specified connected user.
1687
	 */
1688 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1689
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1690
		if ( ! $user_id ) {
1691
			$user_id = get_current_user_id();
1692
		}
1693
1694
		$transient_key = "jetpack_connected_user_data_$user_id";
1695
1696
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1697
			return $cached_user_data;
1698
		}
1699
1700
		$xml = new Jetpack_IXR_Client( array(
1701
			'user_id' => $user_id,
1702
		) );
1703
		$xml->query( 'wpcom.getUser' );
1704
		if ( ! $xml->isError() ) {
1705
			$user_data = $xml->getResponse();
1706
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1707
			return $user_data;
1708
		}
1709
1710
		return false;
1711
	}
1712
1713
	/**
1714
	 * Get the wpcom email of the current|specified connected user.
1715
	 */
1716
	public static function get_connected_user_email( $user_id = null ) {
1717
		if ( ! $user_id ) {
1718
			$user_id = get_current_user_id();
1719
		}
1720
1721
		$xml = new Jetpack_IXR_Client( array(
1722
			'user_id' => $user_id,
1723
		) );
1724
		$xml->query( 'wpcom.getUserEmail' );
1725
		if ( ! $xml->isError() ) {
1726
			return $xml->getResponse();
1727
		}
1728
		return false;
1729
	}
1730
1731
	/**
1732
	 * Get the wpcom email of the master user.
1733
	 */
1734
	public static function get_master_user_email() {
1735
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1736
		if ( $master_user_id ) {
1737
			return self::get_connected_user_email( $master_user_id );
1738
		}
1739
		return '';
1740
	}
1741
1742
	/**
1743
	 * Whether the current user is the connection owner.
1744
	 *
1745
	 * @deprecated since 7.7
1746
	 *
1747
	 * @return bool Whether the current user is the connection owner.
1748
	 */
1749
	public function current_user_is_connection_owner() {
1750
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1751
		return self::connection()->is_connection_owner();
1752
	}
1753
1754
	/**
1755
	 * Gets current user IP address.
1756
	 *
1757
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1758
	 *
1759
	 * @return string                  Current user IP address.
1760
	 */
1761
	public static function current_user_ip( $check_all_headers = false ) {
1762
		if ( $check_all_headers ) {
1763
			foreach ( array(
1764
				'HTTP_CF_CONNECTING_IP',
1765
				'HTTP_CLIENT_IP',
1766
				'HTTP_X_FORWARDED_FOR',
1767
				'HTTP_X_FORWARDED',
1768
				'HTTP_X_CLUSTER_CLIENT_IP',
1769
				'HTTP_FORWARDED_FOR',
1770
				'HTTP_FORWARDED',
1771
				'HTTP_VIA',
1772
			) as $key ) {
1773
				if ( ! empty( $_SERVER[ $key ] ) ) {
1774
					return $_SERVER[ $key ];
1775
				}
1776
			}
1777
		}
1778
1779
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1780
	}
1781
1782
	/**
1783
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1784
	 */
1785
	function extra_oembed_providers() {
1786
		// Cloudup: https://dev.cloudup.com/#oembed
1787
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1788
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1789
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1790
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1791
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1792
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1793
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1794
	}
1795
1796
	/**
1797
	 * Synchronize connected user role changes
1798
	 */
1799
	function user_role_change( $user_id ) {
1800
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1801
		Users::user_role_change( $user_id );
1802
	}
1803
1804
	/**
1805
	 * Loads the currently active modules.
1806
	 */
1807
	public static function load_modules() {
1808
		if (
1809
			! self::is_active()
1810
			&& ! self::is_development_mode()
1811
			&& ! self::is_onboarding()
1812
			&& (
1813
				! is_multisite()
1814
				|| ! get_site_option( 'jetpack_protect_active' )
1815
			)
1816
		) {
1817
			return;
1818
		}
1819
1820
		$version = Jetpack_Options::get_option( 'version' );
1821 View Code Duplication
		if ( ! $version ) {
1822
			$version = $old_version = JETPACK__VERSION . ':' . time();
1823
			/** This action is documented in class.jetpack.php */
1824
			do_action( 'updating_jetpack_version', $version, false );
1825
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1826
		}
1827
		list( $version ) = explode( ':', $version );
1828
1829
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1830
1831
		$modules_data = array();
1832
1833
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1834
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1835
			$updated_modules = array();
1836
			foreach ( $modules as $module ) {
1837
				$modules_data[ $module ] = Jetpack::get_module( $module );
1838
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1839
					continue;
1840
				}
1841
1842
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1843
					continue;
1844
				}
1845
1846
				$updated_modules[] = $module;
1847
			}
1848
1849
			$modules = array_diff( $modules, $updated_modules );
1850
		}
1851
1852
		$is_development_mode = Jetpack::is_development_mode();
1853
1854
		foreach ( $modules as $index => $module ) {
1855
			// If we're in dev mode, disable modules requiring a connection
1856
			if ( $is_development_mode ) {
1857
				// Prime the pump if we need to
1858
				if ( empty( $modules_data[ $module ] ) ) {
1859
					$modules_data[ $module ] = Jetpack::get_module( $module );
1860
				}
1861
				// If the module requires a connection, but we're in local mode, don't include it.
1862
				if ( $modules_data[ $module ]['requires_connection'] ) {
1863
					continue;
1864
				}
1865
			}
1866
1867
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1868
				continue;
1869
			}
1870
1871
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1872
				unset( $modules[ $index ] );
1873
				self::update_active_modules( array_values( $modules ) );
1874
				continue;
1875
			}
1876
1877
			/**
1878
			 * Fires when a specific module is loaded.
1879
			 * The dynamic part of the hook, $module, is the module slug.
1880
			 *
1881
			 * @since 1.1.0
1882
			 */
1883
			do_action( 'jetpack_module_loaded_' . $module );
1884
		}
1885
1886
		/**
1887
		 * Fires when all the modules are loaded.
1888
		 *
1889
		 * @since 1.1.0
1890
		 */
1891
		do_action( 'jetpack_modules_loaded' );
1892
1893
		// 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.
1894
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1895
	}
1896
1897
	/**
1898
	 * Check if Jetpack's REST API compat file should be included
1899
	 * @action plugins_loaded
1900
	 * @return null
1901
	 */
1902
	public function check_rest_api_compat() {
1903
		/**
1904
		 * Filters the list of REST API compat files to be included.
1905
		 *
1906
		 * @since 2.2.5
1907
		 *
1908
		 * @param array $args Array of REST API compat files to include.
1909
		 */
1910
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1911
1912
		if ( function_exists( 'bbpress' ) )
1913
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1914
1915
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1916
			require_once $_jetpack_rest_api_compat_include;
1917
	}
1918
1919
	/**
1920
	 * Gets all plugins currently active in values, regardless of whether they're
1921
	 * traditionally activated or network activated.
1922
	 *
1923
	 * @todo Store the result in core's object cache maybe?
1924
	 */
1925
	public static function get_active_plugins() {
1926
		$active_plugins = (array) get_option( 'active_plugins', array() );
1927
1928
		if ( is_multisite() ) {
1929
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1930
			// whereas active_plugins stores them in the values.
1931
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1932
			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...
1933
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1934
			}
1935
		}
1936
1937
		sort( $active_plugins );
1938
1939
		return array_unique( $active_plugins );
1940
	}
1941
1942
	/**
1943
	 * Gets and parses additional plugin data to send with the heartbeat data
1944
	 *
1945
	 * @since 3.8.1
1946
	 *
1947
	 * @return array Array of plugin data
1948
	 */
1949
	public static function get_parsed_plugin_data() {
1950
		if ( ! function_exists( 'get_plugins' ) ) {
1951
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1952
		}
1953
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1954
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1955
		$active_plugins = Jetpack::get_active_plugins();
1956
1957
		$plugins = array();
1958
		foreach ( $all_plugins as $path => $plugin_data ) {
1959
			$plugins[ $path ] = array(
1960
					'is_active' => in_array( $path, $active_plugins ),
1961
					'file'      => $path,
1962
					'name'      => $plugin_data['Name'],
1963
					'version'   => $plugin_data['Version'],
1964
					'author'    => $plugin_data['Author'],
1965
			);
1966
		}
1967
1968
		return $plugins;
1969
	}
1970
1971
	/**
1972
	 * Gets and parses theme data to send with the heartbeat data
1973
	 *
1974
	 * @since 3.8.1
1975
	 *
1976
	 * @return array Array of theme data
1977
	 */
1978
	public static function get_parsed_theme_data() {
1979
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1980
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1981
1982
		$themes = array();
1983
		foreach ( $all_themes as $slug => $theme_data ) {
1984
			$theme_headers = array();
1985
			foreach ( $header_keys as $header_key ) {
1986
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1987
			}
1988
1989
			$themes[ $slug ] = array(
1990
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1991
					'slug' => $slug,
1992
					'theme_root' => $theme_data->get_theme_root_uri(),
1993
					'parent' => $theme_data->parent(),
1994
					'headers' => $theme_headers
1995
			);
1996
		}
1997
1998
		return $themes;
1999
	}
2000
2001
	/**
2002
	 * Checks whether a specific plugin is active.
2003
	 *
2004
	 * We don't want to store these in a static variable, in case
2005
	 * there are switch_to_blog() calls involved.
2006
	 */
2007
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2008
		return in_array( $plugin, self::get_active_plugins() );
2009
	}
2010
2011
	/**
2012
	 * Check if Jetpack's Open Graph tags should be used.
2013
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2014
	 *
2015
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2016
	 * @action plugins_loaded
2017
	 * @return null
2018
	 */
2019
	public function check_open_graph() {
2020
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2021
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2022
		}
2023
2024
		$active_plugins = self::get_active_plugins();
2025
2026
		if ( ! empty( $active_plugins ) ) {
2027
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2028
				if ( in_array( $plugin, $active_plugins ) ) {
2029
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2030
					break;
2031
				}
2032
			}
2033
		}
2034
2035
		/**
2036
		 * Allow the addition of Open Graph Meta Tags to all pages.
2037
		 *
2038
		 * @since 2.0.3
2039
		 *
2040
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2041
		 */
2042
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2043
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2044
		}
2045
	}
2046
2047
	/**
2048
	 * Check if Jetpack's Twitter tags should be used.
2049
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2050
	 *
2051
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2052
	 * @action plugins_loaded
2053
	 * @return null
2054
	 */
2055
	public function check_twitter_tags() {
2056
2057
		$active_plugins = self::get_active_plugins();
2058
2059
		if ( ! empty( $active_plugins ) ) {
2060
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2061
				if ( in_array( $plugin, $active_plugins ) ) {
2062
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2063
					break;
2064
				}
2065
			}
2066
		}
2067
2068
		/**
2069
		 * Allow Twitter Card Meta tags to be disabled.
2070
		 *
2071
		 * @since 2.6.0
2072
		 *
2073
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2074
		 */
2075
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2076
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2077
		}
2078
	}
2079
2080
	/**
2081
	 * Allows plugins to submit security reports.
2082
 	 *
2083
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2084
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2085
	 * @param array   $args         See definitions above
2086
	 */
2087
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2088
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2089
	}
2090
2091
/* Jetpack Options API */
2092
2093
	public static function get_option_names( $type = 'compact' ) {
2094
		return Jetpack_Options::get_option_names( $type );
2095
	}
2096
2097
	/**
2098
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2099
 	 *
2100
	 * @param string $name    Option name
2101
	 * @param mixed  $default (optional)
2102
	 */
2103
	public static function get_option( $name, $default = false ) {
2104
		return Jetpack_Options::get_option( $name, $default );
2105
	}
2106
2107
	/**
2108
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2109
 	 *
2110
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2111
	 * @param string $name  Option name
2112
	 * @param mixed  $value Option value
2113
	 */
2114
	public static function update_option( $name, $value ) {
2115
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2116
		return Jetpack_Options::update_option( $name, $value );
2117
	}
2118
2119
	/**
2120
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2121
 	 *
2122
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2123
	 * @param array $array array( option name => option value, ... )
2124
	 */
2125
	public static function update_options( $array ) {
2126
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2127
		return Jetpack_Options::update_options( $array );
2128
	}
2129
2130
	/**
2131
	 * Deletes the given option.  May be passed multiple option names as an array.
2132
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2133
	 *
2134
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2135
	 * @param string|array $names
2136
	 */
2137
	public static function delete_option( $names ) {
2138
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2139
		return Jetpack_Options::delete_option( $names );
2140
	}
2141
2142
	/**
2143
	 * Enters a user token into the user_tokens option
2144
	 *
2145
	 * @param int $user_id
2146
	 * @param string $token
2147
	 * return bool
2148
	 */
2149
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2150
		// not designed for concurrent updates
2151
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2152
		if ( ! is_array( $user_tokens ) )
2153
			$user_tokens = array();
2154
		$user_tokens[$user_id] = $token;
2155
		if ( $is_master_user ) {
2156
			$master_user = $user_id;
2157
			$options     = compact( 'user_tokens', 'master_user' );
2158
		} else {
2159
			$options = compact( 'user_tokens' );
2160
		}
2161
		return Jetpack_Options::update_options( $options );
2162
	}
2163
2164
	/**
2165
	 * Returns an array of all PHP files in the specified absolute path.
2166
	 * Equivalent to glob( "$absolute_path/*.php" ).
2167
	 *
2168
	 * @param string $absolute_path The absolute path of the directory to search.
2169
	 * @return array Array of absolute paths to the PHP files.
2170
	 */
2171
	public static function glob_php( $absolute_path ) {
2172
		if ( function_exists( 'glob' ) ) {
2173
			return glob( "$absolute_path/*.php" );
2174
		}
2175
2176
		$absolute_path = untrailingslashit( $absolute_path );
2177
		$files = array();
2178
		if ( ! $dir = @opendir( $absolute_path ) ) {
2179
			return $files;
2180
		}
2181
2182
		while ( false !== $file = readdir( $dir ) ) {
2183
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2184
				continue;
2185
			}
2186
2187
			$file = "$absolute_path/$file";
2188
2189
			if ( ! is_file( $file ) ) {
2190
				continue;
2191
			}
2192
2193
			$files[] = $file;
2194
		}
2195
2196
		closedir( $dir );
2197
2198
		return $files;
2199
	}
2200
2201
	public static function activate_new_modules( $redirect = false ) {
2202
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2203
			return;
2204
		}
2205
2206
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2207 View Code Duplication
		if ( ! $jetpack_old_version ) {
2208
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2209
			/** This action is documented in class.jetpack.php */
2210
			do_action( 'updating_jetpack_version', $version, false );
2211
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2212
		}
2213
2214
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2215
2216
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2217
			return;
2218
		}
2219
2220
		$active_modules     = Jetpack::get_active_modules();
2221
		$reactivate_modules = array();
2222
		foreach ( $active_modules as $active_module ) {
2223
			$module = Jetpack::get_module( $active_module );
2224
			if ( ! isset( $module['changed'] ) ) {
2225
				continue;
2226
			}
2227
2228
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2229
				continue;
2230
			}
2231
2232
			$reactivate_modules[] = $active_module;
2233
			Jetpack::deactivate_module( $active_module );
2234
		}
2235
2236
		$new_version = JETPACK__VERSION . ':' . time();
2237
		/** This action is documented in class.jetpack.php */
2238
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2239
		Jetpack_Options::update_options(
2240
			array(
2241
				'version'     => $new_version,
2242
				'old_version' => $jetpack_old_version,
2243
			)
2244
		);
2245
2246
		Jetpack::state( 'message', 'modules_activated' );
2247
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
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...
2248
2249
		if ( $redirect ) {
2250
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2251
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2252
				$page = $_GET['page'];
2253
			}
2254
2255
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2256
			exit;
2257
		}
2258
	}
2259
2260
	/**
2261
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2262
	 * Make sure to tuck away module "library" files in a sub-directory.
2263
	 */
2264
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2265
		static $modules = null;
2266
2267
		if ( ! isset( $modules ) ) {
2268
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2269
			// Use the cache if we're on the front-end and it's available...
2270
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2271
				$modules = $available_modules_option[ JETPACK__VERSION ];
2272
			} else {
2273
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2274
2275
				$modules = array();
2276
2277
				foreach ( $files as $file ) {
2278
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2279
						continue;
2280
					}
2281
2282
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2283
				}
2284
2285
				Jetpack_Options::update_option( 'available_modules', array(
2286
					JETPACK__VERSION => $modules,
2287
				) );
2288
			}
2289
		}
2290
2291
		/**
2292
		 * Filters the array of modules available to be activated.
2293
		 *
2294
		 * @since 2.4.0
2295
		 *
2296
		 * @param array $modules Array of available modules.
2297
		 * @param string $min_version Minimum version number required to use modules.
2298
		 * @param string $max_version Maximum version number required to use modules.
2299
		 */
2300
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2301
2302
		if ( ! $min_version && ! $max_version ) {
2303
			return array_keys( $mods );
2304
		}
2305
2306
		$r = array();
2307
		foreach ( $mods as $slug => $introduced ) {
2308
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2309
				continue;
2310
			}
2311
2312
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2313
				continue;
2314
			}
2315
2316
			$r[] = $slug;
2317
		}
2318
2319
		return $r;
2320
	}
2321
2322
	/**
2323
	 * Default modules loaded on activation.
2324
	 */
2325
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2326
		$return = array();
2327
2328
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2329
			$module_data = Jetpack::get_module( $module );
2330
2331
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2332
				case 'yes' :
2333
					$return[] = $module;
2334
					break;
2335
				case 'public' :
2336
					if ( Jetpack_Options::get_option( 'public' ) ) {
2337
						$return[] = $module;
2338
					}
2339
					break;
2340
				case 'no' :
2341
				default :
2342
					break;
2343
			}
2344
		}
2345
		/**
2346
		 * Filters the array of default modules.
2347
		 *
2348
		 * @since 2.5.0
2349
		 *
2350
		 * @param array $return Array of default modules.
2351
		 * @param string $min_version Minimum version number required to use modules.
2352
		 * @param string $max_version Maximum version number required to use modules.
2353
		 */
2354
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2355
	}
2356
2357
	/**
2358
	 * Checks activated modules during auto-activation to determine
2359
	 * if any of those modules are being deprecated.  If so, close
2360
	 * them out, and add any replacement modules.
2361
	 *
2362
	 * Runs at priority 99 by default.
2363
	 *
2364
	 * This is run late, so that it can still activate a module if
2365
	 * the new module is a replacement for another that the user
2366
	 * currently has active, even if something at the normal priority
2367
	 * would kibosh everything.
2368
	 *
2369
	 * @since 2.6
2370
	 * @uses jetpack_get_default_modules filter
2371
	 * @param array $modules
2372
	 * @return array
2373
	 */
2374
	function handle_deprecated_modules( $modules ) {
2375
		$deprecated_modules = array(
2376
			'debug'            => null,  // Closed out and moved to the debugger library.
2377
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2378
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2379
		);
2380
2381
		// Don't activate SSO if they never completed activating WPCC.
2382
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2383
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2384
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2385
				$deprecated_modules['wpcc'] = null;
2386
			}
2387
		}
2388
2389
		foreach ( $deprecated_modules as $module => $replacement ) {
2390
			if ( Jetpack::is_module_active( $module ) ) {
2391
				self::deactivate_module( $module );
2392
				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...
2393
					$modules[] = $replacement;
2394
				}
2395
			}
2396
		}
2397
2398
		return array_unique( $modules );
2399
	}
2400
2401
	/**
2402
	 * Checks activated plugins during auto-activation to determine
2403
	 * if any of those plugins are in the list with a corresponding module
2404
	 * that is not compatible with the plugin. The module will not be allowed
2405
	 * to auto-activate.
2406
	 *
2407
	 * @since 2.6
2408
	 * @uses jetpack_get_default_modules filter
2409
	 * @param array $modules
2410
	 * @return array
2411
	 */
2412
	function filter_default_modules( $modules ) {
2413
2414
		$active_plugins = self::get_active_plugins();
2415
2416
		if ( ! empty( $active_plugins ) ) {
2417
2418
			// For each module we'd like to auto-activate...
2419
			foreach ( $modules as $key => $module ) {
2420
				// If there are potential conflicts for it...
2421
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2422
					// For each potential conflict...
2423
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2424
						// If that conflicting plugin is active...
2425
						if ( in_array( $plugin, $active_plugins ) ) {
2426
							// Remove that item from being auto-activated.
2427
							unset( $modules[ $key ] );
2428
						}
2429
					}
2430
				}
2431
			}
2432
		}
2433
2434
		return $modules;
2435
	}
2436
2437
	/**
2438
	 * Extract a module's slug from its full path.
2439
	 */
2440
	public static function get_module_slug( $file ) {
2441
		return str_replace( '.php', '', basename( $file ) );
2442
	}
2443
2444
	/**
2445
	 * Generate a module's path from its slug.
2446
	 */
2447
	public static function get_module_path( $slug ) {
2448
		/**
2449
		 * Filters the path of a modules.
2450
		 *
2451
		 * @since 7.4.0
2452
		 *
2453
		 * @param array $return The absolute path to a module's root php file
2454
		 * @param string $slug The module slug
2455
		 */
2456
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2457
	}
2458
2459
	/**
2460
	 * Load module data from module file. Headers differ from WordPress
2461
	 * plugin headers to avoid them being identified as standalone
2462
	 * plugins on the WordPress plugins page.
2463
	 */
2464
	public static function get_module( $module ) {
2465
		$headers = array(
2466
			'name'                      => 'Module Name',
2467
			'description'               => 'Module Description',
2468
			'sort'                      => 'Sort Order',
2469
			'recommendation_order'      => 'Recommendation Order',
2470
			'introduced'                => 'First Introduced',
2471
			'changed'                   => 'Major Changes In',
2472
			'deactivate'                => 'Deactivate',
2473
			'free'                      => 'Free',
2474
			'requires_connection'       => 'Requires Connection',
2475
			'auto_activate'             => 'Auto Activate',
2476
			'module_tags'               => 'Module Tags',
2477
			'feature'                   => 'Feature',
2478
			'additional_search_queries' => 'Additional Search Queries',
2479
			'plan_classes'              => 'Plans',
2480
		);
2481
2482
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2483
2484
		$mod = Jetpack::get_file_data( $file, $headers );
2485
		if ( empty( $mod['name'] ) ) {
2486
			return false;
2487
		}
2488
2489
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2490
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2491
		$mod['deactivate']              = empty( $mod['deactivate'] );
2492
		$mod['free']                    = empty( $mod['free'] );
2493
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2494
2495
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2496
			$mod['auto_activate'] = 'No';
2497
		} else {
2498
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2499
		}
2500
2501
		if ( $mod['module_tags'] ) {
2502
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2503
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2504
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2505
		} else {
2506
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2507
		}
2508
2509 View Code Duplication
		if ( $mod['plan_classes'] ) {
2510
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2511
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2512
		} else {
2513
			$mod['plan_classes'] = array( 'free' );
2514
		}
2515
2516 View Code Duplication
		if ( $mod['feature'] ) {
2517
			$mod['feature'] = explode( ',', $mod['feature'] );
2518
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2519
		} else {
2520
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2521
		}
2522
2523
		/**
2524
		 * Filters the feature array on a module.
2525
		 *
2526
		 * This filter allows you to control where each module is filtered: Recommended,
2527
		 * and the default "Other" listing.
2528
		 *
2529
		 * @since 3.5.0
2530
		 *
2531
		 * @param array   $mod['feature'] The areas to feature this module:
2532
		 *     'Recommended' shows on the main Jetpack admin screen.
2533
		 *     'Other' should be the default if no other value is in the array.
2534
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2535
		 * @param array   $mod All the currently assembled module data.
2536
		 */
2537
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2538
2539
		/**
2540
		 * Filter the returned data about a module.
2541
		 *
2542
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2543
		 * so please be careful.
2544
		 *
2545
		 * @since 3.6.0
2546
		 *
2547
		 * @param array   $mod    The details of the requested module.
2548
		 * @param string  $module The slug of the module, e.g. sharedaddy
2549
		 * @param string  $file   The path to the module source file.
2550
		 */
2551
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2552
	}
2553
2554
	/**
2555
	 * Like core's get_file_data implementation, but caches the result.
2556
	 */
2557
	public static function get_file_data( $file, $headers ) {
2558
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2559
		$file_name = basename( $file );
2560
2561
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2562
2563
		$file_data_option = get_transient( $cache_key );
2564
2565
		if ( false === $file_data_option ) {
2566
			$file_data_option = array();
2567
		}
2568
2569
		$key           = md5( $file_name . serialize( $headers ) );
2570
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2571
2572
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2573
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2574
			return $file_data_option[ $key ];
2575
		}
2576
2577
		$data = get_file_data( $file, $headers );
2578
2579
		$file_data_option[ $key ] = $data;
2580
2581
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2582
2583
		return $data;
2584
	}
2585
2586
2587
	/**
2588
	 * Return translated module tag.
2589
	 *
2590
	 * @param string $tag Tag as it appears in each module heading.
2591
	 *
2592
	 * @return mixed
2593
	 */
2594
	public static function translate_module_tag( $tag ) {
2595
		return jetpack_get_module_i18n_tag( $tag );
2596
	}
2597
2598
	/**
2599
	 * Get i18n strings as a JSON-encoded string
2600
	 *
2601
	 * @return string The locale as JSON
2602
	 */
2603
	public static function get_i18n_data_json() {
2604
2605
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2606
		// JSON files with the file they should be included for. This is an md5
2607
		// of '_inc/build/admin.js'.
2608
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2609
2610
		$i18n_json =
2611
				   JETPACK__PLUGIN_DIR
2612
				   . 'languages/json/jetpack-'
2613
				   . get_user_locale()
2614
				   . '-'
2615
				   . $path_md5
2616
				   . '.json';
2617
2618
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2619
			$locale_data = @file_get_contents( $i18n_json );
2620
			if ( $locale_data ) {
2621
				return $locale_data;
2622
			}
2623
		}
2624
2625
		// Return valid empty Jed locale
2626
		return '{ "locale_data": { "messages": { "": {} } } }';
2627
	}
2628
2629
	/**
2630
	 * Add locale data setup to wp-i18n
2631
	 *
2632
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2633
	 *
2634
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2635
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2636
	 *
2637
	 * This method provides a safe way to request the setup multiple times but add the script at
2638
	 * most once.
2639
	 *
2640
	 * @since 6.7.0
2641
	 *
2642
	 * @return void
2643
	 */
2644
	public static function setup_wp_i18n_locale_data() {
2645
		static $script_added = false;
2646
		if ( ! $script_added ) {
2647
			$script_added = true;
2648
			wp_add_inline_script(
2649
				'wp-i18n',
2650
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2651
			);
2652
		}
2653
	}
2654
2655
	/**
2656
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2657
	 *
2658
	 * @since 3.9.2
2659
	 *
2660
	 * @param array $modules
2661
	 *
2662
	 * @return string|void
2663
	 */
2664
	public static function get_translated_modules( $modules ) {
2665
		foreach ( $modules as $index => $module ) {
2666
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2667
			if ( isset( $module['name'] ) ) {
2668
				$modules[ $index ]['name'] = $i18n_module['name'];
2669
			}
2670
			if ( isset( $module['description'] ) ) {
2671
				$modules[ $index ]['description'] = $i18n_module['description'];
2672
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2673
			}
2674
		}
2675
		return $modules;
2676
	}
2677
2678
	/**
2679
	 * Get a list of activated modules as an array of module slugs.
2680
	 */
2681
	public static function get_active_modules() {
2682
		$active = Jetpack_Options::get_option( 'active_modules' );
2683
2684
		if ( ! is_array( $active ) ) {
2685
			$active = array();
2686
		}
2687
2688
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2689
			$active[] = 'vaultpress';
2690
		} else {
2691
			$active = array_diff( $active, array( 'vaultpress' ) );
2692
		}
2693
2694
		//If protect is active on the main site of a multisite, it should be active on all sites.
2695
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2696
			$active[] = 'protect';
2697
		}
2698
2699
		/**
2700
		 * Allow filtering of the active modules.
2701
		 *
2702
		 * Gives theme and plugin developers the power to alter the modules that
2703
		 * are activated on the fly.
2704
		 *
2705
		 * @since 5.8.0
2706
		 *
2707
		 * @param array $active Array of active module slugs.
2708
		 */
2709
		$active = apply_filters( 'jetpack_active_modules', $active );
2710
2711
		return array_unique( $active );
2712
	}
2713
2714
	/**
2715
	 * Check whether or not a Jetpack module is active.
2716
	 *
2717
	 * @param string $module The slug of a Jetpack module.
2718
	 * @return bool
2719
	 *
2720
	 * @static
2721
	 */
2722
	public static function is_module_active( $module ) {
2723
		return in_array( $module, self::get_active_modules() );
2724
	}
2725
2726
	public static function is_module( $module ) {
2727
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2728
	}
2729
2730
	/**
2731
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2732
	 *
2733
	 * @param bool $catch True to start catching, False to stop.
2734
	 *
2735
	 * @static
2736
	 */
2737
	public static function catch_errors( $catch ) {
2738
		static $display_errors, $error_reporting;
2739
2740
		if ( $catch ) {
2741
			$display_errors  = @ini_set( 'display_errors', 1 );
2742
			$error_reporting = @error_reporting( E_ALL );
2743
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2744
		} else {
2745
			@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...
2746
			@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...
2747
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2748
		}
2749
	}
2750
2751
	/**
2752
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2753
	 */
2754
	public static function catch_errors_on_shutdown() {
2755
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2756
	}
2757
2758
	/**
2759
	 * Rewrite any string to make paths easier to read.
2760
	 *
2761
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2762
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2763
	 *
2764
	 * @param $string
2765
	 * @return mixed
2766
	 */
2767
	public static function alias_directories( $string ) {
2768
		// ABSPATH has a trailing slash.
2769
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2770
		// WP_CONTENT_DIR does not have a trailing slash.
2771
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2772
2773
		return $string;
2774
	}
2775
2776
	public static function activate_default_modules(
2777
		$min_version = false,
2778
		$max_version = false,
2779
		$other_modules = array(),
2780
		$redirect = null,
2781
		$send_state_messages = null
2782
	) {
2783
		$jetpack = Jetpack::init();
2784
2785
		if ( is_null( $redirect ) ) {
2786
			if (
2787
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2788
			||
2789
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2790
			||
2791
				( defined( 'WP_CLI' ) && WP_CLI )
2792
			||
2793
				( defined( 'DOING_CRON' ) && DOING_CRON )
2794
			||
2795
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2796
			) {
2797
				$redirect = false;
2798
			} elseif ( is_admin() ) {
2799
				$redirect = true;
2800
			} else {
2801
				$redirect = false;
2802
			}
2803
		}
2804
2805
		if ( is_null( $send_state_messages ) ) {
2806
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2807
		}
2808
2809
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2810
		$modules = array_merge( $other_modules, $modules );
2811
2812
		// Look for standalone plugins and disable if active.
2813
2814
		$to_deactivate = array();
2815
		foreach ( $modules as $module ) {
2816
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2817
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2818
			}
2819
		}
2820
2821
		$deactivated = array();
2822
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2823
			list( $probable_file, $probable_title ) = $deactivate_me;
2824
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2825
				$deactivated[] = $module;
2826
			}
2827
		}
2828
2829
		if ( $deactivated ) {
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...
2830
			if ( $send_state_messages ) {
2831
				Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2832
			}
2833
2834
			if ( $redirect ) {
2835
				$url = add_query_arg(
2836
					array(
2837
						'action'   => 'activate_default_modules',
2838
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2839
					),
2840
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2841
				);
2842
				wp_safe_redirect( $url );
2843
				exit;
2844
			}
2845
		}
2846
2847
		/**
2848
		 * Fires before default modules are activated.
2849
		 *
2850
		 * @since 1.9.0
2851
		 *
2852
		 * @param string $min_version Minimum version number required to use modules.
2853
		 * @param string $max_version Maximum version number required to use modules.
2854
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2855
		 */
2856
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2857
2858
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2859
		if ( $send_state_messages ) {
2860
			Jetpack::restate();
2861
			Jetpack::catch_errors( true );
2862
		}
2863
2864
		$active = Jetpack::get_active_modules();
2865
2866
		foreach ( $modules as $module ) {
2867
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2868
				$active[] = $module;
2869
				self::update_active_modules( $active );
2870
				continue;
2871
			}
2872
2873
			if ( $send_state_messages && in_array( $module, $active ) ) {
2874
				$module_info = Jetpack::get_module( $module );
2875 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2876
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2877
					if ( $active_state = Jetpack::state( $state ) ) {
2878
						$active_state = explode( ',', $active_state );
2879
					} else {
2880
						$active_state = array();
2881
					}
2882
					$active_state[] = $module;
2883
					Jetpack::state( $state, implode( ',', $active_state ) );
2884
				}
2885
				continue;
2886
			}
2887
2888
			$file = Jetpack::get_module_path( $module );
2889
			if ( ! file_exists( $file ) ) {
2890
				continue;
2891
			}
2892
2893
			// we'll override this later if the plugin can be included without fatal error
2894
			if ( $redirect ) {
2895
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2896
			}
2897
2898
			if ( $send_state_messages ) {
2899
				Jetpack::state( 'error', 'module_activation_failed' );
2900
				Jetpack::state( 'module', $module );
2901
			}
2902
2903
			ob_start();
2904
			require_once $file;
2905
2906
			$active[] = $module;
2907
2908 View Code Duplication
			if ( $send_state_messages ) {
2909
2910
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2911
				if ( $active_state = Jetpack::state( $state ) ) {
2912
					$active_state = explode( ',', $active_state );
2913
				} else {
2914
					$active_state = array();
2915
				}
2916
				$active_state[] = $module;
2917
				Jetpack::state( $state, implode( ',', $active_state ) );
2918
			}
2919
2920
			Jetpack::update_active_modules( $active );
2921
2922
			ob_end_clean();
2923
		}
2924
2925
		if ( $send_state_messages ) {
2926
			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...
2927
			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...
2928
		}
2929
2930
		Jetpack::catch_errors( false );
2931
		/**
2932
		 * Fires when default modules are activated.
2933
		 *
2934
		 * @since 1.9.0
2935
		 *
2936
		 * @param string $min_version Minimum version number required to use modules.
2937
		 * @param string $max_version Maximum version number required to use modules.
2938
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2939
		 */
2940
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2941
	}
2942
2943
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2944
		/**
2945
		 * Fires before a module is activated.
2946
		 *
2947
		 * @since 2.6.0
2948
		 *
2949
		 * @param string $module Module slug.
2950
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2951
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2952
		 */
2953
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2954
2955
		$jetpack = Jetpack::init();
2956
2957
		if ( ! strlen( $module ) )
2958
			return false;
2959
2960
		if ( ! Jetpack::is_module( $module ) )
2961
			return false;
2962
2963
		// If it's already active, then don't do it again
2964
		$active = Jetpack::get_active_modules();
2965
		foreach ( $active as $act ) {
2966
			if ( $act == $module )
2967
				return true;
2968
		}
2969
2970
		$module_data = Jetpack::get_module( $module );
2971
2972
		if ( ! Jetpack::is_active() ) {
2973
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2974
				return false;
2975
2976
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2977
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2978
				return false;
2979
		}
2980
2981
		// Check and see if the old plugin is active
2982
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2983
			// Deactivate the old plugin
2984
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2985
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2986
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2987
				Jetpack::state( 'deactivated_plugins', $module );
2988
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2989
				exit;
2990
			}
2991
		}
2992
2993
		// Protect won't work with mis-configured IPs
2994
		if ( 'protect' === $module ) {
2995
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2996
			if ( ! jetpack_protect_get_ip() ) {
2997
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2998
				return false;
2999
			}
3000
		}
3001
3002
		if ( ! Jetpack_Plan::supports( $module ) ) {
3003
			return false;
3004
		}
3005
3006
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3007
		Jetpack::state( 'module', $module );
3008
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3009
3010
		Jetpack::catch_errors( true );
3011
		ob_start();
3012
		require Jetpack::get_module_path( $module );
3013
		/** This action is documented in class.jetpack.php */
3014
		do_action( 'jetpack_activate_module', $module );
3015
		$active[] = $module;
3016
		Jetpack::update_active_modules( $active );
3017
3018
		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...
3019
		ob_end_clean();
3020
		Jetpack::catch_errors( false );
3021
3022
		if ( $redirect ) {
3023
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3024
		}
3025
		if ( $exit ) {
3026
			exit;
3027
		}
3028
		return true;
3029
	}
3030
3031
	function activate_module_actions( $module ) {
3032
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3033
	}
3034
3035
	public static function deactivate_module( $module ) {
3036
		/**
3037
		 * Fires when a module is deactivated.
3038
		 *
3039
		 * @since 1.9.0
3040
		 *
3041
		 * @param string $module Module slug.
3042
		 */
3043
		do_action( 'jetpack_pre_deactivate_module', $module );
3044
3045
		$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...
3046
3047
		$active = Jetpack::get_active_modules();
3048
		$new    = array_filter( array_diff( $active, (array) $module ) );
3049
3050
		return self::update_active_modules( $new );
3051
	}
3052
3053
	public static function enable_module_configurable( $module ) {
3054
		$module = Jetpack::get_module_slug( $module );
3055
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3056
	}
3057
3058
	/**
3059
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3060
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3061
	 *
3062
	 * @param string $module Module slug
3063
	 * @return string $url module configuration URL
3064
	 */
3065
	public static function module_configuration_url( $module ) {
3066
		$module = Jetpack::get_module_slug( $module );
3067
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3068
		/**
3069
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3070
		 *
3071
		 * @since 6.9.0
3072
		 *
3073
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3074
		 */
3075
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3076
3077
		return $url;
3078
	}
3079
3080
/* Installation */
3081
	public static function bail_on_activation( $message, $deactivate = true ) {
3082
?>
3083
<!doctype html>
3084
<html>
3085
<head>
3086
<meta charset="<?php bloginfo( 'charset' ); ?>">
3087
<style>
3088
* {
3089
	text-align: center;
3090
	margin: 0;
3091
	padding: 0;
3092
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3093
}
3094
p {
3095
	margin-top: 1em;
3096
	font-size: 18px;
3097
}
3098
</style>
3099
<body>
3100
<p><?php echo esc_html( $message ); ?></p>
3101
</body>
3102
</html>
3103
<?php
3104
		if ( $deactivate ) {
3105
			$plugins = get_option( 'active_plugins' );
3106
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3107
			$update  = false;
3108
			foreach ( $plugins as $i => $plugin ) {
3109
				if ( $plugin === $jetpack ) {
3110
					$plugins[$i] = false;
3111
					$update = true;
3112
				}
3113
			}
3114
3115
			if ( $update ) {
3116
				update_option( 'active_plugins', array_filter( $plugins ) );
3117
			}
3118
		}
3119
		exit;
3120
	}
3121
3122
	/**
3123
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3124
	 * @static
3125
	 */
3126
	public static function plugin_activation( $network_wide ) {
3127
		Jetpack_Options::update_option( 'activated', 1 );
3128
3129
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3130
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3131
		}
3132
3133
		if ( $network_wide )
3134
			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...
3135
3136
		// For firing one-off events (notices) immediately after activation
3137
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3138
3139
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3140
3141
		Jetpack::plugin_initialize();
3142
	}
3143
3144
	public static function get_activation_source( $referer_url ) {
3145
3146
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3147
			return array( 'wp-cli', null );
3148
		}
3149
3150
		$referer = parse_url( $referer_url );
3151
3152
		$source_type = 'unknown';
3153
		$source_query = null;
3154
3155
		if ( ! is_array( $referer ) ) {
3156
			return array( $source_type, $source_query );
3157
		}
3158
3159
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3160
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3161
3162
		if ( isset( $referer['query'] ) ) {
3163
			parse_str( $referer['query'], $query_parts );
3164
		} else {
3165
			$query_parts = array();
3166
		}
3167
3168
		if ( $plugins_path === $referer['path'] ) {
3169
			$source_type = 'list';
3170
		} elseif ( $plugins_install_path === $referer['path'] ) {
3171
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3172
			switch( $tab ) {
3173
				case 'popular':
3174
					$source_type = 'popular';
3175
					break;
3176
				case 'recommended':
3177
					$source_type = 'recommended';
3178
					break;
3179
				case 'favorites':
3180
					$source_type = 'favorites';
3181
					break;
3182
				case 'search':
3183
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3184
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3185
					break;
3186
				default:
3187
					$source_type = 'featured';
3188
			}
3189
		}
3190
3191
		return array( $source_type, $source_query );
3192
	}
3193
3194
	/**
3195
	 * Runs before bumping version numbers up to a new version
3196
	 * @param  string $version    Version:timestamp
3197
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3198
	 * @return null              [description]
3199
	 */
3200
	public static function do_version_bump( $version, $old_version ) {
3201
		if ( ! $old_version ) { // For new sites
3202
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3203
		}
3204
	}
3205
3206
	/**
3207
	 * Sets the internal version number and activation state.
3208
	 * @static
3209
	 */
3210
	public static function plugin_initialize() {
3211
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3212
			Jetpack_Options::update_option( 'activated', 2 );
3213
		}
3214
3215 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3216
			$version = $old_version = JETPACK__VERSION . ':' . time();
3217
			/** This action is documented in class.jetpack.php */
3218
			do_action( 'updating_jetpack_version', $version, false );
3219
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3220
		}
3221
3222
		Jetpack::load_modules();
3223
3224
		Jetpack_Options::delete_option( 'do_activate' );
3225
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3226
	}
3227
3228
	/**
3229
	 * Removes all connection options
3230
	 * @static
3231
	 */
3232
	public static function plugin_deactivation( ) {
3233
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3234
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3235
			Jetpack_Network::init()->deactivate();
3236
		} else {
3237
			Jetpack::disconnect( false );
3238
			//Jetpack_Heartbeat::init()->deactivate();
3239
		}
3240
	}
3241
3242
	/**
3243
	 * Disconnects from the Jetpack servers.
3244
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3245
	 * @static
3246
	 */
3247
	public static function disconnect( $update_activated_state = true ) {
3248
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3249
		$connection = self::connection();
3250
		$connection->clean_nonces( true );
3251
3252
		// If the site is in an IDC because sync is not allowed,
3253
		// let's make sure to not disconnect the production site.
3254
		if ( ! self::validate_sync_error_idc_option() ) {
3255
			$tracking = new Tracking();
3256
			$tracking->record_user_event( 'disconnect_site', array() );
3257
3258
			$xml = new Jetpack_IXR_Client();
3259
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3260
		}
3261
3262
		Jetpack_Options::delete_option(
3263
			array(
3264
				'blog_token',
3265
				'user_token',
3266
				'user_tokens',
3267
				'master_user',
3268
				'time_diff',
3269
				'fallback_no_verify_ssl_certs',
3270
			)
3271
		);
3272
3273
		Jetpack_IDC::clear_all_idc_options();
3274
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3275
3276
		if ( $update_activated_state ) {
3277
			Jetpack_Options::update_option( 'activated', 4 );
3278
		}
3279
3280
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3281
			// Check then record unique disconnection if site has never been disconnected previously
3282
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3283
				$jetpack_unique_connection['disconnected'] = 1;
3284
			} else {
3285
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3286
					//track unique disconnect
3287
					$jetpack = Jetpack::init();
3288
3289
					$jetpack->stat( 'connections', 'unique-disconnect' );
3290
					$jetpack->do_stats( 'server_side' );
3291
				}
3292
				// increment number of times disconnected
3293
				$jetpack_unique_connection['disconnected'] += 1;
3294
			}
3295
3296
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3297
		}
3298
3299
		// Delete cached connected user data
3300
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3301
		delete_transient( $transient_key );
3302
3303
		// Delete all the sync related data. Since it could be taking up space.
3304
		Sender::get_instance()->uninstall();
3305
3306
		// Disable the Heartbeat cron
3307
		Jetpack_Heartbeat::init()->deactivate();
3308
	}
3309
3310
	/**
3311
	 * Unlinks the current user from the linked WordPress.com user.
3312
	 *
3313
	 * @deprecated since 7.7
3314
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3315
	 *
3316
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|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...
3317
	 * @return Boolean Whether the disconnection of the user was successful.
3318
	 */
3319
	public static function unlink_user( $user_id = null ) {
3320
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3321
		return Connection_Manager::disconnect_user( $user_id );
3322
	}
3323
3324
	/**
3325
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3326
	 */
3327
	public static function try_registration() {
3328
		// The user has agreed to the TOS at some point by now.
3329
		Jetpack_Options::update_option( 'tos_agreed', true );
3330
3331
		// Let's get some testing in beta versions and such.
3332
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3333
			// Before attempting to connect, let's make sure that the domains are viable.
3334
			$domains_to_check = array_unique( array(
3335
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3336
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3337
			) );
3338
			foreach ( $domains_to_check as $domain ) {
3339
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3338 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...
3340
				if ( is_wp_error( $result ) ) {
3341
					return $result;
3342
				}
3343
			}
3344
		}
3345
3346
		$result = Jetpack::register();
3347
3348
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3349
		if ( ! $result || is_wp_error( $result ) ) {
3350
			return $result;
3351
		} else {
3352
			return true;
3353
		}
3354
	}
3355
3356
	/**
3357
	 * Tracking an internal event log. Try not to put too much chaff in here.
3358
	 *
3359
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3360
	 */
3361
	public static function log( $code, $data = null ) {
3362
		// only grab the latest 200 entries
3363
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3364
3365
		// Append our event to the log
3366
		$log_entry = array(
3367
			'time'    => time(),
3368
			'user_id' => get_current_user_id(),
3369
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3370
			'code'    => $code,
3371
		);
3372
		// Don't bother storing it unless we've got some.
3373
		if ( ! is_null( $data ) ) {
3374
			$log_entry['data'] = $data;
3375
		}
3376
		$log[] = $log_entry;
3377
3378
		// Try add_option first, to make sure it's not autoloaded.
3379
		// @todo: Add an add_option method to Jetpack_Options
3380
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3381
			Jetpack_Options::update_option( 'log', $log );
3382
		}
3383
3384
		/**
3385
		 * Fires when Jetpack logs an internal event.
3386
		 *
3387
		 * @since 3.0.0
3388
		 *
3389
		 * @param array $log_entry {
3390
		 *	Array of details about the log entry.
3391
		 *
3392
		 *	@param string time Time of the event.
3393
		 *	@param int user_id ID of the user who trigerred the event.
3394
		 *	@param int blog_id Jetpack Blog ID.
3395
		 *	@param string code Unique name for the event.
3396
		 *	@param string data Data about the event.
3397
		 * }
3398
		 */
3399
		do_action( 'jetpack_log_entry', $log_entry );
3400
	}
3401
3402
	/**
3403
	 * Get the internal event log.
3404
	 *
3405
	 * @param $event (string) - only return the specific log events
3406
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3407
	 *
3408
	 * @return array of log events || WP_Error for invalid params
3409
	 */
3410
	public static function get_log( $event = false, $num = false ) {
3411
		if ( $event && ! is_string( $event ) ) {
3412
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3413
		}
3414
3415
		if ( $num && ! is_numeric( $num ) ) {
3416
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3417
		}
3418
3419
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3420
3421
		// If nothing set - act as it did before, otherwise let's start customizing the output
3422
		if ( ! $num && ! $event ) {
3423
			return $entire_log;
3424
		} else {
3425
			$entire_log = array_reverse( $entire_log );
3426
		}
3427
3428
		$custom_log_output = array();
3429
3430
		if ( $event ) {
3431
			foreach ( $entire_log as $log_event ) {
3432
				if ( $event == $log_event[ 'code' ] ) {
3433
					$custom_log_output[] = $log_event;
3434
				}
3435
			}
3436
		} else {
3437
			$custom_log_output = $entire_log;
3438
		}
3439
3440
		if ( $num ) {
3441
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3442
		}
3443
3444
		return $custom_log_output;
3445
	}
3446
3447
	/**
3448
	 * Log modification of important settings.
3449
	 */
3450
	public static function log_settings_change( $option, $old_value, $value ) {
3451
		switch( $option ) {
3452
			case 'jetpack_sync_non_public_post_stati':
3453
				self::log( $option, $value );
3454
				break;
3455
		}
3456
	}
3457
3458
	/**
3459
	 * Return stat data for WPCOM sync
3460
	 */
3461
	public static function get_stat_data( $encode = true, $extended = true ) {
3462
		$data = Jetpack_Heartbeat::generate_stats_array();
3463
3464
		if ( $extended ) {
3465
			$additional_data = self::get_additional_stat_data();
3466
			$data = array_merge( $data, $additional_data );
3467
		}
3468
3469
		if ( $encode ) {
3470
			return json_encode( $data );
3471
		}
3472
3473
		return $data;
3474
	}
3475
3476
	/**
3477
	 * Get additional stat data to sync to WPCOM
3478
	 */
3479
	public static function get_additional_stat_data( $prefix = '' ) {
3480
		$return["{$prefix}themes"]         = Jetpack::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3481
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3482
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3483
		$return["{$prefix}site-count"]     = 0;
3484
3485
		if ( function_exists( 'get_blog_count' ) ) {
3486
			$return["{$prefix}site-count"] = get_blog_count();
3487
		}
3488
		return $return;
3489
	}
3490
3491
	private static function get_site_user_count() {
3492
		global $wpdb;
3493
3494
		if ( function_exists( 'wp_is_large_network' ) ) {
3495
			if ( wp_is_large_network( 'users' ) ) {
3496
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3497
			}
3498
		}
3499
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3500
			// It wasn't there, so regenerate the data and save the transient
3501
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3502
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3503
		}
3504
		return $user_count;
3505
	}
3506
3507
	/* Admin Pages */
3508
3509
	function admin_init() {
3510
		// If the plugin is not connected, display a connect message.
3511
		if (
3512
			// the plugin was auto-activated and needs its candy
3513
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3514
		||
3515
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3516
			! Jetpack_Options::get_option( 'activated' )
3517
		) {
3518
			Jetpack::plugin_initialize();
3519
		}
3520
3521
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3522
			Jetpack_Connection_Banner::init();
3523
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3524
			// Upgrade: 1.1 -> 1.1.1
3525
			// Check and see if host can verify the Jetpack servers' SSL certificate
3526
			$args = array();
3527
			$connection = self::connection();
3528
			Client::_wp_remote_request(
3529
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3530
				$args,
3531
				true
3532
			);
3533
		}
3534
3535
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3536
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3537
		}
3538
3539
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3540
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3541
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3542
3543
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3544
			// Artificially throw errors in certain whitelisted cases during plugin activation
3545
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3546
		}
3547
3548
		// Add custom column in wp-admin/users.php to show whether user is linked.
3549
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3550
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3551
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3552
	}
3553
3554
	function admin_body_class( $admin_body_class = '' ) {
3555
		$classes = explode( ' ', trim( $admin_body_class ) );
3556
3557
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3558
3559
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3560
		return " $admin_body_class ";
3561
	}
3562
3563
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3564
		return $admin_body_class . ' jetpack-pagestyles ';
3565
	}
3566
3567
	/**
3568
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3569
	 * This function artificially throws errors for such cases (whitelisted).
3570
	 *
3571
	 * @param string $plugin The activated plugin.
3572
	 */
3573
	function throw_error_on_activate_plugin( $plugin ) {
3574
		$active_modules = Jetpack::get_active_modules();
3575
3576
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3577
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3578
			$throw = false;
3579
3580
			// Try and make sure it really was the stats plugin
3581
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3582
				if ( 'stats.php' == basename( $plugin ) ) {
3583
					$throw = true;
3584
				}
3585
			} else {
3586
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3587
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3588
					$throw = true;
3589
				}
3590
			}
3591
3592
			if ( $throw ) {
3593
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3594
			}
3595
		}
3596
	}
3597
3598
	function intercept_plugin_error_scrape_init() {
3599
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3600
	}
3601
3602
	function intercept_plugin_error_scrape( $action, $result ) {
3603
		if ( ! $result ) {
3604
			return;
3605
		}
3606
3607
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3608
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3609
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3610
			}
3611
		}
3612
	}
3613
3614
	/**
3615
	 * Register the remote file upload request handlers, if needed.
3616
	 *
3617
	 * @access public
3618
	 */
3619
	public function add_remote_request_handlers() {
3620
		// Remote file uploads are allowed only via AJAX requests.
3621
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3622
			return;
3623
		}
3624
3625
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3626
		$remote_request_actions = array(
3627
			'jetpack_upload_file',
3628
			'jetpack_update_file',
3629
		);
3630
3631
		// phpcs:ignore WordPress.Security.NonceVerification
3632
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3633
			return;
3634
		}
3635
3636
		// Require Jetpack authentication for the remote file upload AJAX requests.
3637
		$this->connection_manager->require_jetpack_authentication();
3638
3639
		// Register the remote file upload AJAX handlers.
3640
		foreach ( $remote_request_actions as $action ) {
3641
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3642
		}
3643
	}
3644
3645
	/**
3646
	 * Handler for Jetpack remote file uploads.
3647
	 *
3648
	 * @access public
3649
	 */
3650
	public function remote_request_handlers() {
3651
		$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...
3652
3653
		switch ( current_filter() ) {
3654
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3655
			$response = $this->upload_handler();
3656
			break;
3657
3658
		case 'wp_ajax_nopriv_jetpack_update_file' :
3659
			$response = $this->upload_handler( true );
3660
			break;
3661
		default :
3662
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_handler'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3663
			break;
3664
		}
3665
3666
		if ( ! $response ) {
3667
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3668
		}
3669
3670
		if ( is_wp_error( $response ) ) {
3671
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<Jetpack_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3672
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<Jetpack_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3673
			$error_description = $response->get_error_message();
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<Jetpack_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3674
3675
			if ( ! is_int( $status_code ) ) {
3676
				$status_code = 400;
3677
			}
3678
3679
			status_header( $status_code );
3680
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3681
		}
3682
3683
		status_header( 200 );
3684
		if ( true === $response ) {
3685
			exit;
3686
		}
3687
3688
		die( json_encode( (object) $response ) );
3689
	}
3690
3691
	/**
3692
	 * Uploads a file gotten from the global $_FILES.
3693
	 * If `$update_media_item` is true and `post_id` is defined
3694
	 * the attachment file of the media item (gotten through of the post_id)
3695
	 * will be updated instead of add a new one.
3696
	 *
3697
	 * @param  boolean $update_media_item - update media attachment
3698
	 * @return array - An array describing the uploadind files process
3699
	 */
3700
	function upload_handler( $update_media_item = false ) {
3701
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3702
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 405.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3703
		}
3704
3705
		$user = wp_authenticate( '', '' );
3706
		if ( ! $user || is_wp_error( $user ) ) {
3707
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 403.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3708
		}
3709
3710
		wp_set_current_user( $user->ID );
3711
3712
		if ( ! current_user_can( 'upload_files' ) ) {
3713
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3714
		}
3715
3716
		if ( empty( $_FILES ) ) {
3717
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3718
		}
3719
3720
		foreach ( array_keys( $_FILES ) as $files_key ) {
3721
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3722
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_hmac'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3723
			}
3724
		}
3725
3726
		$media_keys = array_keys( $_FILES['media'] );
3727
3728
		$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...
3729
		if ( ! $token || is_wp_error( $token ) ) {
3730
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3731
		}
3732
3733
		$uploaded_files = array();
3734
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3735
		unset( $GLOBALS['post'] );
3736
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3737
			$file = array();
3738
			foreach ( $media_keys as $media_key ) {
3739
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3740
			}
3741
3742
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3743
3744
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3745
			if ( $hmac_provided !== $hmac_file ) {
3746
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3747
				continue;
3748
			}
3749
3750
			$_FILES['.jetpack.upload.'] = $file;
3751
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3752
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3753
				$post_id = 0;
3754
			}
3755
3756
			if ( $update_media_item ) {
3757
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3758
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'invalid_input'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3759
				}
3760
3761
				$media_array = $_FILES['media'];
3762
3763
				$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...
3764
				$file_array['type'] = $media_array['type'][0];
3765
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3766
				$file_array['error'] = $media_array['error'][0];
3767
				$file_array['size'] = $media_array['size'][0];
3768
3769
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3770
3771
				if ( is_wp_error( $edited_media_item ) ) {
3772
					return $edited_media_item;
3773
				}
3774
3775
				$response = (object) array(
3776
					'id'   => (string) $post_id,
3777
					'file' => (string) $edited_media_item->post_title,
3778
					'url'  => (string) wp_get_attachment_url( $post_id ),
3779
					'type' => (string) $edited_media_item->post_mime_type,
3780
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3781
				);
3782
3783
				return (array) array( $response );
3784
			}
3785
3786
			$attachment_id = media_handle_upload(
3787
				'.jetpack.upload.',
3788
				$post_id,
3789
				array(),
3790
				array(
3791
					'action' => 'jetpack_upload_file',
3792
				)
3793
			);
3794
3795
			if ( ! $attachment_id ) {
3796
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3797
			} elseif ( is_wp_error( $attachment_id ) ) {
3798
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3799
			} else {
3800
				$attachment = get_post( $attachment_id );
3801
				$uploaded_files[$index] = (object) array(
3802
					'id'   => (string) $attachment_id,
3803
					'file' => $attachment->post_title,
3804
					'url'  => wp_get_attachment_url( $attachment_id ),
3805
					'type' => $attachment->post_mime_type,
3806
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3807
				);
3808
				// Zip files uploads are not supported unless they are done for installation purposed
3809
				// lets delete them in case something goes wrong in this whole process
3810
				if ( 'application/zip' === $attachment->post_mime_type ) {
3811
					// Schedule a cleanup for 2 hours from now in case of failed install.
3812
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3813
				}
3814
			}
3815
		}
3816
		if ( ! is_null( $global_post ) ) {
3817
			$GLOBALS['post'] = $global_post;
3818
		}
3819
3820
		return $uploaded_files;
3821
	}
3822
3823
	/**
3824
	 * Add help to the Jetpack page
3825
	 *
3826
	 * @since Jetpack (1.2.3)
3827
	 * @return false if not the Jetpack page
3828
	 */
3829
	function admin_help() {
3830
		$current_screen = get_current_screen();
3831
3832
		// Overview
3833
		$current_screen->add_help_tab(
3834
			array(
3835
				'id'		=> 'home',
3836
				'title'		=> __( 'Home', 'jetpack' ),
3837
				'content'	=>
3838
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3839
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3840
					'<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>',
3841
			)
3842
		);
3843
3844
		// Screen Content
3845
		if ( current_user_can( 'manage_options' ) ) {
3846
			$current_screen->add_help_tab(
3847
				array(
3848
					'id'		=> 'settings',
3849
					'title'		=> __( 'Settings', 'jetpack' ),
3850
					'content'	=>
3851
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3852
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3853
						'<ol>' .
3854
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3855
							'<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>' .
3856
						'</ol>' .
3857
						'<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>'
3858
				)
3859
			);
3860
		}
3861
3862
		// Help Sidebar
3863
		$current_screen->set_help_sidebar(
3864
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3865
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3866
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3867
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3868
		);
3869
	}
3870
3871
	function admin_menu_css() {
3872
		wp_enqueue_style( 'jetpack-icons' );
3873
	}
3874
3875
	function admin_menu_order() {
3876
		return true;
3877
	}
3878
3879 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3880
		$jp_menu_order = array();
3881
3882
		foreach ( $menu_order as $index => $item ) {
3883
			if ( $item != 'jetpack' ) {
3884
				$jp_menu_order[] = $item;
3885
			}
3886
3887
			if ( $index == 0 ) {
3888
				$jp_menu_order[] = 'jetpack';
3889
			}
3890
		}
3891
3892
		return $jp_menu_order;
3893
	}
3894
3895
	function admin_banner_styles() {
3896
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3897
3898
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3899
			wp_register_style(
3900
				'jetpack-dops-style',
3901
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3902
				array(),
3903
				JETPACK__VERSION
3904
			);
3905
		}
3906
3907
		wp_enqueue_style(
3908
			'jetpack',
3909
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3910
			array( 'jetpack-dops-style' ),
3911
			 JETPACK__VERSION . '-20121016'
3912
		);
3913
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3914
		wp_style_add_data( 'jetpack', 'suffix', $min );
3915
	}
3916
3917
	function plugin_action_links( $actions ) {
3918
3919
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3920
3921
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3922
			return array_merge(
3923
				$jetpack_home,
3924
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3925
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3926
				$actions
3927
				);
3928
			}
3929
3930
		return array_merge( $jetpack_home, $actions );
3931
	}
3932
3933
	/*
3934
	 * Registration flow:
3935
	 * 1 - ::admin_page_load() action=register
3936
	 * 2 - ::try_registration()
3937
	 * 3 - ::register()
3938
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3939
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3940
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3941
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3942
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3943
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3944
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3945
	 *       jetpack_id, jetpack_secret, jetpack_public
3946
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3947
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3948
	 * 5 - user logs in with WP.com account
3949
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3950
	 *		- Jetpack_Client_Server::authorize()
3951
	 *		- Jetpack_Client_Server::get_token()
3952
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3953
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3954
	 *			- which responds with access_token, token_type, scope
3955
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3956
	 *		- Jetpack::activate_default_modules()
3957
	 *     		- Deactivates deprecated plugins
3958
	 *     		- Activates all default modules
3959
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3960
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3961
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3962
	 *     Done!
3963
	 */
3964
3965
	/**
3966
	 * Handles the page load events for the Jetpack admin page
3967
	 */
3968
	function admin_page_load() {
3969
		$error = false;
3970
3971
		// Make sure we have the right body class to hook stylings for subpages off of.
3972
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3973
3974
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3975
			// Should only be used in intermediate redirects to preserve state across redirects
3976
			Jetpack::restate();
3977
		}
3978
3979
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3980
			// @todo: Add validation against a known whitelist
3981
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3982
			// User clicked in the iframe to link their accounts
3983
			if ( ! Jetpack::is_user_connected() ) {
3984
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3985
3986
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3987
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3988
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3989
3990
				if ( isset( $_GET['notes_iframe'] ) )
3991
					$connect_url .= '&notes_iframe';
3992
				wp_redirect( $connect_url );
3993
				exit;
3994
			} else {
3995
				if ( ! isset( $_GET['calypso_env'] ) ) {
3996
					Jetpack::state( 'message', 'already_authorized' );
3997
					wp_safe_redirect( Jetpack::admin_url() );
3998
					exit;
3999
				} else {
4000
					$connect_url = $this->build_connect_url( true, false, $from );
4001
					$connect_url .= '&already_authorized=true';
4002
					wp_redirect( $connect_url );
4003
					exit;
4004
				}
4005
			}
4006
		}
4007
4008
4009
		if ( isset( $_GET['action'] ) ) {
4010
			switch ( $_GET['action'] ) {
4011
			case 'authorize':
4012
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4013
					Jetpack::state( 'message', 'already_authorized' );
4014
					wp_safe_redirect( Jetpack::admin_url() );
4015
					exit;
4016
				}
4017
				Jetpack::log( 'authorize' );
4018
				$client_server = new Jetpack_Client_Server;
4019
				$client_server->client_authorize();
4020
				exit;
4021
			case 'register' :
4022
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4023
					$error = 'cheatin';
4024
					break;
4025
				}
4026
				check_admin_referer( 'jetpack-register' );
4027
				Jetpack::log( 'register' );
4028
				Jetpack::maybe_set_version_option();
4029
				$registered = Jetpack::try_registration();
4030
				if ( is_wp_error( $registered ) ) {
4031
					$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4032
					Jetpack::state( 'error', $error );
4033
					Jetpack::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4034
4035
					/**
4036
					 * Jetpack registration Error.
4037
					 *
4038
					 * @since 7.5.0
4039
					 *
4040
					 * @param string|int $error The error code.
4041
					 * @param \WP_Error $registered The error object.
4042
					 */
4043
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4044
					break;
4045
				}
4046
4047
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4048
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4049
4050
				/**
4051
				 * Jetpack registration Success.
4052
				 *
4053
				 * @since 7.5.0
4054
				 *
4055
				 * @param string $from 'from' GET parameter;
4056
				 */
4057
				do_action( 'jetpack_connection_register_success', $from );
4058
4059
				$url = $this->build_connect_url( true, $redirect, $from );
4060
4061
				if ( ! empty( $_GET['onboarding'] ) ) {
4062
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4063
				}
4064
4065
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4066
					$url = add_query_arg( 'auth_approved', 'true', $url );
4067
				}
4068
4069
				wp_redirect( $url );
4070
				exit;
4071
			case 'activate' :
4072
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4073
					$error = 'cheatin';
4074
					break;
4075
				}
4076
4077
				$module = stripslashes( $_GET['module'] );
4078
				check_admin_referer( "jetpack_activate-$module" );
4079
				Jetpack::log( 'activate', $module );
4080
				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...
4081
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4082
				}
4083
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4084
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4085
				exit;
4086
			case 'activate_default_modules' :
4087
				check_admin_referer( 'activate_default_modules' );
4088
				Jetpack::log( 'activate_default_modules' );
4089
				Jetpack::restate();
4090
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4091
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4092
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4093
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4094
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4095
				exit;
4096
			case 'disconnect' :
4097
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4098
					$error = 'cheatin';
4099
					break;
4100
				}
4101
4102
				check_admin_referer( 'jetpack-disconnect' );
4103
				Jetpack::log( 'disconnect' );
4104
				Jetpack::disconnect();
4105
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4106
				exit;
4107
			case 'reconnect' :
4108
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4109
					$error = 'cheatin';
4110
					break;
4111
				}
4112
4113
				check_admin_referer( 'jetpack-reconnect' );
4114
				Jetpack::log( 'reconnect' );
4115
				$this->disconnect();
4116
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4117
				exit;
4118 View Code Duplication
			case 'deactivate' :
4119
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4120
					$error = 'cheatin';
4121
					break;
4122
				}
4123
4124
				$modules = stripslashes( $_GET['module'] );
4125
				check_admin_referer( "jetpack_deactivate-$modules" );
4126
				foreach ( explode( ',', $modules ) as $module ) {
4127
					Jetpack::log( 'deactivate', $module );
4128
					Jetpack::deactivate_module( $module );
4129
					Jetpack::state( 'message', 'module_deactivated' );
4130
				}
4131
				Jetpack::state( 'module', $modules );
4132
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4133
				exit;
4134
			case 'unlink' :
4135
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4136
				check_admin_referer( 'jetpack-unlink' );
4137
				Jetpack::log( 'unlink' );
4138
				Connection_Manager::disconnect_user();
4139
				Jetpack::state( 'message', 'unlinked' );
4140
				if ( 'sub-unlink' == $redirect ) {
4141
					wp_safe_redirect( admin_url() );
4142
				} else {
4143
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4144
				}
4145
				exit;
4146
			case 'onboard' :
4147
				if ( ! current_user_can( 'manage_options' ) ) {
4148
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4149
				} else {
4150
					Jetpack::create_onboarding_token();
4151
					$url = $this->build_connect_url( true );
4152
4153
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4154
						$url = add_query_arg( 'onboarding', $token, $url );
4155
					}
4156
4157
					$calypso_env = $this->get_calypso_env();
4158
					if ( ! empty( $calypso_env ) ) {
4159
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4160
					}
4161
4162
					wp_redirect( $url );
4163
					exit;
4164
				}
4165
				exit;
4166
			default:
4167
				/**
4168
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4169
				 *
4170
				 * @since 2.6.0
4171
				 *
4172
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4173
				 */
4174
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4175
			}
4176
		}
4177
4178
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4179
			self::activate_new_modules( true );
4180
		}
4181
4182
		$message_code = Jetpack::state( 'message' );
4183
		if ( Jetpack::state( 'optin-manage' ) ) {
4184
			$activated_manage = $message_code;
4185
			$message_code = 'jetpack-manage';
4186
		}
4187
4188
		switch ( $message_code ) {
4189
		case 'jetpack-manage':
4190
			$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>';
4191
			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...
4192
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4193
			}
4194
			break;
4195
4196
		}
4197
4198
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4199
4200
		if ( ! empty( $deactivated_plugins ) ) {
4201
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4202
			$deactivated_titles  = array();
4203
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4204
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4205
					continue;
4206
				}
4207
4208
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4209
			}
4210
4211
			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...
4212
				if ( $this->message ) {
4213
					$this->message .= "<br /><br />\n";
4214
				}
4215
4216
				$this->message .= wp_sprintf(
4217
					_n(
4218
						'Jetpack contains the most recent version of the old %l plugin.',
4219
						'Jetpack contains the most recent versions of the old %l plugins.',
4220
						count( $deactivated_titles ),
4221
						'jetpack'
4222
					),
4223
					$deactivated_titles
4224
				);
4225
4226
				$this->message .= "<br />\n";
4227
4228
				$this->message .= _n(
4229
					'The old version has been deactivated and can be removed from your site.',
4230
					'The old versions have been deactivated and can be removed from your site.',
4231
					count( $deactivated_titles ),
4232
					'jetpack'
4233
				);
4234
			}
4235
		}
4236
4237
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4238
4239
		if ( $this->message || $this->error || $this->privacy_checks ) {
4240
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4241
		}
4242
4243
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4244
	}
4245
4246
	function admin_notices() {
4247
4248
		if ( $this->error ) {
4249
?>
4250
<div id="message" class="jetpack-message jetpack-err">
4251
	<div class="squeezer">
4252
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4253
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4254
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4255
<?php	endif; ?>
4256
	</div>
4257
</div>
4258
<?php
4259
		}
4260
4261
		if ( $this->message ) {
4262
?>
4263
<div id="message" class="jetpack-message">
4264
	<div class="squeezer">
4265
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4266
	</div>
4267
</div>
4268
<?php
4269
		}
4270
4271
		if ( $this->privacy_checks ) :
4272
			$module_names = $module_slugs = array();
4273
4274
			$privacy_checks = explode( ',', $this->privacy_checks );
4275
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4276
			foreach ( $privacy_checks as $module_slug ) {
4277
				$module = Jetpack::get_module( $module_slug );
4278
				if ( ! $module ) {
4279
					continue;
4280
				}
4281
4282
				$module_slugs[] = $module_slug;
4283
				$module_names[] = "<strong>{$module['name']}</strong>";
4284
			}
4285
4286
			$module_slugs = join( ',', $module_slugs );
4287
?>
4288
<div id="message" class="jetpack-message jetpack-err">
4289
	<div class="squeezer">
4290
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4291
		<p><?php
4292
			echo wp_kses(
4293
				wptexturize(
4294
					wp_sprintf(
4295
						_nx(
4296
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4297
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4298
							count( $privacy_checks ),
4299
							'%l = list of Jetpack module/feature names',
4300
							'jetpack'
4301
						),
4302
						$module_names
4303
					)
4304
				),
4305
				array( 'strong' => true )
4306
			);
4307
4308
			echo "\n<br />\n";
4309
4310
			echo wp_kses(
4311
				sprintf(
4312
					_nx(
4313
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4314
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4315
						count( $privacy_checks ),
4316
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4317
						'jetpack'
4318
					),
4319
					wp_nonce_url(
4320
						Jetpack::admin_url(
4321
							array(
4322
								'page'   => 'jetpack',
4323
								'action' => 'deactivate',
4324
								'module' => urlencode( $module_slugs ),
4325
							)
4326
						),
4327
						"jetpack_deactivate-$module_slugs"
4328
					),
4329
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4330
				),
4331
				array( 'a' => array( 'href' => true, 'title' => true ) )
4332
			);
4333
		?></p>
4334
	</div>
4335
</div>
4336
<?php endif;
4337
	}
4338
4339
	/**
4340
	 * We can't always respond to a signed XML-RPC request with a
4341
	 * helpful error message. In some circumstances, doing so could
4342
	 * leak information.
4343
	 *
4344
	 * Instead, track that the error occurred via a Jetpack_Option,
4345
	 * and send that data back in the heartbeat.
4346
	 * All this does is increment a number, but it's enough to find
4347
	 * trends.
4348
	 *
4349
	 * @param WP_Error $xmlrpc_error The error produced during
4350
	 *                               signature validation.
4351
	 */
4352
	function track_xmlrpc_error( $xmlrpc_error ) {
4353
		$code = is_wp_error( $xmlrpc_error )
4354
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4355
			: 'should-not-happen';
4356
4357
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4358
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4359
			// No need to update the option if we already have
4360
			// this code stored.
4361
			return;
4362
		}
4363
		$xmlrpc_errors[ $code ] = true;
4364
4365
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, 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...
4366
	}
4367
4368
	/**
4369
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4370
	 */
4371
	function stat( $group, $detail ) {
4372
		if ( ! isset( $this->stats[ $group ] ) )
4373
			$this->stats[ $group ] = array();
4374
		$this->stats[ $group ][] = $detail;
4375
	}
4376
4377
	/**
4378
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4379
	 */
4380
	function do_stats( $method = '' ) {
4381
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4382
			foreach ( $this->stats as $group => $stats ) {
4383
				if ( is_array( $stats ) && count( $stats ) ) {
4384
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4385
					if ( 'server_side' === $method ) {
4386
						self::do_server_side_stat( $args );
4387
					} else {
4388
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4389
					}
4390
				}
4391
				unset( $this->stats[ $group ] );
4392
			}
4393
		}
4394
	}
4395
4396
	/**
4397
	 * Runs stats code for a one-off, server-side.
4398
	 *
4399
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4400
	 *
4401
	 * @return bool If it worked.
4402
	 */
4403
	static function do_server_side_stat( $args ) {
4404
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4405
		if ( is_wp_error( $response ) )
4406
			return false;
4407
4408
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4409
			return false;
4410
4411
		return true;
4412
	}
4413
4414
	/**
4415
	 * Builds the stats url.
4416
	 *
4417
	 * @param $args array|string The arguments to append to the URL.
4418
	 *
4419
	 * @return string The URL to be pinged.
4420
	 */
4421
	static function build_stats_url( $args ) {
4422
		$defaults = array(
4423
			'v'    => 'wpcom2',
4424
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4425
		);
4426
		$args     = wp_parse_args( $args, $defaults );
4427
		/**
4428
		 * Filter the URL used as the Stats tracking pixel.
4429
		 *
4430
		 * @since 2.3.2
4431
		 *
4432
		 * @param string $url Base URL used as the Stats tracking pixel.
4433
		 */
4434
		$base_url = apply_filters(
4435
			'jetpack_stats_base_url',
4436
			'https://pixel.wp.com/g.gif'
4437
		);
4438
		$url      = add_query_arg( $args, $base_url );
4439
		return $url;
4440
	}
4441
4442
	/**
4443
	 * Get the role of the current user.
4444
	 *
4445
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4446
	 *
4447
	 * @access public
4448
	 * @static
4449
	 *
4450
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4451
	 */
4452
	public static function translate_current_user_to_role() {
4453
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4454
4455
		$roles = new Roles();
4456
		return $roles->translate_current_user_to_role();
4457
	}
4458
4459
	/**
4460
	 * Get the role of a particular user.
4461
	 *
4462
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4463
	 *
4464
	 * @access public
4465
	 * @static
4466
	 *
4467
	 * @param \WP_User $user User object.
4468
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4469
	 */
4470
	public static function translate_user_to_role( $user ) {
4471
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4472
4473
		$roles = new Roles();
4474
		return $roles->translate_user_to_role( $user );
4475
	}
4476
4477
	/**
4478
	 * Get the minimum capability for a role.
4479
	 *
4480
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4481
	 *
4482
	 * @access public
4483
	 * @static
4484
	 *
4485
	 * @param string $role Role name.
4486
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4487
	 */
4488
	public static function translate_role_to_cap( $role ) {
4489
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4490
4491
		$roles = new Roles();
4492
		return $roles->translate_role_to_cap( $role );
4493
	}
4494
4495
	/**
4496
	 * Sign a user role with the master access token.
4497
	 * If not specified, will default to the current user.
4498
	 *
4499
	 * @deprecated since 7.7
4500
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4501
	 *
4502
	 * @access public
4503
	 * @static
4504
	 *
4505
	 * @param string $role    User role.
4506
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|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...
4507
	 * @return string Signed user role.
4508
	 */
4509
	public static function sign_role( $role, $user_id = null ) {
4510
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4511
		return self::connection()->sign_role( $role, $user_id );
4512
	}
4513
4514
	/**
4515
	 * Builds a URL to the Jetpack connection auth page
4516
	 *
4517
	 * @since 3.9.5
4518
	 *
4519
	 * @param bool $raw If true, URL will not be escaped.
4520
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4521
	 *                              If string, will be a custom redirect.
4522
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4523
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4524
	 *
4525
	 * @return string Connect URL
4526
	 */
4527
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4528
		$site_id = Jetpack_Options::get_option( 'id' );
4529
		$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...
4530
4531
		if ( $register || ! $blog_token || ! $site_id ) {
4532
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4533
4534
			if ( ! empty( $redirect ) ) {
4535
				$url = add_query_arg(
4536
					'redirect',
4537
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4538
					$url
4539
				);
4540
			}
4541
4542
			if( is_network_admin() ) {
4543
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4544
			}
4545
4546
			$calypso_env = self::get_calypso_env();
4547
4548
			if ( ! empty( $calypso_env ) ) {
4549
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4550
			}
4551
4552
		} else {
4553
4554
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4555
			// because otherwise this logic can get us in to a loop.
4556
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4557
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4558
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4559
4560
				$response = Client::wpcom_json_api_request_as_blog(
4561
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4562
					'1.1'
4563
				);
4564
4565
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4566
4567
					// Generating a register URL instead to refresh the existing token
4568
					return $this->build_connect_url( $raw, $redirect, $from, true );
4569
				}
4570
			}
4571
4572
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4527 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4573
		}
4574
4575
		if ( $from ) {
4576
			$url = add_query_arg( 'from', $from, $url );
4577
		}
4578
4579
		// Ensure that class to get the affiliate code is loaded
4580
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4581
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4582
		}
4583
		// Get affiliate code and add it to the URL
4584
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4585
4586
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4587
	}
4588
4589
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4590
		if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4591
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4592
		}
4593
4594
		$roles       = new Roles();
4595
		$role        = $roles->translate_current_user_to_role();
4596
		$signed_role = self::connection()->sign_role( $role );
4597
4598
		$user = wp_get_current_user();
4599
4600
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4601
		$redirect = $redirect
4602
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4603
			: $jetpack_admin_page;
4604
4605
		if( isset( $_REQUEST['is_multisite'] ) ) {
4606
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4607
		}
4608
4609
		$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4610
4611
		/**
4612
		 * Filter the type of authorization.
4613
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4614
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4615
		 *
4616
		 * @since 4.3.3
4617
		 *
4618
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4619
		 */
4620
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4621
4622
4623
		$tracks = new Tracking();
4624
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4625
4626
		$args = urlencode_deep(
4627
			array(
4628
				'response_type' => 'code',
4629
				'client_id'     => Jetpack_Options::get_option( 'id' ),
4630
				'redirect_uri'  => add_query_arg(
4631
					array(
4632
						'action'   => 'authorize',
4633
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4634
						'redirect' => urlencode( $redirect ),
4635
					),
4636
					esc_url( admin_url( 'admin.php?page=jetpack' ) )
4637
				),
4638
				'state'         => $user->ID,
4639
				'scope'         => $signed_role,
4640
				'user_email'    => $user->user_email,
4641
				'user_login'    => $user->user_login,
4642
				'is_active'     => Jetpack::is_active(),
4643
				'jp_version'    => JETPACK__VERSION,
4644
				'auth_type'     => $auth_type,
4645
				'secret'        => $secrets['secret_1'],
4646
				'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4647
				'blogname'      => get_option( 'blogname' ),
4648
				'site_url'      => site_url(),
4649
				'home_url'      => home_url(),
4650
				'site_icon'     => get_site_icon_url(),
4651
				'site_lang'     => get_locale(),
4652
				'_ui'           => $tracks_identity['_ui'],
4653
				'_ut'           => $tracks_identity['_ut'],
4654
				'site_created'  => Jetpack::get_assumed_site_creation_date(),
4655
			)
4656
		);
4657
4658
		self::apply_activation_source_to_args( $args );
4659
4660
		$connection = self::connection();
4661
4662
		$calypso_env = self::get_calypso_env();
4663
4664
		if ( ! empty( $calypso_env ) ) {
4665
			$args['calypso_env'] = $calypso_env;
4666
		}
4667
4668
		$api_url = $iframe ? $connection->api_url( 'authorize_iframe' ) : $connection->api_url( 'authorize' );
4669
4670
		return add_query_arg( $args, $api_url );
4671
	}
4672
4673
	/**
4674
	 * Get our assumed site creation date.
4675
	 * Calculated based on the earlier date of either:
4676
	 * - Earliest admin user registration date.
4677
	 * - Earliest date of post of any post type.
4678
	 *
4679
	 * @since 7.2.0
4680
	 *
4681
	 * @return string Assumed site creation date and time.
4682
	 */
4683 View Code Duplication
	public static function get_assumed_site_creation_date() {
4684
		$earliest_registered_users = get_users( array(
4685
			'role'    => 'administrator',
4686
			'orderby' => 'user_registered',
4687
			'order'   => 'ASC',
4688
			'fields'  => array( 'user_registered' ),
4689
			'number'  => 1,
4690
		) );
4691
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4692
4693
		$earliest_posts = get_posts( array(
4694
			'posts_per_page' => 1,
4695
			'post_type'      => 'any',
4696
			'post_status'    => 'any',
4697
			'orderby'        => 'date',
4698
			'order'          => 'ASC',
4699
		) );
4700
4701
		// If there are no posts at all, we'll count only on user registration date.
4702
		if ( $earliest_posts ) {
4703
			$earliest_post_date = $earliest_posts[0]->post_date;
4704
		} else {
4705
			$earliest_post_date = PHP_INT_MAX;
4706
		}
4707
4708
		return min( $earliest_registration_date, $earliest_post_date );
4709
	}
4710
4711 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4712
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4713
4714
		if ( $activation_source_name ) {
4715
			$args['_as'] = urlencode( $activation_source_name );
4716
		}
4717
4718
		if ( $activation_source_keyword ) {
4719
			$args['_ak'] = urlencode( $activation_source_keyword );
4720
		}
4721
	}
4722
4723
	function build_reconnect_url( $raw = false ) {
4724
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4725
		return $raw ? $url : esc_url( $url );
4726
	}
4727
4728
	public static function admin_url( $args = null ) {
4729
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4730
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4731
		return $url;
4732
	}
4733
4734
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4735
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4736
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4737
	}
4738
4739
	function dismiss_jetpack_notice() {
4740
4741
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4742
			return;
4743
		}
4744
4745
		switch( $_GET['jetpack-notice'] ) {
4746
			case 'dismiss':
4747
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4748
4749
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4750
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4751
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4752
				}
4753
				break;
4754
		}
4755
	}
4756
4757
	public static function sort_modules( $a, $b ) {
4758
		if ( $a['sort'] == $b['sort'] )
4759
			return 0;
4760
4761
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4762
	}
4763
4764
	function ajax_recheck_ssl() {
4765
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4766
		$result = Jetpack::permit_ssl( true );
4767
		wp_send_json( array(
4768
			'enabled' => $result,
4769
			'message' => get_transient( 'jetpack_https_test_message' )
4770
		) );
4771
	}
4772
4773
/* Client API */
4774
4775
	/**
4776
	 * Returns the requested Jetpack API URL
4777
	 *
4778
	 * @deprecated since 7.7
4779
	 * @return string
4780
	 */
4781
	public static function api_url( $relative_url ) {
4782
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4783
		$connection = self::connection();
4784
		return $connection->api_url( $relative_url );
4785
	}
4786
4787
	/**
4788
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4789
	 */
4790
	public static function fix_url_for_bad_hosts( $url ) {
4791
		if ( 0 !== strpos( $url, 'https://' ) ) {
4792
			return $url;
4793
		}
4794
4795
		switch ( JETPACK_CLIENT__HTTPS ) {
4796
			case 'ALWAYS' :
4797
				return $url;
4798
			case 'NEVER' :
4799
				return set_url_scheme( $url, 'http' );
4800
			// default : case 'AUTO' :
4801
		}
4802
4803
		// we now return the unmodified SSL URL by default, as a security precaution
4804
		return $url;
4805
	}
4806
4807
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4808
		// Default to a blog token.
4809
		$token_type = 'blog';
4810
4811
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4812
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4813
			if ( ! empty( $_GET['onboarding'] ) ) {
4814
				$jpo = $_GET;
4815
			} else {
4816
				$jpo = json_decode( $request_data, true );
4817
			}
4818
4819
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4820
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4821
4822
			if (
4823
				isset( $jpo_user )
4824
				&& isset( $jpo_token )
4825
				&& is_email( $jpo_user )
4826
				&& ctype_alnum( $jpo_token )
4827
				&& isset( $_GET['rest_route'] )
4828
				&& self::validate_onboarding_token_action(
4829
					$jpo_token,
4830
					$_GET['rest_route']
4831
				)
4832
			) {
4833
				$jp_user = get_user_by( 'email', $jpo_user );
4834
				if ( is_a( $jp_user, 'WP_User' ) ) {
4835
					wp_set_current_user( $jp_user->ID );
4836
					$user_can = is_multisite()
4837
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4838
						: current_user_can( 'manage_options' );
4839
					if ( $user_can ) {
4840
						$token_type = 'user';
4841
						$token->external_user_id = $jp_user->ID;
4842
					}
4843
				}
4844
			}
4845
4846
			$token_data['type']    = $token_type;
4847
			$token_data['user_id'] = $token->external_user_id;
4848
		}
4849
4850
		return $token_data;
4851
	}
4852
4853
	/**
4854
	 * Create a random secret for validating onboarding payload
4855
	 *
4856
	 * @return string Secret token
4857
	 */
4858
	public static function create_onboarding_token() {
4859
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4860
			$token = wp_generate_password( 32, false );
4861
			Jetpack_Options::update_option( 'onboarding', $token );
4862
		}
4863
4864
		return $token;
4865
	}
4866
4867
	/**
4868
	 * Remove the onboarding token
4869
	 *
4870
	 * @return bool True on success, false on failure
4871
	 */
4872
	public static function invalidate_onboarding_token() {
4873
		return Jetpack_Options::delete_option( 'onboarding' );
4874
	}
4875
4876
	/**
4877
	 * Validate an onboarding token for a specific action
4878
	 *
4879
	 * @return boolean True if token/action pair is accepted, false if not
4880
	 */
4881
	public static function validate_onboarding_token_action( $token, $action ) {
4882
		// Compare tokens, bail if tokens do not match
4883
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4884
			return false;
4885
		}
4886
4887
		// List of valid actions we can take
4888
		$valid_actions = array(
4889
			'/jetpack/v4/settings',
4890
		);
4891
4892
		// Whitelist the action
4893
		if ( ! in_array( $action, $valid_actions ) ) {
4894
			return false;
4895
		}
4896
4897
		return true;
4898
	}
4899
4900
	/**
4901
	 * Checks to see if the URL is using SSL to connect with Jetpack
4902
	 *
4903
	 * @since 2.3.3
4904
	 * @return boolean
4905
	 */
4906
	public static function permit_ssl( $force_recheck = false ) {
4907
		// Do some fancy tests to see if ssl is being supported
4908
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4909
			$message = '';
4910
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4911
				$ssl = 0;
4912
			} else {
4913
				switch ( JETPACK_CLIENT__HTTPS ) {
4914
					case 'NEVER':
4915
						$ssl = 0;
4916
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4917
						break;
4918
					case 'ALWAYS':
4919
					case 'AUTO':
4920
					default:
4921
						$ssl = 1;
4922
						break;
4923
				}
4924
4925
				// If it's not 'NEVER', test to see
4926
				if ( $ssl ) {
4927
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4928
						$ssl = 0;
4929
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4930
					} else {
4931
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4932
						if ( is_wp_error( $response ) ) {
4933
							$ssl = 0;
4934
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4935
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4936
							$ssl = 0;
4937
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4938
						}
4939
					}
4940
				}
4941
			}
4942
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4943
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4944
		}
4945
4946
		return (bool) $ssl;
4947
	}
4948
4949
	/*
4950
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4951
	 */
4952
	public function alert_auto_ssl_fail() {
4953
		if ( ! current_user_can( 'manage_options' ) )
4954
			return;
4955
4956
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4957
		?>
4958
4959
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4960
			<div class="jp-banner__content">
4961
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4962
				<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>
4963
				<p>
4964
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4965
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4966
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4967
				</p>
4968
				<p>
4969
					<?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' ),
4970
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4971
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4972
				</p>
4973
			</div>
4974
		</div>
4975
		<style>
4976
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4977
		</style>
4978
		<script type="text/javascript">
4979
			jQuery( document ).ready( function( $ ) {
4980
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4981
					var $this = $( this );
4982
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4983
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4984
					e.preventDefault();
4985
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4986
					$.post( ajaxurl, data )
4987
					  .done( function( response ) {
4988
					  	if ( response.enabled ) {
4989
					  		$( '#jetpack-ssl-warning' ).hide();
4990
					  	} else {
4991
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4992
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4993
					  	}
4994
					  }.bind( $this ) );
4995
				} );
4996
			} );
4997
		</script>
4998
4999
		<?php
5000
	}
5001
5002
	/**
5003
	 * Returns the Jetpack XML-RPC API
5004
	 *
5005
	 * @return string
5006
	 */
5007
	public static function xmlrpc_api_url() {
5008
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
5009
		return untrailingslashit( $base ) . '/xmlrpc.php';
5010
	}
5011
5012
	public static function connection() {
5013
		return self::init()->connection_manager;
5014
	}
5015
5016
	/**
5017
	 * Creates two secret tokens and the end of life timestamp for them.
5018
	 *
5019
	 * Note these tokens are unique per call, NOT static per site for connecting.
5020
	 *
5021
	 * @since 2.6
5022
	 * @return array
5023
	 */
5024
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5025
		if ( false === $user_id ) {
5026
			$user_id = get_current_user_id();
5027
		}
5028
5029
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5030
	}
5031
5032
	public static function get_secrets( $action, $user_id ) {
5033
		$secrets = self::connection()->get_secrets( $action, $user_id );
5034
5035
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5036
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5037
		}
5038
5039
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5040
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5041
		}
5042
5043
		return $secrets;
5044
	}
5045
5046
	/**
5047
	 * @deprecated 7.5 Use Connection_Manager instead.
5048
	 *
5049
	 * @param $action
5050
	 * @param $user_id
5051
	 */
5052
	public static function delete_secrets( $action, $user_id ) {
5053
		return self::connection()->delete_secrets( $action, $user_id );
5054
	}
5055
5056
	/**
5057
	 * Builds the timeout limit for queries talking with the wpcom servers.
5058
	 *
5059
	 * Based on local php max_execution_time in php.ini
5060
	 *
5061
	 * @since 2.6
5062
	 * @return int
5063
	 * @deprecated
5064
	 **/
5065
	public function get_remote_query_timeout_limit() {
5066
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5067
		return Jetpack::get_max_execution_time();
5068
	}
5069
5070
	/**
5071
	 * Builds the timeout limit for queries talking with the wpcom servers.
5072
	 *
5073
	 * Based on local php max_execution_time in php.ini
5074
	 *
5075
	 * @since 5.4
5076
	 * @return int
5077
	 **/
5078
	public static function get_max_execution_time() {
5079
		$timeout = (int) ini_get( 'max_execution_time' );
5080
5081
		// Ensure exec time set in php.ini
5082
		if ( ! $timeout ) {
5083
			$timeout = 30;
5084
		}
5085
		return $timeout;
5086
	}
5087
5088
	/**
5089
	 * Sets a minimum request timeout, and returns the current timeout
5090
	 *
5091
	 * @since 5.4
5092
	 **/
5093 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5094
		$timeout = self::get_max_execution_time();
5095
		if ( $timeout < $min_timeout ) {
5096
			$timeout = $min_timeout;
5097
			set_time_limit( $timeout );
5098
		}
5099
		return $timeout;
5100
	}
5101
5102
	/**
5103
	 * Takes the response from the Jetpack register new site endpoint and
5104
	 * verifies it worked properly.
5105
	 *
5106
	 * @since 2.6
5107
	 * @deprecated since 7.7.0
5108
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5109
	 **/
5110
	public function validate_remote_register_response() {
5111
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5112
	}
5113
5114
	/**
5115
	 * @return bool|WP_Error
5116
	 */
5117
	public static function register() {
5118
		$tracking = new Tracking();
5119
		$tracking->record_user_event( 'jpc_register_begin' );
5120
5121
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5122
5123
		$connection = self::connection();
5124
		$registration = $connection->register();
5125
5126
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5127
5128
		if ( ! $registration || is_wp_error( $registration ) ) {
5129
			return $registration;
5130
		}
5131
5132
		return true;
5133
	}
5134
5135
	/**
5136
	 * Filters the registration request body to include tracking properties.
5137
	 *
5138
	 * @param Array $properties
5139
	 * @return Array amended properties.
5140
	 */
5141
	public static function filter_register_request_body( $properties ) {
5142
		$tracking = new Tracking();
5143
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5144
5145
		return array_merge(
5146
			$properties,
5147
			array(
5148
				'_ui' => $tracks_identity['_ui'],
5149
				'_ut' => $tracks_identity['_ut'],
5150
			)
5151
		);
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
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5179
	 *
5180
	 * @deprecated since 7.7.0
5181
	 */
5182
	public static function load_xml_rpc_client() {
5183
		// Removed the php notice that shows up in order to give time to Akismet and VaultPress time to update.
5184
		// _deprecated_function( __METHOD__, 'jetpack-7.7' );
5185
	}
5186
5187
	/**
5188
	 * Resets the saved authentication state in between testing requests.
5189
	 */
5190
	public function reset_saved_auth_state() {
5191
		$this->rest_authentication_status = null;
5192
		$this->connection_manager->reset_saved_auth_state();
5193
	}
5194
5195
	/**
5196
	 * Verifies the signature of the current request.
5197
	 *
5198
	 * @deprecated since 7.7.0
5199
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5200
	 *
5201
	 * @return false|array
5202
	 */
5203
	public function verify_xml_rpc_signature() {
5204
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5205
		return self::connection()->verify_xml_rpc_signature();
5206
	}
5207
5208
	/**
5209
	 * Verifies the signature of the current request.
5210
	 *
5211
	 * This function has side effects and should not be used. Instead,
5212
	 * use the memoized version `->verify_xml_rpc_signature()`.
5213
	 *
5214
	 * @deprecated since 7.7.0
5215
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5216
	 * @internal
5217
	 */
5218
	private function internal_verify_xml_rpc_signature() {
5219
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5220
	}
5221
5222
	/**
5223
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5224
	 *
5225
	 * @deprecated since 7.7.0
5226
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5227
	 *
5228
	 * @param \WP_User|mixed $user     User object if authenticated.
5229
	 * @param string         $username Username.
5230
	 * @param string         $password Password string.
5231
	 * @return \WP_User|mixed Authenticated user or error.
5232
	 */
5233
	public function authenticate_jetpack( $user, $username, $password ) {
5234
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5235
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5236
	}
5237
5238
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5239
	// Uses the existing XMLRPC request signing implementation.
5240
	function wp_rest_authenticate( $user ) {
5241
		if ( ! empty( $user ) ) {
5242
			// Another authentication method is in effect.
5243
			return $user;
5244
		}
5245
5246
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5247
			// Nothing to do for this authentication method.
5248
			return null;
5249
		}
5250
5251
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5252
			// Nothing to do for this authentication method.
5253
			return null;
5254
		}
5255
5256
		// Ensure that we always have the request body available.  At this
5257
		// point, the WP REST API code to determine the request body has not
5258
		// run yet.  That code may try to read from 'php://input' later, but
5259
		// this can only be done once per request in PHP versions prior to 5.6.
5260
		// So we will go ahead and perform this read now if needed, and save
5261
		// the request body where both the Jetpack signature verification code
5262
		// and the WP REST API code can see it.
5263
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5264
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5265
		}
5266
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5267
5268
		// Only support specific request parameters that have been tested and
5269
		// are known to work with signature verification.  A different method
5270
		// can be passed to the WP REST API via the '?_method=' parameter if
5271
		// needed.
5272
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5273
			$this->rest_authentication_status = new WP_Error(
5274
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5275
				__( 'This request method is not supported.', 'jetpack' ),
5276
				array( 'status' => 400 )
5277
			);
5278
			return null;
5279
		}
5280
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5281
			$this->rest_authentication_status = new WP_Error(
5282
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5283
				__( 'This request method does not support body parameters.', 'jetpack' ),
5284
				array( 'status' => 400 )
5285
			);
5286
			return null;
5287
		}
5288
5289
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5290
5291
		if (
5292
			$verified &&
5293
			isset( $verified['type'] ) &&
5294
			'user' === $verified['type'] &&
5295
			! empty( $verified['user_id'] )
5296
		) {
5297
			// Authentication successful.
5298
			$this->rest_authentication_status = true;
5299
			return $verified['user_id'];
5300
		}
5301
5302
		// Something else went wrong.  Probably a signature error.
5303
		$this->rest_authentication_status = new WP_Error(
5304
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5305
			__( 'The request is not signed correctly.', 'jetpack' ),
5306
			array( 'status' => 400 )
5307
		);
5308
		return null;
5309
	}
5310
5311
	/**
5312
	 * Report authentication status to the WP REST API.
5313
	 *
5314
	 * @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...
5315
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5316
	 */
5317
	public function wp_rest_authentication_errors( $value ) {
5318
		if ( $value !== null ) {
5319
			return $value;
5320
		}
5321
		return $this->rest_authentication_status;
5322
	}
5323
5324
	/**
5325
	 * Add our nonce to this request.
5326
	 *
5327
	 * @deprecated since 7.7.0
5328
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5329
	 *
5330
	 * @param int    $timestamp Timestamp of the request.
5331
	 * @param string $nonce     Nonce string.
5332
	 */
5333
	public function add_nonce( $timestamp, $nonce ) {
5334
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5335
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5336
	}
5337
5338
	/**
5339
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5340
	 * Capture it here so we can verify the signature later.
5341
	 *
5342
	 * @deprecated since 7.7.0
5343
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5344
	 *
5345
	 * @param array $methods XMLRPC methods.
5346
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5347
	 */
5348
	public function xmlrpc_methods( $methods ) {
5349
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5350
		return $this->connection_manager->xmlrpc_methods( $methods );
5351
	}
5352
5353
	/**
5354
	 * Register additional public XMLRPC methods.
5355
	 *
5356
	 * @deprecated since 7.7.0
5357
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5358
	 *
5359
	 * @param array $methods Public XMLRPC methods.
5360
	 * @return array Public XMLRPC methods, with the getOptions one.
5361
	 */
5362
	public function public_xmlrpc_methods( $methods ) {
5363
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5364
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5365
	}
5366
5367
	/**
5368
	 * Handles a getOptions XMLRPC method call.
5369
	 *
5370
	 * @deprecated since 7.7.0
5371
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5372
	 *
5373
	 * @param array $args method call arguments.
5374
	 * @return array an amended XMLRPC server options array.
5375
	 */
5376
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5377
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5378
		return $this->connection_manager->jetpack_getOptions( $args );
5379
	}
5380
5381
	/**
5382
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5383
	 *
5384
	 * @deprecated since 7.7.0
5385
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5386
	 *
5387
	 * @param array $options Standard Core options.
5388
	 * @return array Amended options.
5389
	 */
5390
	public function xmlrpc_options( $options ) {
5391
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5392
		return $this->connection_manager->xmlrpc_options( $options );
5393
	}
5394
5395
	/**
5396
	 * Cleans nonces that were saved when calling ::add_nonce.
5397
	 *
5398
	 * @deprecated since 7.7.0
5399
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5400
	 *
5401
	 * @param bool $all whether to clean even non-expired nonces.
5402
	 */
5403
	public static function clean_nonces( $all = false ) {
5404
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5405
		return self::connection()->clean_nonces( $all );
5406
	}
5407
5408
	/**
5409
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5410
	 * SET: state( $key, $value );
5411
	 * GET: $value = state( $key );
5412
	 *
5413
	 * @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...
5414
	 * @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...
5415
	 * @param bool $restate private
5416
	 */
5417
	public static function state( $key = null, $value = null, $restate = false ) {
5418
		static $state = array();
5419
		static $path, $domain;
5420
		if ( ! isset( $path ) ) {
5421
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5422
			$admin_url = Jetpack::admin_url();
5423
			$bits      = wp_parse_url( $admin_url );
5424
5425
			if ( is_array( $bits ) ) {
5426
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5427
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5428
			} else {
5429
				$path = $domain = null;
5430
			}
5431
		}
5432
5433
		// Extract state from cookies and delete cookies
5434
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5435
			$yum = $_COOKIE[ 'jetpackState' ];
5436
			unset( $_COOKIE[ 'jetpackState' ] );
5437
			foreach ( $yum as $k => $v ) {
5438
				if ( strlen( $v ) )
5439
					$state[ $k ] = $v;
5440
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5441
			}
5442
		}
5443
5444
		if ( $restate ) {
5445
			foreach ( $state as $k => $v ) {
5446
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5447
			}
5448
			return;
5449
		}
5450
5451
		// Get a state variable
5452
		if ( isset( $key ) && ! isset( $value ) ) {
5453
			if ( array_key_exists( $key, $state ) )
5454
				return $state[ $key ];
5455
			return null;
5456
		}
5457
5458
		// Set a state variable
5459
		if ( isset ( $key ) && isset( $value ) ) {
5460
			if( is_array( $value ) && isset( $value[0] ) ) {
5461
				$value = $value[0];
5462
			}
5463
			$state[ $key ] = $value;
5464
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5465
		}
5466
	}
5467
5468
	public static function restate() {
5469
		Jetpack::state( null, null, true );
5470
	}
5471
5472
	public static function check_privacy( $file ) {
5473
		static $is_site_publicly_accessible = null;
5474
5475
		if ( is_null( $is_site_publicly_accessible ) ) {
5476
			$is_site_publicly_accessible = false;
5477
5478
			$rpc = new Jetpack_IXR_Client();
5479
5480
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5481
			if ( $success ) {
5482
				$response = $rpc->getResponse();
5483
				if ( $response ) {
5484
					$is_site_publicly_accessible = true;
5485
				}
5486
			}
5487
5488
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5489
		}
5490
5491
		if ( $is_site_publicly_accessible ) {
5492
			return;
5493
		}
5494
5495
		$module_slug = self::get_module_slug( $file );
5496
5497
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5498
		if ( ! $privacy_checks ) {
5499
			$privacy_checks = $module_slug;
5500
		} else {
5501
			$privacy_checks .= ",$module_slug";
5502
		}
5503
5504
		Jetpack::state( 'privacy_checks', $privacy_checks );
5505
	}
5506
5507
	/**
5508
	 * Helper method for multicall XMLRPC.
5509
	 */
5510
	public static function xmlrpc_async_call() {
5511
		global $blog_id;
5512
		static $clients = array();
5513
5514
		$client_blog_id = is_multisite() ? $blog_id : 0;
5515
5516
		if ( ! isset( $clients[$client_blog_id] ) ) {
5517
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5518
			if ( function_exists( 'ignore_user_abort' ) ) {
5519
				ignore_user_abort( true );
5520
			}
5521
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5522
		}
5523
5524
		$args = func_get_args();
5525
5526
		if ( ! empty( $args[0] ) ) {
5527
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5528
		} elseif ( is_multisite() ) {
5529
			foreach ( $clients as $client_blog_id => $client ) {
5530
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5531
					continue;
5532
				}
5533
5534
				$switch_success = switch_to_blog( $client_blog_id, true );
5535
				if ( ! $switch_success ) {
5536
					continue;
5537
				}
5538
5539
				flush();
5540
				$client->query();
5541
5542
				restore_current_blog();
5543
			}
5544
		} else {
5545
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5546
				flush();
5547
				$clients[0]->query();
5548
			}
5549
		}
5550
	}
5551
5552
	public static function staticize_subdomain( $url ) {
5553
5554
		// Extract hostname from URL
5555
		$host = parse_url( $url, PHP_URL_HOST );
5556
5557
		// Explode hostname on '.'
5558
		$exploded_host = explode( '.', $host );
5559
5560
		// Retrieve the name and TLD
5561
		if ( count( $exploded_host ) > 1 ) {
5562
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5563
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5564
			// Rebuild domain excluding subdomains
5565
			$domain = $name . '.' . $tld;
5566
		} else {
5567
			$domain = $host;
5568
		}
5569
		// Array of Automattic domains
5570
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5571
5572
		// Return $url if not an Automattic domain
5573
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5574
			return $url;
5575
		}
5576
5577
		if ( is_ssl() ) {
5578
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5579
		}
5580
5581
		srand( crc32( basename( $url ) ) );
5582
		$static_counter = rand( 0, 2 );
5583
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5584
5585
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5586
	}
5587
5588
/* JSON API Authorization */
5589
5590
	/**
5591
	 * Handles the login action for Authorizing the JSON API
5592
	 */
5593
	function login_form_json_api_authorization() {
5594
		$this->verify_json_api_authorization_request();
5595
5596
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5597
5598
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5599
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5600
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5601
	}
5602
5603
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5604
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5605
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5606
			return $url;
5607
		}
5608
5609
		$parsed_url = parse_url( $url );
5610
		$url = strtok( $url, '?' );
5611
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5612
		if ( ! empty( $parsed_url['query'] ) )
5613
			$url .= "&{$parsed_url['query']}";
5614
5615
		return $url;
5616
	}
5617
5618
	// Make sure the POSTed request is handled by the same action
5619
	function preserve_action_in_login_form_for_json_api_authorization() {
5620
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5621
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5622
	}
5623
5624
	// If someone logs in to approve API access, store the Access Code in usermeta
5625
	function store_json_api_authorization_token( $user_login, $user ) {
5626
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5627
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5628
		$token = wp_generate_password( 32, false );
5629
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5630
	}
5631
5632
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5633
	function allow_wpcom_public_api_domain( $domains ) {
5634
		$domains[] = 'public-api.wordpress.com';
5635
		return $domains;
5636
	}
5637
5638
	static function is_redirect_encoded( $redirect_url ) {
5639
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5640
	}
5641
5642
	// Add all wordpress.com environments to the safe redirect whitelist
5643
	function allow_wpcom_environments( $domains ) {
5644
		$domains[] = 'wordpress.com';
5645
		$domains[] = 'wpcalypso.wordpress.com';
5646
		$domains[] = 'horizon.wordpress.com';
5647
		$domains[] = 'calypso.localhost';
5648
		return $domains;
5649
	}
5650
5651
	// Add the Access Code details to the public-api.wordpress.com redirect
5652
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5653
		return add_query_arg(
5654
			urlencode_deep(
5655
				array(
5656
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5657
					'jetpack-user-id' => (int) $user->ID,
5658
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5659
				)
5660
			),
5661
			$redirect_to
5662
		);
5663
	}
5664
5665
5666
	/**
5667
	 * Verifies the request by checking the signature
5668
	 *
5669
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5670
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5671
	 *
5672
	 * @param null|array $environment
5673
	 */
5674
	function verify_json_api_authorization_request( $environment = null ) {
5675
		$environment = is_null( $environment )
5676
			? $_REQUEST
5677
			: $environment;
5678
5679
		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...
5680
		$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...
5681
		if ( ! $token || empty( $token->secret ) ) {
5682
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5683
		}
5684
5685
		$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' );
5686
5687
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5688
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5689
			/**
5690
			 * Jetpack authorisation request Error.
5691
			 *
5692
			 * @since 7.5.0
5693
			 *
5694
			 */
5695
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5696
			$die_error = sprintf(
5697
				/* translators: %s is a URL */
5698
				__( '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' ),
5699
				'https://jetpack.com/support/double-encoding/'
5700
			);
5701
		}
5702
5703
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5704
5705
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5706
			$signature = $jetpack_signature->sign_request(
5707
				$environment['token'],
5708
				$environment['timestamp'],
5709
				$environment['nonce'],
5710
				'',
5711
				'GET',
5712
				$environment['jetpack_json_api_original_query'],
5713
				null,
5714
				true
5715
			);
5716
		} else {
5717
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5718
		}
5719
5720
		if ( ! $signature ) {
5721
			wp_die( $die_error );
5722
		} else if ( is_wp_error( $signature ) ) {
5723
			wp_die( $die_error );
5724
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5725
			if ( is_ssl() ) {
5726
				// 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
5727
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5728
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5729
					wp_die( $die_error );
5730
				}
5731
			} else {
5732
				wp_die( $die_error );
5733
			}
5734
		}
5735
5736
		$timestamp = (int) $environment['timestamp'];
5737
		$nonce     = stripslashes( (string) $environment['nonce'] );
5738
5739
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
Bug introduced by
The property connection does not seem to exist. Did you mean connection_manager?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
5740
			// De-nonce the nonce, at least for 5 minutes.
5741
			// 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)
5742
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5743
			if ( $old_nonce_time < time() - 300 ) {
5744
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5745
			}
5746
		}
5747
5748
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5749
		$data_filters = array(
5750
			'state'        => 'opaque',
5751
			'client_id'    => 'int',
5752
			'client_title' => 'string',
5753
			'client_image' => 'url',
5754
		);
5755
5756
		foreach ( $data_filters as $key => $sanitation ) {
5757
			if ( ! isset( $data->$key ) ) {
5758
				wp_die( $die_error );
5759
			}
5760
5761
			switch ( $sanitation ) {
5762
			case 'int' :
5763
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5764
				break;
5765
			case 'opaque' :
5766
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5767
				break;
5768
			case 'string' :
5769
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5770
				break;
5771
			case 'url' :
5772
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5773
				break;
5774
			}
5775
		}
5776
5777
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5778
			wp_die( $die_error );
5779
		}
5780
	}
5781
5782
	function login_message_json_api_authorization( $message ) {
5783
		return '<p class="message">' . sprintf(
5784
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5785
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5786
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5787
	}
5788
5789
	/**
5790
	 * Get $content_width, but with a <s>twist</s> filter.
5791
	 */
5792
	public static function get_content_width() {
5793
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5794
			? $GLOBALS['content_width']
5795
			: false;
5796
		/**
5797
		 * Filter the Content Width value.
5798
		 *
5799
		 * @since 2.2.3
5800
		 *
5801
		 * @param string $content_width Content Width value.
5802
		 */
5803
		return apply_filters( 'jetpack_content_width', $content_width );
5804
	}
5805
5806
	/**
5807
	 * Pings the WordPress.com Mirror Site for the specified options.
5808
	 *
5809
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5810
	 *
5811
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5812
	 */
5813
	public function get_cloud_site_options( $option_names ) {
5814
		$option_names = array_filter( (array) $option_names, 'is_string' );
5815
5816
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5817
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5818
		if ( $xml->isError() ) {
5819
			return array(
5820
				'error_code' => $xml->getErrorCode(),
5821
				'error_msg'  => $xml->getErrorMessage(),
5822
			);
5823
		}
5824
		$cloud_site_options = $xml->getResponse();
5825
5826
		return $cloud_site_options;
5827
	}
5828
5829
	/**
5830
	 * Checks if the site is currently in an identity crisis.
5831
	 *
5832
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5833
	 */
5834
	public static function check_identity_crisis() {
5835
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5836
			return false;
5837
		}
5838
5839
		return Jetpack_Options::get_option( 'sync_error_idc' );
5840
	}
5841
5842
	/**
5843
	 * Checks whether the home and siteurl specifically are whitelisted
5844
	 * Written so that we don't have re-check $key and $value params every time
5845
	 * we want to check if this site is whitelisted, for example in footer.php
5846
	 *
5847
	 * @since  3.8.0
5848
	 * @return bool True = already whitelisted False = not whitelisted
5849
	 */
5850
	public static function is_staging_site() {
5851
		$is_staging = false;
5852
5853
		$known_staging = array(
5854
			'urls' => array(
5855
				'#\.staging\.wpengine\.com$#i', // WP Engine
5856
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5857
				'#\.stage\.site$#i'             // DreamPress
5858
			),
5859
			'constants' => array(
5860
				'IS_WPE_SNAPSHOT',      // WP Engine
5861
				'KINSTA_DEV_ENV',       // Kinsta.com
5862
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5863
				'JETPACK_STAGING_MODE', // Generic
5864
			)
5865
		);
5866
		/**
5867
		 * Filters the flags of known staging sites.
5868
		 *
5869
		 * @since 3.9.0
5870
		 *
5871
		 * @param array $known_staging {
5872
		 *     An array of arrays that each are used to check if the current site is staging.
5873
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5874
		 *     @type array $constants PHP constants of known staging/developement environments.
5875
		 *  }
5876
		 */
5877
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5878
5879
		if ( isset( $known_staging['urls'] ) ) {
5880
			foreach ( $known_staging['urls'] as $url ){
5881
				if ( preg_match( $url, site_url() ) ) {
5882
					$is_staging = true;
5883
					break;
5884
				}
5885
			}
5886
		}
5887
5888
		if ( isset( $known_staging['constants'] ) ) {
5889
			foreach ( $known_staging['constants'] as $constant ) {
5890
				if ( defined( $constant ) && constant( $constant ) ) {
5891
					$is_staging = true;
5892
				}
5893
			}
5894
		}
5895
5896
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5897
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5898
			$is_staging = true;
5899
		}
5900
5901
		/**
5902
		 * Filters is_staging_site check.
5903
		 *
5904
		 * @since 3.9.0
5905
		 *
5906
		 * @param bool $is_staging If the current site is a staging site.
5907
		 */
5908
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5909
	}
5910
5911
	/**
5912
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5913
	 *
5914
	 * @since 4.4.0
5915
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5916
	 *
5917
	 * @return bool
5918
	 */
5919
	public static function validate_sync_error_idc_option() {
5920
		$is_valid = false;
5921
5922
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5923
		if ( false === $idc_allowed ) {
5924
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5925
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5926
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5927
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5928
				$transient_duration = HOUR_IN_SECONDS;
5929
			} else {
5930
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5931
				$idc_allowed = '1';
5932
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5933
			}
5934
5935
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5936
		}
5937
5938
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5939
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5940
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5941
			$local_options = self::get_sync_error_idc_option();
5942
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5943
				$is_valid = true;
5944
			}
5945
		}
5946
5947
		/**
5948
		 * Filters whether the sync_error_idc option is valid.
5949
		 *
5950
		 * @since 4.4.0
5951
		 *
5952
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5953
		 */
5954
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5955
5956
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5957
			// Since the option exists, and did not validate, delete it
5958
			Jetpack_Options::delete_option( 'sync_error_idc' );
5959
		}
5960
5961
		return $is_valid;
5962
	}
5963
5964
	/**
5965
	 * Normalizes a url by doing three things:
5966
	 *  - Strips protocol
5967
	 *  - Strips www
5968
	 *  - Adds a trailing slash
5969
	 *
5970
	 * @since 4.4.0
5971
	 * @param string $url
5972
	 * @return WP_Error|string
5973
	 */
5974
	public static function normalize_url_protocol_agnostic( $url ) {
5975
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5976
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5977
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5978
		}
5979
5980
		// Strip www and protocols
5981
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5982
		return $url;
5983
	}
5984
5985
	/**
5986
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5987
	 *
5988
	 * @since 4.4.0
5989
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5990
	 *
5991
	 * @param array $response
5992
	 * @return array Array of the local urls, wpcom urls, and error code
5993
	 */
5994
	public static function get_sync_error_idc_option( $response = array() ) {
5995
		// Since the local options will hit the database directly, store the values
5996
		// in a transient to allow for autoloading and caching on subsequent views.
5997
		$local_options = get_transient( 'jetpack_idc_local' );
5998
		if ( false === $local_options ) {
5999
			$local_options = array(
6000
				'home'    => Functions::home_url(),
6001
				'siteurl' => Functions::site_url(),
6002
			);
6003
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6004
		}
6005
6006
		$options = array_merge( $local_options, $response );
6007
6008
		$returned_values = array();
6009
		foreach( $options as $key => $option ) {
6010
			if ( 'error_code' === $key ) {
6011
				$returned_values[ $key ] = $option;
6012
				continue;
6013
			}
6014
6015
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6016
				continue;
6017
			}
6018
6019
			$returned_values[ $key ] = $normalized_url;
6020
		}
6021
6022
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6023
6024
		return $returned_values;
6025
	}
6026
6027
	/**
6028
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6029
	 * If set to true, the site will be put into staging mode.
6030
	 *
6031
	 * @since 4.3.2
6032
	 * @return bool
6033
	 */
6034
	public static function sync_idc_optin() {
6035
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6036
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6037
		} else {
6038
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6039
		}
6040
6041
		/**
6042
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6043
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6044
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6045
		 *
6046
		 * @since 4.3.2
6047
		 *
6048
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6049
		 */
6050
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6051
	}
6052
6053
	/**
6054
	 * Maybe Use a .min.css stylesheet, maybe not.
6055
	 *
6056
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6057
	 */
6058
	public static function maybe_min_asset( $url, $path, $plugin ) {
6059
		// Short out on things trying to find actual paths.
6060
		if ( ! $path || empty( $plugin ) ) {
6061
			return $url;
6062
		}
6063
6064
		$path = ltrim( $path, '/' );
6065
6066
		// Strip out the abspath.
6067
		$base = dirname( plugin_basename( $plugin ) );
6068
6069
		// Short out on non-Jetpack assets.
6070
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6071
			return $url;
6072
		}
6073
6074
		// File name parsing.
6075
		$file              = "{$base}/{$path}";
6076
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6077
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6078
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6079
		$extension         = array_shift( $file_name_parts_r );
6080
6081
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6082
			// Already pointing at the minified version.
6083
			if ( 'min' === $file_name_parts_r[0] ) {
6084
				return $url;
6085
			}
6086
6087
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6088
			if ( file_exists( $min_full_path ) ) {
6089
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6090
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6091
				if ( 'css' === $extension ) {
6092
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6093
					self::$min_assets[ $key ] = $path;
6094
				}
6095
			}
6096
		}
6097
6098
		return $url;
6099
	}
6100
6101
	/**
6102
	 * If the asset is minified, let's flag .min as the suffix.
6103
	 *
6104
	 * Attached to `style_loader_src` filter.
6105
	 *
6106
	 * @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...
6107
	 * @param string $handle The registered handle of the script in question.
6108
	 * @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...
6109
	 */
6110
	public static function set_suffix_on_min( $src, $handle ) {
6111
		if ( false === strpos( $src, '.min.css' ) ) {
6112
			return $src;
6113
		}
6114
6115
		if ( ! empty( self::$min_assets ) ) {
6116
			foreach ( self::$min_assets as $file => $path ) {
6117
				if ( false !== strpos( $src, $file ) ) {
6118
					wp_style_add_data( $handle, 'suffix', '.min' );
6119
					return $src;
6120
				}
6121
			}
6122
		}
6123
6124
		return $src;
6125
	}
6126
6127
	/**
6128
	 * Maybe inlines a stylesheet.
6129
	 *
6130
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6131
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6132
	 *
6133
	 * Attached to `style_loader_tag` filter.
6134
	 *
6135
	 * @param string $tag The tag that would link to the external asset.
6136
	 * @param string $handle The registered handle of the script in question.
6137
	 *
6138
	 * @return string
6139
	 */
6140
	public static function maybe_inline_style( $tag, $handle ) {
6141
		global $wp_styles;
6142
		$item = $wp_styles->registered[ $handle ];
6143
6144
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6145
			return $tag;
6146
		}
6147
6148
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6149
			$href = $matches[1];
6150
			// Strip off query string
6151
			if ( $pos = strpos( $href, '?' ) ) {
6152
				$href = substr( $href, 0, $pos );
6153
			}
6154
			// Strip off fragment
6155
			if ( $pos = strpos( $href, '#' ) ) {
6156
				$href = substr( $href, 0, $pos );
6157
			}
6158
		} else {
6159
			return $tag;
6160
		}
6161
6162
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6163
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6164
			return $tag;
6165
		}
6166
6167
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6168
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6169
			// And this isn't the pass that actually deals with the RTL version...
6170
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6171
				// Short out, as the RTL version will deal with it in a moment.
6172
				return $tag;
6173
			}
6174
		}
6175
6176
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6177
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6178
		if ( $css ) {
6179
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6180
			if ( empty( $item->extra['after'] ) ) {
6181
				wp_add_inline_style( $handle, $css );
6182
			} else {
6183
				array_unshift( $item->extra['after'], $css );
6184
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6185
			}
6186
		}
6187
6188
		return $tag;
6189
	}
6190
6191
	/**
6192
	 * Loads a view file from the views
6193
	 *
6194
	 * Data passed in with the $data parameter will be available in the
6195
	 * template file as $data['value']
6196
	 *
6197
	 * @param string $template - Template file to load
6198
	 * @param array $data - Any data to pass along to the template
6199
	 * @return boolean - If template file was found
6200
	 **/
6201
	public function load_view( $template, $data = array() ) {
6202
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6203
6204
		if( file_exists( $views_dir . $template ) ) {
6205
			require_once( $views_dir . $template );
6206
			return true;
6207
		}
6208
6209
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6210
		return false;
6211
	}
6212
6213
	/**
6214
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6215
	 */
6216
	public function deprecated_hooks() {
6217
		global $wp_filter;
6218
6219
		/*
6220
		 * Format:
6221
		 * deprecated_filter_name => replacement_name
6222
		 *
6223
		 * If there is no replacement, use null for replacement_name
6224
		 */
6225
		$deprecated_list = array(
6226
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6227
			'wpl_sharing_2014_1'                                     => null,
6228
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6229
			'jetpack_identity_crisis_options_to_check'               => null,
6230
			'update_option_jetpack_single_user_site'                 => null,
6231
			'audio_player_default_colors'                            => null,
6232
			'add_option_jetpack_featured_images_enabled'             => null,
6233
			'add_option_jetpack_update_details'                      => null,
6234
			'add_option_jetpack_updates'                             => null,
6235
			'add_option_jetpack_network_name'                        => null,
6236
			'add_option_jetpack_network_allow_new_registrations'     => null,
6237
			'add_option_jetpack_network_add_new_users'               => null,
6238
			'add_option_jetpack_network_site_upload_space'           => null,
6239
			'add_option_jetpack_network_upload_file_types'           => null,
6240
			'add_option_jetpack_network_enable_administration_menus' => null,
6241
			'add_option_jetpack_is_multi_site'                       => null,
6242
			'add_option_jetpack_is_main_network'                     => null,
6243
			'add_option_jetpack_main_network_site'                   => null,
6244
			'jetpack_sync_all_registered_options'                    => null,
6245
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6246
			'jetpack_is_post_mailable'                               => null,
6247
			'jetpack_seo_site_host'                                  => null,
6248
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6249
			'jetpack_holiday_snow_option_name'                       => null,
6250
			'jetpack_holiday_chance_of_snow'                         => null,
6251
			'jetpack_holiday_snow_js_url'                            => null,
6252
			'jetpack_is_holiday_snow_season'                         => null,
6253
			'jetpack_holiday_snow_option_updated'                    => null,
6254
			'jetpack_holiday_snowing'                                => null,
6255
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6256
			'jetpack_cache_plans'                                    => null,
6257
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6258
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6259
			'jetpack_enable_site_verification'                       => null,
6260
			'can_display_jetpack_manage_notice'                      => null,
6261
			// Removed in Jetpack 7.3.0
6262
			'atd_load_scripts'                                       => null,
6263
			'atd_http_post_timeout'                                  => null,
6264
			'atd_http_post_error'                                    => null,
6265
			'atd_service_domain'                                     => null,
6266
			'jetpack_widget_authors_exclude'                         => 'jetpack_widget_authors_params',
6267
		);
6268
6269
		// This is a silly loop depth. Better way?
6270
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6271
			if ( has_action( $hook ) ) {
6272
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6273
					foreach( $values AS $hooked ) {
6274
						if ( is_callable( $hooked['function'] ) ) {
6275
							$function_name = 'an anonymous function';
6276
						} else {
6277
							$function_name = $hooked['function'];
6278
						}
6279
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6280
					}
6281
				}
6282
			}
6283
		}
6284
	}
6285
6286
	/**
6287
	 * Converts any url in a stylesheet, to the correct absolute url.
6288
	 *
6289
	 * Considerations:
6290
	 *  - Normal, relative URLs     `feh.png`
6291
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6292
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6293
	 *  - Absolute URLs             `http://domain.com/feh.png`
6294
	 *  - Domain root relative URLs `/feh.png`
6295
	 *
6296
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6297
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6298
	 *
6299
	 * @return mixed|string
6300
	 */
6301
	public static function absolutize_css_urls( $css, $css_file_url ) {
6302
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6303
		$css_dir = dirname( $css_file_url );
6304
		$p       = parse_url( $css_dir );
6305
		$domain  = sprintf(
6306
					'%1$s//%2$s%3$s%4$s',
6307
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6308
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6309
					$p['host'],
6310
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6311
				);
6312
6313
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6314
			$find = $replace = array();
6315
			foreach ( $matches as $match ) {
6316
				$url = trim( $match['path'], "'\" \t" );
6317
6318
				// If this is a data url, we don't want to mess with it.
6319
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6320
					continue;
6321
				}
6322
6323
				// If this is an absolute or protocol-agnostic url,
6324
				// we don't want to mess with it.
6325
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6326
					continue;
6327
				}
6328
6329
				switch ( substr( $url, 0, 1 ) ) {
6330
					case '/':
6331
						$absolute = $domain . $url;
6332
						break;
6333
					default:
6334
						$absolute = $css_dir . '/' . $url;
6335
				}
6336
6337
				$find[]    = $match[0];
6338
				$replace[] = sprintf( 'url("%s")', $absolute );
6339
			}
6340
			$css = str_replace( $find, $replace, $css );
6341
		}
6342
6343
		return $css;
6344
	}
6345
6346
	/**
6347
	 * This methods removes all of the registered css files on the front end
6348
	 * from Jetpack in favor of using a single file. In effect "imploding"
6349
	 * all the files into one file.
6350
	 *
6351
	 * Pros:
6352
	 * - Uses only ONE css asset connection instead of 15
6353
	 * - Saves a minimum of 56k
6354
	 * - Reduces server load
6355
	 * - Reduces time to first painted byte
6356
	 *
6357
	 * Cons:
6358
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6359
	 *		should not cause any issues with themes.
6360
	 * - Plugins/themes dequeuing styles no longer do anything. See
6361
	 *		jetpack_implode_frontend_css filter for a workaround
6362
	 *
6363
	 * For some situations developers may wish to disable css imploding and
6364
	 * instead operate in legacy mode where each file loads seperately and
6365
	 * can be edited individually or dequeued. This can be accomplished with
6366
	 * the following line:
6367
	 *
6368
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6369
	 *
6370
	 * @since 3.2
6371
	 **/
6372
	public function implode_frontend_css( $travis_test = false ) {
6373
		$do_implode = true;
6374
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6375
			$do_implode = false;
6376
		}
6377
6378
		// Do not implode CSS when the page loads via the AMP plugin.
6379
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6380
			$do_implode = false;
6381
		}
6382
6383
		/**
6384
		 * Allow CSS to be concatenated into a single jetpack.css file.
6385
		 *
6386
		 * @since 3.2.0
6387
		 *
6388
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6389
		 */
6390
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6391
6392
		// Do not use the imploded file when default behavior was altered through the filter
6393
		if ( ! $do_implode ) {
6394
			return;
6395
		}
6396
6397
		// We do not want to use the imploded file in dev mode, or if not connected
6398
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6399
			if ( ! $travis_test ) {
6400
				return;
6401
			}
6402
		}
6403
6404
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6405
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6406
			return;
6407
		}
6408
6409
		/*
6410
		 * Now we assume Jetpack is connected and able to serve the single
6411
		 * file.
6412
		 *
6413
		 * In the future there will be a check here to serve the file locally
6414
		 * or potentially from the Jetpack CDN
6415
		 *
6416
		 * For now:
6417
		 * - Enqueue a single imploded css file
6418
		 * - Zero out the style_loader_tag for the bundled ones
6419
		 * - Be happy, drink scotch
6420
		 */
6421
6422
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6423
6424
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6425
6426
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6427
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6428
	}
6429
6430
	function concat_remove_style_loader_tag( $tag, $handle ) {
6431
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6432
			$tag = '';
6433
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6434
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6435
			}
6436
		}
6437
6438
		return $tag;
6439
	}
6440
6441
	/**
6442
	 * Add an async attribute to scripts that can be loaded asynchronously.
6443
	 * https://www.w3schools.com/tags/att_script_async.asp
6444
	 *
6445
	 * @since 7.7.0
6446
	 *
6447
	 * @param string $tag    The <script> tag for the enqueued script.
6448
	 * @param string $handle The script's registered handle.
6449
	 * @param string $src    The script's source URL.
6450
	 */
6451
	public function script_add_async( $tag, $handle, $src ) {
6452
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6453
			return preg_replace( '/^<script /i', '<script async ', $tag );
6454
		}
6455
6456
		return $tag;
6457
	}
6458
6459
	/*
6460
	 * Check the heartbeat data
6461
	 *
6462
	 * Organizes the heartbeat data by severity.  For example, if the site
6463
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6464
	 *
6465
	 * Data will be added to "caution" array, if it either:
6466
	 *  - Out of date Jetpack version
6467
	 *  - Out of date WP version
6468
	 *  - Out of date PHP version
6469
	 *
6470
	 * $return array $filtered_data
6471
	 */
6472
	public static function jetpack_check_heartbeat_data() {
6473
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6474
6475
		$good    = array();
6476
		$caution = array();
6477
		$bad     = array();
6478
6479
		foreach ( $raw_data as $stat => $value ) {
6480
6481
			// Check jetpack version
6482
			if ( 'version' == $stat ) {
6483
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6484
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6485
					continue;
6486
				}
6487
			}
6488
6489
			// Check WP version
6490
			if ( 'wp-version' == $stat ) {
6491
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6492
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6493
					continue;
6494
				}
6495
			}
6496
6497
			// Check PHP version
6498
			if ( 'php-version' == $stat ) {
6499
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6500
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6501
					continue;
6502
				}
6503
			}
6504
6505
			// Check ID crisis
6506
			if ( 'identitycrisis' == $stat ) {
6507
				if ( 'yes' == $value ) {
6508
					$bad[ $stat ] = $value;
6509
					continue;
6510
				}
6511
			}
6512
6513
			// The rest are good :)
6514
			$good[ $stat ] = $value;
6515
		}
6516
6517
		$filtered_data = array(
6518
			'good'    => $good,
6519
			'caution' => $caution,
6520
			'bad'     => $bad
6521
		);
6522
6523
		return $filtered_data;
6524
	}
6525
6526
6527
	/*
6528
	 * This method is used to organize all options that can be reset
6529
	 * without disconnecting Jetpack.
6530
	 *
6531
	 * It is used in class.jetpack-cli.php to reset options
6532
	 *
6533
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6534
	 *
6535
	 * @return array of options to delete.
6536
	 */
6537
	public static function get_jetpack_options_for_reset() {
6538
		return Jetpack_Options::get_options_for_reset();
6539
	}
6540
6541
	/*
6542
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6543
	 * so we can bring them directly to their site in calypso.
6544
	 *
6545
	 * @param string | url
6546
	 * @return string | url without the guff
6547
	 */
6548
	public static function build_raw_urls( $url ) {
6549
		$strip_http = '/.*?:\/\//i';
6550
		$url = preg_replace( $strip_http, '', $url  );
6551
		$url = str_replace( '/', '::', $url );
6552
		return $url;
6553
	}
6554
6555
	/**
6556
	 * Stores and prints out domains to prefetch for page speed optimization.
6557
	 *
6558
	 * @param mixed $new_urls
6559
	 */
6560
	public static function dns_prefetch( $new_urls = null ) {
6561
		static $prefetch_urls = array();
6562
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6563
			echo "\r\n";
6564
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6565
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6566
			}
6567
		} elseif ( ! empty( $new_urls ) ) {
6568
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6569
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6570
			}
6571
			foreach ( (array) $new_urls as $this_new_url ) {
6572
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6573
			}
6574
			$prefetch_urls = array_unique( $prefetch_urls );
6575
		}
6576
	}
6577
6578
	public function wp_dashboard_setup() {
6579
		if ( self::is_active() ) {
6580
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6581
		}
6582
6583
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6584
			$jetpack_logo = new Jetpack_Logo();
6585
			$widget_title = sprintf(
6586
				wp_kses(
6587
					/* translators: Placeholder is a Jetpack logo. */
6588
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6589
					array( 'span' => array() )
6590
				),
6591
				$jetpack_logo->get_jp_emblem( true )
6592
			);
6593
6594
			wp_add_dashboard_widget(
6595
				'jetpack_summary_widget',
6596
				$widget_title,
6597
				array( __CLASS__, 'dashboard_widget' )
6598
			);
6599
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6600
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6601
6602
			// If we're inactive and not in development mode, sort our box to the top.
6603
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6604
				global $wp_meta_boxes;
6605
6606
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6607
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6608
6609
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6610
			}
6611
		}
6612
	}
6613
6614
	/**
6615
	 * @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...
6616
	 * @return mixed
6617
	 */
6618
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6619
		if ( ! is_array( $sorted ) ) {
6620
			return $sorted;
6621
		}
6622
6623
		foreach ( $sorted as $box_context => $ids ) {
6624
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6625
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6626
				continue;
6627
			}
6628
6629
			$ids_array = explode( ',', $ids );
6630
			$key = array_search( 'dashboard_stats', $ids_array );
6631
6632
			if ( false !== $key ) {
6633
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6634
				$ids_array[ $key ] = 'jetpack_summary_widget';
6635
				$sorted[ $box_context ] = implode( ',', $ids_array );
6636
				// We've found it, stop searching, and just return.
6637
				break;
6638
			}
6639
		}
6640
6641
		return $sorted;
6642
	}
6643
6644
	public static function dashboard_widget() {
6645
		/**
6646
		 * Fires when the dashboard is loaded.
6647
		 *
6648
		 * @since 3.4.0
6649
		 */
6650
		do_action( 'jetpack_dashboard_widget' );
6651
	}
6652
6653
	public static function dashboard_widget_footer() {
6654
		?>
6655
		<footer>
6656
6657
		<div class="protect">
6658
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6659
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6660
				<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>
6661
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6662
				<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' ); ?>">
6663
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6664
				</a>
6665
			<?php else : ?>
6666
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6667
			<?php endif; ?>
6668
		</div>
6669
6670
		<div class="akismet">
6671
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6672
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6673
				<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>
6674
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6675
				<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">
6676
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6677
				</a>
6678
			<?php else : ?>
6679
				<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>
6680
			<?php endif; ?>
6681
		</div>
6682
6683
		</footer>
6684
		<?php
6685
	}
6686
6687
	/*
6688
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6689
	 */
6690
	function jetpack_icon_user_connected( $columns ) {
6691
		$columns['user_jetpack'] = '';
6692
		return $columns;
6693
	}
6694
6695
	/*
6696
	 * Show Jetpack icon if the user is linked.
6697
	 */
6698
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6699
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6700
			$jetpack_logo = new Jetpack_Logo();
6701
			$emblem_html = sprintf(
6702
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6703
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6704
				$jetpack_logo->get_jp_emblem()
6705
			);
6706
			return $emblem_html;
6707
		}
6708
6709
		return $val;
6710
	}
6711
6712
	/*
6713
	 * Style the Jetpack user column
6714
	 */
6715
	function jetpack_user_col_style() {
6716
		global $current_screen;
6717
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6718
			<style>
6719
				.fixed .column-user_jetpack {
6720
					width: 21px;
6721
				}
6722
				.jp-emblem-user-admin svg {
6723
					width: 20px;
6724
					height: 20px;
6725
				}
6726
				.jp-emblem-user-admin path {
6727
					fill: #00BE28;
6728
				}
6729
			</style>
6730
		<?php }
6731
	}
6732
6733
	/**
6734
	 * Checks if Akismet is active and working.
6735
	 *
6736
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6737
	 * that implied usage of methods present since more recent version.
6738
	 * See https://github.com/Automattic/jetpack/pull/9585
6739
	 *
6740
	 * @since  5.1.0
6741
	 *
6742
	 * @return bool True = Akismet available. False = Aksimet not available.
6743
	 */
6744
	public static function is_akismet_active() {
6745
		static $status = null;
6746
6747
		if ( ! is_null( $status ) ) {
6748
			return $status;
6749
		}
6750
6751
		// Check if a modern version of Akismet is active.
6752
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6753
			$status = false;
6754
			return $status;
6755
		}
6756
6757
		// Make sure there is a key known to Akismet at all before verifying key.
6758
		$akismet_key = Akismet::get_api_key();
6759
		if ( ! $akismet_key ) {
6760
			$status = false;
6761
			return $status;
6762
		}
6763
6764
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6765
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6766
6767
		// 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.
6768
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6769
		// We cache the result of the Akismet key verification for ten minutes.
6770
		if ( ! $akismet_key_state || $recheck ) {
6771
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6772
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6773
		}
6774
6775
		$status = 'valid' === $akismet_key_state;
6776
6777
		return $status;
6778
	}
6779
6780
	/**
6781
	 * @deprecated
6782
	 *
6783
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6784
	 */
6785
	public static function is_function_in_backtrace() {
6786
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6787
	}
6788
6789
	/**
6790
	 * Given a minified path, and a non-minified path, will return
6791
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6792
	 *
6793
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6794
	 * root Jetpack directory.
6795
	 *
6796
	 * @since 5.6.0
6797
	 *
6798
	 * @param string $min_path
6799
	 * @param string $non_min_path
6800
	 * @return string The URL to the file
6801
	 */
6802
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6803
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6804
	}
6805
6806
	/**
6807
	 * Checks for whether Jetpack Backup & Scan is enabled.
6808
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6809
	 * @return bool|int|mixed
6810
	 */
6811
	public static function is_rewind_enabled() {
6812
		if ( ! Jetpack::is_active() ) {
6813
			return false;
6814
		}
6815
6816
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6817
		if ( false === $rewind_enabled ) {
6818
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6819
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6820
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6821
				&& ! empty( $rewind_data['state'] )
6822
				&& 'active' === $rewind_data['state'] )
6823
				? 1
6824
				: 0;
6825
6826
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6827
		}
6828
		return $rewind_enabled;
6829
	}
6830
6831
	/**
6832
	 * Return Calypso environment value; used for developing Jetpack and pairing
6833
	 * it with different Calypso enrionments, such as localhost.
6834
	 *
6835
	 * @since 7.4.0
6836
	 *
6837
	 * @return string Calypso environment
6838
	 */
6839
	public static function get_calypso_env() {
6840
		if ( isset( $_GET['calypso_env'] ) ) {
6841
			return sanitize_key( $_GET['calypso_env'] );
6842
		}
6843
6844
		if ( getenv( 'CALYPSO_ENV' ) ) {
6845
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6846
		}
6847
6848
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6849
			return sanitize_key( CALYPSO_ENV );
6850
		}
6851
6852
		return '';
6853
	}
6854
6855
	/**
6856
	 * Checks whether or not TOS has been agreed upon.
6857
	 * Will return true if a user has clicked to register, or is already connected.
6858
	 */
6859
	public static function jetpack_tos_agreed() {
6860
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6861
	}
6862
6863
	/**
6864
	 * Handles activating default modules as well general cleanup for the new connection.
6865
	 *
6866
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6867
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6868
	 * @param boolean $send_state_messages          Whether to send state messages.
6869
	 * @return void
6870
	 */
6871
	public static function handle_post_authorization_actions(
6872
		$activate_sso = false,
6873
		$redirect_on_activation_error = false,
6874
		$send_state_messages = true
6875
	) {
6876
		$other_modules = $activate_sso
6877
			? array( 'sso' )
6878
			: array();
6879
6880
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6881
			Jetpack::delete_active_modules();
6882
6883
			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...
6884
		} else {
6885
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6886
		}
6887
6888
		// Since this is a fresh connection, be sure to clear out IDC options
6889
		Jetpack_IDC::clear_all_idc_options();
6890
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6891
6892
		// Start nonce cleaner
6893
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6894
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6895
6896
		if ( $send_state_messages ) {
6897
			Jetpack::state( 'message', 'authorized' );
6898
		}
6899
	}
6900
6901
	/**
6902
	 * Returns a boolean for whether backups UI should be displayed or not.
6903
	 *
6904
	 * @return bool Should backups UI be displayed?
6905
	 */
6906
	public static function show_backups_ui() {
6907
		/**
6908
		 * Whether UI for backups should be displayed.
6909
		 *
6910
		 * @since 6.5.0
6911
		 *
6912
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6913
		 */
6914
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6915
	}
6916
6917
	/*
6918
	 * Deprecated manage functions
6919
	 */
6920
	function prepare_manage_jetpack_notice() {
6921
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6922
	}
6923
	function manage_activate_screen() {
6924
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6925
	}
6926
	function admin_jetpack_manage_notice() {
6927
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6928
	}
6929
	function opt_out_jetpack_manage_url() {
6930
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6931
	}
6932
	function opt_in_jetpack_manage_url() {
6933
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6934
	}
6935
	function opt_in_jetpack_manage_notice() {
6936
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6937
	}
6938
	function can_display_jetpack_manage_notice() {
6939
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6940
	}
6941
6942
	/**
6943
	 * Clean leftoveruser meta.
6944
	 *
6945
	 * Delete Jetpack-related user meta when it is no longer needed.
6946
	 *
6947
	 * @since 7.3.0
6948
	 *
6949
	 * @param int $user_id User ID being updated.
6950
	 */
6951
	public static function user_meta_cleanup( $user_id ) {
6952
		$meta_keys = array(
6953
			// AtD removed from Jetpack 7.3
6954
			'AtD_options',
6955
			'AtD_check_when',
6956
			'AtD_guess_lang',
6957
			'AtD_ignored_phrases',
6958
		);
6959
6960
		foreach ( $meta_keys as $meta_key ) {
6961
			if ( get_user_meta( $user_id, $meta_key ) ) {
6962
				delete_user_meta( $user_id, $meta_key );
6963
			}
6964
		}
6965
	}
6966
6967
	function is_active_and_not_development_mode( $maybe ) {
6968
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6969
			return false;
6970
		}
6971
		return true;
6972
	}
6973
}
6974