Completed
Push — add/upgrade-url-subsidiary-id ( 62f547...fadb60 )
by Jeremy
16:26 queued 08:26
created

class.jetpack.php (64 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
use Automattic\Jetpack\Assets;
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\Connection\Utils as Connection_Utils;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Sender;
15
use Automattic\Jetpack\Sync\Users;
16
use Automattic\Jetpack\Terms_Of_Service;
17
use Automattic\Jetpack\Tracking;
18
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
19
20
/*
21
Options:
22
jetpack_options (array)
23
	An array of options.
24
	@see Jetpack_Options::get_option_names()
25
26
jetpack_register (string)
27
	Temporary verification secrets.
28
29
jetpack_activated (int)
30
	1: the plugin was activated normally
31
	2: the plugin was activated on this site because of a network-wide activation
32
	3: the plugin was auto-installed
33
	4: the plugin was manually disconnected (but is still installed)
34
35
jetpack_active_modules (array)
36
	Array of active module slugs.
37
38
jetpack_do_activate (bool)
39
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
40
*/
41
42
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
43
44
class Jetpack {
45
	public $xmlrpc_server = null;
46
47
	private $rest_authentication_status = null;
48
49
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
50
51
	private $tracking;
52
53
	/**
54
	 * @var array The handles of styles that are concatenated into jetpack.css.
55
	 *
56
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
57
	 */
58
	public $concatenated_style_handles = array(
59
		'jetpack-carousel',
60
		'grunion.css',
61
		'the-neverending-homepage',
62
		'jetpack_likes',
63
		'jetpack_related-posts',
64
		'sharedaddy',
65
		'jetpack-slideshow',
66
		'presentations',
67
		'quiz',
68
		'jetpack-subscriptions',
69
		'jetpack-responsive-videos-style',
70
		'jetpack-social-menu',
71
		'tiled-gallery',
72
		'jetpack_display_posts_widget',
73
		'gravatar-profile-widget',
74
		'goodreads-widget',
75
		'jetpack_social_media_icons_widget',
76
		'jetpack-top-posts-widget',
77
		'jetpack_image_widget',
78
		'jetpack-my-community-widget',
79
		'jetpack-authors-widget',
80
		'wordads',
81
		'eu-cookie-law-style',
82
		'flickr-widget-style',
83
		'jetpack-search-widget',
84
		'jetpack-simple-payments-widget-style',
85
		'jetpack-widget-social-icons-styles',
86
	);
87
88
	/**
89
	 * The handles of scripts that can be loaded asynchronously.
90
	 *
91
	 * @var array
92
	 */
93
	public $async_script_handles = array(
94
		'woocommerce-analytics',
95
	);
96
97
	/**
98
	 * Contains all assets that have had their URL rewritten to minified versions.
99
	 *
100
	 * @var array
101
	 */
102
	static $min_assets = array();
103
104
	public $plugins_to_deactivate = array(
105
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
106
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
107
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
108
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
109
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
110
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
111
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
112
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
113
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
114
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
115
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
116
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
117
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
118
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
119
	);
120
121
	/**
122
	 * Map of roles we care about, and their corresponding minimum capabilities.
123
	 *
124
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
125
	 *
126
	 * @access public
127
	 * @static
128
	 *
129
	 * @var array
130
	 */
131
	public static $capability_translations = array(
132
		'administrator' => 'manage_options',
133
		'editor'        => 'edit_others_posts',
134
		'author'        => 'publish_posts',
135
		'contributor'   => 'edit_posts',
136
		'subscriber'    => 'read',
137
	);
138
139
	/**
140
	 * Map of modules that have conflicts with plugins and should not be auto-activated
141
	 * if the plugins are active.  Used by filter_default_modules
142
	 *
143
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
144
	 * change `module-slug` and add this to your plugin:
145
	 *
146
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
147
	 * function my_jetpack_get_default_modules( $modules ) {
148
	 *     return array_diff( $modules, array( 'module-slug' ) );
149
	 * }
150
	 *
151
	 * @var array
152
	 */
153
	private $conflicting_plugins = array(
154
		'comments'           => array(
155
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
156
			'Disqus'                         => 'disqus-comment-system/disqus.php',
157
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
158
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
159
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
160
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
161
		),
162
		'comment-likes'      => array(
163
			'Epoch' => 'epoch/plugincore.php',
164
		),
165
		'contact-form'       => array(
166
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
167
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
168
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
169
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
170
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
171
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
172
		),
173
		'minileven'          => array(
174
			'WPtouch' => 'wptouch/wptouch.php',
175
		),
176
		'latex'              => array(
177
			'LaTeX for WordPress'     => 'latex/latex.php',
178
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
179
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
180
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
181
			'Enable Latex'            => 'enable-latex/enable-latex.php',
182
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
183
		),
184
		'protect'            => array(
185
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
186
			'Captcha'                           => 'captcha/captcha.php',
187
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
188
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
189
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
190
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
191
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
192
			'Security-protection'               => 'security-protection/security-protection.php',
193
			'Login Security'                    => 'login-security/login-security.php',
194
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
195
			'Wordfence Security'                => 'wordfence/wordfence.php',
196
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
197
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
198
		),
199
		'random-redirect'    => array(
200
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
201
		),
202
		'related-posts'      => array(
203
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
204
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
205
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
206
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
207
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
208
			'outbrain'                    => 'outbrain/outbrain.php',
209
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
210
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
211
		),
212
		'sharedaddy'         => array(
213
			'AddThis'     => 'addthis/addthis_social_widget.php',
214
			'Add To Any'  => 'add-to-any/add-to-any.php',
215
			'ShareThis'   => 'share-this/sharethis.php',
216
			'Shareaholic' => 'shareaholic/shareaholic.php',
217
		),
218
		'seo-tools'          => array(
219
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
220
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
221
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
222
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
223
			'The SEO Framework'              => 'autodescription/autodescription.php',
224
		),
225
		'verification-tools' => array(
226
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
227
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
228
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
229
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
230
			'The SEO Framework'              => 'autodescription/autodescription.php',
231
		),
232
		'widget-visibility'  => array(
233
			'Widget Logic'    => 'widget-logic/widget_logic.php',
234
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
235
		),
236
		'sitemaps'           => array(
237
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
238
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
239
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
240
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
241
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
242
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
243
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
244
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
245
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
246
			'The SEO Framework'                    => 'autodescription/autodescription.php',
247
			'Sitemap'                              => 'sitemap/sitemap.php',
248
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
249
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
250
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
251
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
252
		),
253
		'lazy-images'        => array(
254
			'Lazy Load'              => 'lazy-load/lazy-load.php',
255
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
256
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
257
		),
258
	);
259
260
	/**
261
	 * Plugins for which we turn off our Facebook OG Tags implementation.
262
	 *
263
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
264
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
265
	 *
266
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
267
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
268
	 */
269
	private $open_graph_conflicting_plugins = array(
270
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
271
		// 2 Click Social Media Buttons
272
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
273
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
274
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
275
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
276
		// Open Graph Meta Tags by Heateor
277
		'facebook/facebook.php',                                 // Facebook (official plugin)
278
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
279
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
280
		// Facebook Featured Image & OG Meta Tags
281
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
282
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
283
		// Facebook Open Graph Meta Tags for WordPress
284
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
285
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
286
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
287
		// Fedmich's Facebook Open Graph Meta
288
		'network-publisher/networkpub.php',                      // Network Publisher
289
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
290
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
291
		// NextScripts SNAP
292
		'og-tags/og-tags.php',                                   // OG Tags
293
		'opengraph/opengraph.php',                               // Open Graph
294
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
295
		// Open Graph Protocol Framework
296
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
297
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
298
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
299
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
300
		'sharepress/sharepress.php',                             // SharePress
301
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
302
		'social-discussions/social-discussions.php',             // Social Discussions
303
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
304
		'socialize/socialize.php',                               // Socialize
305
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
306
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
307
		// Tweet, Like, Google +1 and Share
308
		'wordbooker/wordbooker.php',                             // Wordbooker
309
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
310
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
311
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
312
		// WP Facebook Like Send & Open Graph Meta
313
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
314
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
315
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
316
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
317
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
318
	);
319
320
	/**
321
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
322
	 */
323
	private $twitter_cards_conflicting_plugins = array(
324
		// 'twitter/twitter.php',                       // The official one handles this on its own.
325
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
326
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
327
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
328
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
329
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
330
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
331
		'twitter-cards/twitter-cards.php',           // Twitter Cards
332
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
333
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
334
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
335
	);
336
337
	/**
338
	 * Message to display in admin_notice
339
	 *
340
	 * @var string
341
	 */
342
	public $message = '';
343
344
	/**
345
	 * Error to display in admin_notice
346
	 *
347
	 * @var string
348
	 */
349
	public $error = '';
350
351
	/**
352
	 * Modules that need more privacy description.
353
	 *
354
	 * @var string
355
	 */
356
	public $privacy_checks = '';
357
358
	/**
359
	 * Stats to record once the page loads
360
	 *
361
	 * @var array
362
	 */
363
	public $stats = array();
364
365
	/**
366
	 * Jetpack_Sync object
367
	 */
368
	public $sync;
369
370
	/**
371
	 * Verified data for JSON authorization request
372
	 */
373
	public $json_api_authorization_request = array();
374
375
	/**
376
	 * @var Automattic\Jetpack\Connection\Manager
377
	 */
378
	protected $connection_manager;
379
380
	/**
381
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
382
	 */
383
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
384
385
	/**
386
	 * Holds the singleton instance of this class
387
	 *
388
	 * @since 2.3.3
389
	 * @var Jetpack
390
	 */
391
	static $instance = false;
392
393
	/**
394
	 * Singleton
395
	 *
396
	 * @static
397
	 */
398
	public static function init() {
399
		if ( ! self::$instance ) {
400
			self::$instance = new Jetpack();
401
402
			self::$instance->plugin_upgrade();
403
		}
404
405
		return self::$instance;
406
	}
407
408
	/**
409
	 * Must never be called statically
410
	 */
411
	function plugin_upgrade() {
412
		if ( self::is_active() ) {
413
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
414
			if ( JETPACK__VERSION != $version ) {
415
				// Prevent multiple upgrades at once - only a single process should trigger
416
				// an upgrade to avoid stampedes
417
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
418
					return;
419
				}
420
421
				// Set a short lock to prevent multiple instances of the upgrade
422
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
423
424
				// check which active modules actually exist and remove others from active_modules list
425
				$unfiltered_modules = self::get_active_modules();
426
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
427
				if ( array_diff( $unfiltered_modules, $modules ) ) {
428
					self::update_active_modules( $modules );
429
				}
430
431
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
432
433
				// Upgrade to 4.3.0
434
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
435
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
436
				}
437
438
				// Make sure Markdown for posts gets turned back on
439
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
440
					update_option( 'wpcom_publish_posts_with_markdown', true );
441
				}
442
443
				if ( did_action( 'wp_loaded' ) ) {
444
					self::upgrade_on_load();
445
				} else {
446
					add_action(
447
						'wp_loaded',
448
						array( __CLASS__, 'upgrade_on_load' )
449
					);
450
				}
451
			}
452
		}
453
	}
454
455
	/**
456
	 * Runs upgrade routines that need to have modules loaded.
457
	 */
458
	static function upgrade_on_load() {
459
460
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
461
		// This can happen in case Jetpack has been just upgraded and is
462
		// being initialized late during the page load. In this case we wait
463
		// until the next proper admin page load with Jetpack active.
464
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
465
			delete_transient( self::$plugin_upgrade_lock_key );
466
467
			return;
468
		}
469
470
		self::maybe_set_version_option();
471
472
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
473
			Jetpack_Widget_Conditions::migrate_post_type_rules();
474
		}
475
476
		if (
477
			class_exists( 'Jetpack_Sitemap_Manager' )
478
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
479
		) {
480
			do_action( 'jetpack_sitemaps_purge_data' );
481
		}
482
483
		// Delete old stats cache
484
		delete_option( 'jetpack_restapi_stats_cache' );
485
486
		delete_transient( self::$plugin_upgrade_lock_key );
487
	}
488
489
	/**
490
	 * Saves all the currently active modules to options.
491
	 * Also fires Action hooks for each newly activated and deactivated module.
492
	 *
493
	 * @param $modules Array Array of active modules to be saved in options.
494
	 *
495
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
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...
496
	 */
497
	static function update_active_modules( $modules ) {
498
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
499
		$active_modules       = self::get_active_modules();
500
		$new_active_modules   = array_diff( $modules, $current_modules );
501
		$new_inactive_modules = array_diff( $active_modules, $modules );
502
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
503
		$reindexed_modules    = array_values( $new_current_modules );
504
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
505
506
		foreach ( $new_active_modules as $module ) {
507
			/**
508
			 * Fires when a specific module is activated.
509
			 *
510
			 * @since 1.9.0
511
			 *
512
			 * @param string $module Module slug.
513
			 * @param boolean $success whether the module was activated. @since 4.2
514
			 */
515
			do_action( 'jetpack_activate_module', $module, $success );
516
			/**
517
			 * Fires when a module is activated.
518
			 * The dynamic part of the filter, $module, is the module slug.
519
			 *
520
			 * @since 1.9.0
521
			 *
522
			 * @param string $module Module slug.
523
			 */
524
			do_action( "jetpack_activate_module_$module", $module );
525
		}
526
527
		foreach ( $new_inactive_modules as $module ) {
528
			/**
529
			 * Fired after a module has been deactivated.
530
			 *
531
			 * @since 4.2.0
532
			 *
533
			 * @param string $module Module slug.
534
			 * @param boolean $success whether the module was deactivated.
535
			 */
536
			do_action( 'jetpack_deactivate_module', $module, $success );
537
			/**
538
			 * Fires when a module is deactivated.
539
			 * The dynamic part of the filter, $module, is the module slug.
540
			 *
541
			 * @since 1.9.0
542
			 *
543
			 * @param string $module Module slug.
544
			 */
545
			do_action( "jetpack_deactivate_module_$module", $module );
546
		}
547
548
		return $success;
549
	}
550
551
	static function delete_active_modules() {
552
		self::update_active_modules( array() );
553
	}
554
555
	/**
556
	 * Constructor.  Initializes WordPress hooks
557
	 */
558
	private function __construct() {
559
		/*
560
		 * Check for and alert any deprecated hooks
561
		 */
562
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
563
564
		/*
565
		 * Enable enhanced handling of previewing sites in Calypso
566
		 */
567
		if ( self::is_active() ) {
568
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
569
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
570
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
571
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
572
		}
573
574
		add_action( 'plugins_loaded', array( $this, 'after_plugins_loaded' )  );
575
576
		add_filter(
577
			'jetpack_connection_secret_generator',
578
			function( $callable ) {
579
				return function() {
580
					return wp_generate_password( 32, false );
581
				};
582
			}
583
		);
584
585
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
586
587
		$this->connection_manager = new Connection_Manager();
588
		$this->connection_manager->init();
589
590
		/*
591
		 * Load things that should only be in Network Admin.
592
		 *
593
		 * For now blow away everything else until a more full
594
		 * understanding of what is needed at the network level is
595
		 * available
596
		 */
597
		if ( is_multisite() ) {
598
			$network = Jetpack_Network::init();
599
			$network->set_connection( $this->connection_manager );
600
		}
601
602
		add_filter(
603
			'jetpack_signature_check_token',
604
			array( __CLASS__, 'verify_onboarding_token' ),
605
			10,
606
			3
607
		);
608
609
		/**
610
		 * Prepare Gutenberg Editor functionality
611
		 */
612
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
613
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
614
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
615
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
616
617
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
618
619
		// Unlink user before deleting the user from WP.com.
620
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
621
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
622
623
		// Initialize remote file upload request handlers.
624
		$this->add_remote_request_handlers();
625
626
		if ( self::is_active() ) {
627
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
628
629
			Jetpack_Heartbeat::init();
630
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
631
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
632
				Jetpack_Search_Performance_Logger::init();
633
			}
634
		}
635
636
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
637
638
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
639
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
640
641
		add_action( 'admin_init', array( $this, 'admin_init' ) );
642
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
643
644
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
645
646
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
647
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
648
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
649
650
		// returns HTTPS support status
651
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
652
653
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
654
655
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
656
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
657
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
658
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
659
660
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
661
662
		/**
663
		 * These actions run checks to load additional files.
664
		 * They check for external files or plugins, so they need to run as late as possible.
665
		 */
666
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
667
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
668
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
669
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
670
671
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
672
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
673
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
674
675
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
676
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
677
678
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
679
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
680
681
		// A filter to control all just in time messages
682
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
683
684
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
685
686
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
687
		// We should make sure to only do this for front end links.
688
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
689
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
690
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
691
692
			// we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
693
			// so they point moderation links on emails to Calypso
694
			jetpack_require_lib( 'functions.wp-notify' );
695
		}
696
697
		// Hide edit post link if mobile app.
698
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
699
			add_filter( 'edit_post_link', '__return_empty_string' );
700
		}
701
702
		// Update the Jetpack plan from API on heartbeats
703
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
704
705
		/**
706
		 * This is the hack to concatenate all css files into one.
707
		 * For description and reasoning see the implode_frontend_css method
708
		 *
709
		 * Super late priority so we catch all the registered styles
710
		 */
711
		if ( ! is_admin() ) {
712
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
713
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
714
		}
715
716
		/**
717
		 * These are sync actions that we need to keep track of for jitms
718
		 */
719
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
720
721
		// Actually push the stats on shutdown.
722
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
723
			add_action( 'shutdown', array( $this, 'push_stats' ) );
724
		}
725
726
		/*
727
		 * Load some scripts asynchronously.
728
		 */
729
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
730
731
		// Actions for Manager::authorize().
732
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
733
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
734
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
735
736
		// Filters for the Manager::get_token() urls and request body.
737
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
738
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
739
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
740
	}
741
742
	/**
743
	 * Runs after all the plugins have loaded but before init.
744
	 */
745
	function after_plugins_loaded() {
746
747
		Partner::init();
748
		$terms_of_service = new Terms_Of_Service();
749
		$tracking = new Plugin_Tracking();
750
		if ( $terms_of_service->has_agreed() ) {
751
			add_action( 'init', array( $tracking, 'init' ) );
752
		} else {
753
			/**
754
			 * Initialize tracking right after the user agrees to the terms of service.
755
			 */
756
			add_action( 'jetpack_agreed_to_terms_of_service', array( $tracking, 'init' ) );
757
		}
758
	}
759
760
	/**
761
	 * Sets up the XMLRPC request handlers.
762
	 *
763
	 * @deprecated since 7.7.0
764
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
765
	 *
766
	 * @param Array                 $request_params Incoming request parameters.
767
	 * @param Boolean               $is_active      Whether the connection is currently active.
768
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
769
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
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...
770
	 */
771
	public function setup_xmlrpc_handlers(
772
		$request_params,
773
		$is_active,
774
		$is_signed,
775
		Jetpack_XMLRPC_Server $xmlrpc_server = null
776
	) {
777
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
778
		return $this->connection_manager->setup_xmlrpc_handlers(
779
			$request_params,
780
			$is_active,
781
			$is_signed,
782
			$xmlrpc_server
783
		);
784
	}
785
786
	/**
787
	 * Initialize REST API registration connector.
788
	 *
789
	 * @deprecated since 7.7.0
790
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
791
	 */
792
	public function initialize_rest_api_registration_connector() {
793
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
794
		$this->connection_manager->initialize_rest_api_registration_connector();
795
	}
796
797
	/**
798
	 * This is ported over from the manage module, which has been deprecated and baked in here.
799
	 *
800
	 * @param $domains
801
	 */
802
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
803
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
804
	}
805
806
	/**
807
	 * Return $domains, with 'wordpress.com' appended.
808
	 * This is ported over from the manage module, which has been deprecated and baked in here.
809
	 *
810
	 * @param $domains
811
	 * @return array
812
	 */
813
	function allow_wpcom_domain( $domains ) {
814
		if ( empty( $domains ) ) {
815
			$domains = array();
816
		}
817
		$domains[] = 'wordpress.com';
818
		return array_unique( $domains );
819
	}
820
821
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
822
		$post = get_post( $post_id );
823
824
		if ( empty( $post ) ) {
825
			return $default_url;
826
		}
827
828
		$post_type = $post->post_type;
829
830
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
831
		// https://en.support.wordpress.com/custom-post-types/
832
		$allowed_post_types = array(
833
			'post'                => 'post',
834
			'page'                => 'page',
835
			'jetpack-portfolio'   => 'edit/jetpack-portfolio',
836
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
837
		);
838
839
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
840
			return $default_url;
841
		}
842
843
		$path_prefix = $allowed_post_types[ $post_type ];
844
845
		$site_slug = self::build_raw_urls( get_home_url() );
846
847
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
848
	}
849
850
	function point_edit_comment_links_to_calypso( $url ) {
851
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
852
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
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...
853
		return esc_url(
854
			sprintf(
855
				'https://wordpress.com/comment/%s/%d',
856
				self::build_raw_urls( get_home_url() ),
857
				$query_args['amp;c']
858
			)
859
		);
860
	}
861
862
	function jetpack_track_last_sync_callback( $params ) {
863
		/**
864
		 * Filter to turn off jitm caching
865
		 *
866
		 * @since 5.4.0
867
		 *
868
		 * @param bool false Whether to cache just in time messages
869
		 */
870
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
871
			return $params;
872
		}
873
874
		if ( is_array( $params ) && isset( $params[0] ) ) {
875
			$option = $params[0];
876
			if ( 'active_plugins' === $option ) {
877
				// use the cache if we can, but not terribly important if it gets evicted
878
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
879
			}
880
		}
881
882
		return $params;
883
	}
884
885
	function jetpack_connection_banner_callback() {
886
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
887
888
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
889
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
890
			wp_send_json_success();
891
		}
892
893
		wp_die();
894
	}
895
896
	/**
897
	 * Removes all XML-RPC methods that are not `jetpack.*`.
898
	 * Only used in our alternate XML-RPC endpoint, where we want to
899
	 * ensure that Core and other plugins' methods are not exposed.
900
	 *
901
	 * @deprecated since 7.7.0
902
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
903
	 *
904
	 * @param array $methods A list of registered WordPress XMLRPC methods.
905
	 * @return array Filtered $methods
906
	 */
907
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
908
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
909
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
910
	}
911
912
	/**
913
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
914
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
915
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
916
	 * which is accessible via a different URI. Most of the below is copied directly
917
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
918
	 *
919
	 * @deprecated since 7.7.0
920
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
921
	 */
922
	public function alternate_xmlrpc() {
923
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
924
		$this->connection_manager->alternate_xmlrpc();
925
	}
926
927
	/**
928
	 * The callback for the JITM ajax requests.
929
	 *
930
	 * @deprecated since 7.9.0
931
	 */
932
	function jetpack_jitm_ajax_callback() {
933
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
934
	}
935
936
	/**
937
	 * If there are any stats that need to be pushed, but haven't been, push them now.
938
	 */
939
	function push_stats() {
940
		if ( ! empty( $this->stats ) ) {
941
			$this->do_stats( 'server_side' );
942
		}
943
	}
944
945
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
946
		$is_development_mode = ( new Status() )->is_development_mode();
947
		switch ( $cap ) {
948
			case 'jetpack_connect':
949
			case 'jetpack_reconnect':
950
				if ( $is_development_mode ) {
951
					$caps = array( 'do_not_allow' );
952
					break;
953
				}
954
				/**
955
				 * Pass through. If it's not development mode, these should match disconnect.
956
				 * Let users disconnect if it's development mode, just in case things glitch.
957
				 */
958
			case 'jetpack_disconnect':
959
				/**
960
				 * In multisite, can individual site admins manage their own connection?
961
				 *
962
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
963
				 */
964
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
965
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
966
						/**
967
						 * We need to update the option name -- it's terribly unclear which
968
						 * direction the override goes.
969
						 *
970
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
971
						 */
972
						$caps = array( 'do_not_allow' );
973
						break;
974
					}
975
				}
976
977
				$caps = array( 'manage_options' );
978
				break;
979
			case 'jetpack_manage_modules':
980
			case 'jetpack_activate_modules':
981
			case 'jetpack_deactivate_modules':
982
				$caps = array( 'manage_options' );
983
				break;
984
			case 'jetpack_configure_modules':
985
				$caps = array( 'manage_options' );
986
				break;
987
			case 'jetpack_manage_autoupdates':
988
				$caps = array(
989
					'manage_options',
990
					'update_plugins',
991
				);
992
				break;
993
			case 'jetpack_network_admin_page':
994
			case 'jetpack_network_settings_page':
995
				$caps = array( 'manage_network_plugins' );
996
				break;
997
			case 'jetpack_network_sites_page':
998
				$caps = array( 'manage_sites' );
999
				break;
1000
			case 'jetpack_admin_page':
1001
				if ( $is_development_mode ) {
1002
					$caps = array( 'manage_options' );
1003
					break;
1004
				} else {
1005
					$caps = array( 'read' );
1006
				}
1007
				break;
1008
			case 'jetpack_connect_user':
1009
				if ( $is_development_mode ) {
1010
					$caps = array( 'do_not_allow' );
1011
					break;
1012
				}
1013
				$caps = array( 'read' );
1014
				break;
1015
		}
1016
		return $caps;
1017
	}
1018
1019
	/**
1020
	 * Require a Jetpack authentication.
1021
	 *
1022
	 * @deprecated since 7.7.0
1023
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1024
	 */
1025
	public function require_jetpack_authentication() {
1026
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1027
		$this->connection_manager->require_jetpack_authentication();
1028
	}
1029
1030
	/**
1031
	 * Load language files
1032
	 *
1033
	 * @action plugins_loaded
1034
	 */
1035
	public static function plugin_textdomain() {
1036
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1037
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1038
	}
1039
1040
	/**
1041
	 * Register assets for use in various modules and the Jetpack admin page.
1042
	 *
1043
	 * @uses wp_script_is, wp_register_script, plugins_url
1044
	 * @action wp_loaded
1045
	 * @return null
1046
	 */
1047
	public function register_assets() {
1048
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1049
			wp_register_script(
1050
				'spin',
1051
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1052
				false,
1053
				'1.3'
1054
			);
1055
		}
1056
1057 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1058
			wp_register_script(
1059
				'jquery.spin',
1060
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1061
				array( 'jquery', 'spin' ),
1062
				'1.3'
1063
			);
1064
		}
1065
1066 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1067
			wp_register_script(
1068
				'jetpack-gallery-settings',
1069
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1070
				array( 'media-views' ),
1071
				'20121225'
1072
			);
1073
		}
1074
1075 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1076
			wp_register_script(
1077
				'jetpack-twitter-timeline',
1078
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1079
				array( 'jquery' ),
1080
				'4.0.0',
1081
				true
1082
			);
1083
		}
1084
1085
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1086
			wp_register_script(
1087
				'jetpack-facebook-embed',
1088
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1089
				array( 'jquery' ),
1090
				null,
1091
				true
1092
			);
1093
1094
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1095
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1096
			if ( ! is_numeric( $fb_app_id ) ) {
1097
				$fb_app_id = '';
1098
			}
1099
			wp_localize_script(
1100
				'jetpack-facebook-embed',
1101
				'jpfbembed',
1102
				array(
1103
					'appid'  => $fb_app_id,
1104
					'locale' => $this->get_locale(),
1105
				)
1106
			);
1107
		}
1108
1109
		/**
1110
		 * As jetpack_register_genericons is by default fired off a hook,
1111
		 * the hook may have already fired by this point.
1112
		 * So, let's just trigger it manually.
1113
		 */
1114
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1115
		jetpack_register_genericons();
1116
1117
		/**
1118
		 * Register the social logos
1119
		 */
1120
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1121
		jetpack_register_social_logos();
1122
1123 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1124
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1125
		}
1126
	}
1127
1128
	/**
1129
	 * Guess locale from language code.
1130
	 *
1131
	 * @param string $lang Language code.
1132
	 * @return string|bool
1133
	 */
1134 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1135
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1136
			return 'en_US';
1137
		}
1138
1139
		if ( ! class_exists( 'GP_Locales' ) ) {
1140
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1141
				return false;
1142
			}
1143
1144
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1145
		}
1146
1147
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1148
			// WP.com: get_locale() returns 'it'
1149
			$locale = GP_Locales::by_slug( $lang );
1150
		} else {
1151
			// Jetpack: get_locale() returns 'it_IT';
1152
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1153
		}
1154
1155
		if ( ! $locale ) {
1156
			return false;
1157
		}
1158
1159
		if ( empty( $locale->facebook_locale ) ) {
1160
			if ( empty( $locale->wp_locale ) ) {
1161
				return false;
1162
			} else {
1163
				// Facebook SDK is smart enough to fall back to en_US if a
1164
				// locale isn't supported. Since supported Facebook locales
1165
				// can fall out of sync, we'll attempt to use the known
1166
				// wp_locale value and rely on said fallback.
1167
				return $locale->wp_locale;
1168
			}
1169
		}
1170
1171
		return $locale->facebook_locale;
1172
	}
1173
1174
	/**
1175
	 * Get the locale.
1176
	 *
1177
	 * @return string|bool
1178
	 */
1179
	function get_locale() {
1180
		$locale = $this->guess_locale_from_lang( get_locale() );
1181
1182
		if ( ! $locale ) {
1183
			$locale = 'en_US';
1184
		}
1185
1186
		return $locale;
1187
	}
1188
1189
	/**
1190
	 * Device Pixels support
1191
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1192
	 */
1193
	function devicepx() {
1194
		if ( self::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1195
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1196
		}
1197
	}
1198
1199
	/**
1200
	 * Return the network_site_url so that .com knows what network this site is a part of.
1201
	 *
1202
	 * @param  bool $option
1203
	 * @return string
1204
	 */
1205
	public function jetpack_main_network_site_option( $option ) {
1206
		return network_site_url();
1207
	}
1208
	/**
1209
	 * Network Name.
1210
	 */
1211
	static function network_name( $option = null ) {
1212
		global $current_site;
1213
		return $current_site->site_name;
1214
	}
1215
	/**
1216
	 * Does the network allow new user and site registrations.
1217
	 *
1218
	 * @return string
1219
	 */
1220
	static function network_allow_new_registrations( $option = null ) {
1221
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1222
	}
1223
	/**
1224
	 * Does the network allow admins to add new users.
1225
	 *
1226
	 * @return boolian
1227
	 */
1228
	static function network_add_new_users( $option = null ) {
1229
		return (bool) get_site_option( 'add_new_users' );
1230
	}
1231
	/**
1232
	 * File upload psace left per site in MB.
1233
	 *  -1 means NO LIMIT.
1234
	 *
1235
	 * @return number
1236
	 */
1237
	static function network_site_upload_space( $option = null ) {
1238
		// value in MB
1239
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1240
	}
1241
1242
	/**
1243
	 * Network allowed file types.
1244
	 *
1245
	 * @return string
1246
	 */
1247
	static function network_upload_file_types( $option = null ) {
1248
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1249
	}
1250
1251
	/**
1252
	 * Maximum file upload size set by the network.
1253
	 *
1254
	 * @return number
1255
	 */
1256
	static function network_max_upload_file_size( $option = null ) {
1257
		// value in KB
1258
		return get_site_option( 'fileupload_maxk', 300 );
1259
	}
1260
1261
	/**
1262
	 * Lets us know if a site allows admins to manage the network.
1263
	 *
1264
	 * @return array
1265
	 */
1266
	static function network_enable_administration_menus( $option = null ) {
1267
		return get_site_option( 'menu_items' );
1268
	}
1269
1270
	/**
1271
	 * If a user has been promoted to or demoted from admin, we need to clear the
1272
	 * jetpack_other_linked_admins transient.
1273
	 *
1274
	 * @since 4.3.2
1275
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1276
	 *
1277
	 * @param int    $user_id   The user ID whose role changed.
1278
	 * @param string $role      The new role.
1279
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
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...
1280
	 */
1281
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1282
		if ( 'administrator' == $role
1283
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1284
			|| is_null( $old_roles )
1285
		) {
1286
			delete_transient( 'jetpack_other_linked_admins' );
1287
		}
1288
	}
1289
1290
	/**
1291
	 * Checks to see if there are any other users available to become primary
1292
	 * Users must both:
1293
	 * - Be linked to wpcom
1294
	 * - Be an admin
1295
	 *
1296
	 * @return mixed False if no other users are linked, Int if there are.
1297
	 */
1298
	static function get_other_linked_admins() {
1299
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1300
1301
		if ( false === $other_linked_users ) {
1302
			$admins = get_users( array( 'role' => 'administrator' ) );
1303
			if ( count( $admins ) > 1 ) {
1304
				$available = array();
1305
				foreach ( $admins as $admin ) {
1306
					if ( self::is_user_connected( $admin->ID ) ) {
1307
						$available[] = $admin->ID;
1308
					}
1309
				}
1310
1311
				$count_connected_admins = count( $available );
1312
				if ( count( $available ) > 1 ) {
1313
					$other_linked_users = $count_connected_admins;
1314
				} else {
1315
					$other_linked_users = 0;
1316
				}
1317
			} else {
1318
				$other_linked_users = 0;
1319
			}
1320
1321
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1322
		}
1323
1324
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1325
	}
1326
1327
	/**
1328
	 * Return whether we are dealing with a multi network setup or not.
1329
	 * The reason we are type casting this is because we want to avoid the situation where
1330
	 * the result is false since when is_main_network_option return false it cases
1331
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1332
	 * database which could be set to anything as opposed to what this function returns.
1333
	 *
1334
	 * @param  bool $option
1335
	 *
1336
	 * @return boolean
1337
	 */
1338
	public function is_main_network_option( $option ) {
1339
		// return '1' or ''
1340
		return (string) (bool) self::is_multi_network();
1341
	}
1342
1343
	/**
1344
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1345
	 *
1346
	 * @param  string $option
1347
	 * @return boolean
1348
	 */
1349
	public function is_multisite( $option ) {
1350
		return (string) (bool) is_multisite();
1351
	}
1352
1353
	/**
1354
	 * Implemented since there is no core is multi network function
1355
	 * Right now there is no way to tell if we which network is the dominant network on the system
1356
	 *
1357
	 * @since  3.3
1358
	 * @return boolean
1359
	 */
1360 View Code Duplication
	public static function is_multi_network() {
1361
		global  $wpdb;
1362
1363
		// if we don't have a multi site setup no need to do any more
1364
		if ( ! is_multisite() ) {
1365
			return false;
1366
		}
1367
1368
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1369
		if ( $num_sites > 1 ) {
1370
			return true;
1371
		} else {
1372
			return false;
1373
		}
1374
	}
1375
1376
	/**
1377
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1378
	 *
1379
	 * @return null
1380
	 */
1381
	function update_jetpack_main_network_site_option() {
1382
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1383
	}
1384
	/**
1385
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1386
	 */
1387
	function update_jetpack_network_settings() {
1388
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1389
		// Only sync this info for the main network site.
1390
	}
1391
1392
	/**
1393
	 * Get back if the current site is single user site.
1394
	 *
1395
	 * @return bool
1396
	 */
1397 View Code Duplication
	public static function is_single_user_site() {
1398
		global $wpdb;
1399
1400
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1401
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1402
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1403
		}
1404
		return 1 === (int) $some_users;
1405
	}
1406
1407
	/**
1408
	 * Returns true if the site has file write access false otherwise.
1409
	 *
1410
	 * @return string ( '1' | '0' )
1411
	 **/
1412
	public static function file_system_write_access() {
1413
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1414
			require_once ABSPATH . 'wp-admin/includes/file.php';
1415
		}
1416
1417
		require_once ABSPATH . 'wp-admin/includes/template.php';
1418
1419
		$filesystem_method = get_filesystem_method();
1420
		if ( $filesystem_method === 'direct' ) {
1421
			return 1;
1422
		}
1423
1424
		ob_start();
1425
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1426
		ob_end_clean();
1427
		if ( $filesystem_credentials_are_stored ) {
1428
			return 1;
1429
		}
1430
		return 0;
1431
	}
1432
1433
	/**
1434
	 * Finds out if a site is using a version control system.
1435
	 *
1436
	 * @return string ( '1' | '0' )
1437
	 **/
1438
	public static function is_version_controlled() {
1439
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1440
		return (string) (int) Functions::is_version_controlled();
1441
	}
1442
1443
	/**
1444
	 * Determines whether the current theme supports featured images or not.
1445
	 *
1446
	 * @return string ( '1' | '0' )
1447
	 */
1448
	public static function featured_images_enabled() {
1449
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1450
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1451
	}
1452
1453
	/**
1454
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1455
	 *
1456
	 * @deprecated 4.7 use get_avatar_url instead.
1457
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1458
	 * @param int               $size Size of the avatar image
1459
	 * @param string            $default URL to a default image to use if no avatar is available
1460
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1461
	 *
1462
	 * @return array
1463
	 */
1464
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1465
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1466
		return get_avatar_url(
1467
			$id_or_email,
1468
			array(
1469
				'size'          => $size,
1470
				'default'       => $default,
1471
				'force_default' => $force_display,
1472
			)
1473
		);
1474
	}
1475
1476
	/**
1477
	 * jetpack_updates is saved in the following schema:
1478
	 *
1479
	 * array (
1480
	 *      'plugins'                       => (int) Number of plugin updates available.
1481
	 *      'themes'                        => (int) Number of theme updates available.
1482
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1483
	 *      'translations'                  => (int) Number of translation updates available.
1484
	 *      'total'                         => (int) Total of all available updates.
1485
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1486
	 * )
1487
	 *
1488
	 * @return array
1489
	 */
1490
	public static function get_updates() {
1491
		$update_data = wp_get_update_data();
1492
1493
		// Stores the individual update counts as well as the total count.
1494
		if ( isset( $update_data['counts'] ) ) {
1495
			$updates = $update_data['counts'];
1496
		}
1497
1498
		// If we need to update WordPress core, let's find the latest version number.
1499 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1500
			$cur = get_preferred_from_update_core();
1501
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1502
				$updates['wp_update_version'] = $cur->current;
1503
			}
1504
		}
1505
		return isset( $updates ) ? $updates : array();
1506
	}
1507
1508
	public static function get_update_details() {
1509
		$update_details = array(
1510
			'update_core'    => get_site_transient( 'update_core' ),
1511
			'update_plugins' => get_site_transient( 'update_plugins' ),
1512
			'update_themes'  => get_site_transient( 'update_themes' ),
1513
		);
1514
		return $update_details;
1515
	}
1516
1517
	public static function refresh_update_data() {
1518
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1519
1520
	}
1521
1522
	public static function refresh_theme_data() {
1523
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1524
	}
1525
1526
	/**
1527
	 * Is Jetpack active?
1528
	 */
1529
	public static function is_active() {
1530
		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...
1531
	}
1532
1533
	/**
1534
	 * Make an API call to WordPress.com for plan status
1535
	 *
1536
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1537
	 *
1538
	 * @return bool True if plan is updated, false if no update
1539
	 */
1540
	public static function refresh_active_plan_from_wpcom() {
1541
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1542
		return Jetpack_Plan::refresh_from_wpcom();
1543
	}
1544
1545
	/**
1546
	 * Get the plan that this Jetpack site is currently using
1547
	 *
1548
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1549
	 * @return array Active Jetpack plan details.
1550
	 */
1551
	public static function get_active_plan() {
1552
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1553
		return Jetpack_Plan::get();
1554
	}
1555
1556
	/**
1557
	 * Determine whether the active plan supports a particular feature
1558
	 *
1559
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1560
	 * @return bool True if plan supports feature, false if not.
1561
	 */
1562
	public static function active_plan_supports( $feature ) {
1563
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1564
		return Jetpack_Plan::supports( $feature );
1565
	}
1566
1567
	/**
1568
	 * Deprecated: Is Jetpack in development (offline) mode?
1569
	 *
1570
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1571
	 * and themes still use it, and we do not want to flood them with notices.
1572
	 *
1573
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1574
	 *
1575
	 * @deprecated since 8.0.
1576
	 */
1577
	public static function is_development_mode() {
1578
		return ( new Status() )->is_development_mode();
1579
	}
1580
1581
	/**
1582
	 * Whether the site is currently onboarding or not.
1583
	 * A site is considered as being onboarded if it currently has an onboarding token.
1584
	 *
1585
	 * @since 5.8
1586
	 *
1587
	 * @access public
1588
	 * @static
1589
	 *
1590
	 * @return bool True if the site is currently onboarding, false otherwise
1591
	 */
1592
	public static function is_onboarding() {
1593
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1594
	}
1595
1596
	/**
1597
	 * Determines reason for Jetpack development mode.
1598
	 */
1599
	public static function development_mode_trigger_text() {
1600
		if ( ! ( new Status() )->is_development_mode() ) {
1601
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1602
		}
1603
1604
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1605
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1606
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1607
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1608
		} else {
1609
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1610
		}
1611
1612
		return $notice;
1613
1614
	}
1615
	/**
1616
	 * Get Jetpack development mode notice text and notice class.
1617
	 *
1618
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1619
	 */
1620
	public static function show_development_mode_notice() {
1621 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1622
			$notice = sprintf(
1623
				/* translators: %s is a URL */
1624
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1625
				'https://jetpack.com/support/development-mode/'
1626
			);
1627
1628
			$notice .= ' ' . self::development_mode_trigger_text();
1629
1630
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1631
		}
1632
1633
		// Throw up a notice if using a development version and as for feedback.
1634
		if ( self::is_development_version() ) {
1635
			/* translators: %s is a URL */
1636
			$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/' );
1637
1638
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1639
		}
1640
		// Throw up a notice if using staging mode
1641
		if ( self::is_staging_site() ) {
1642
			/* translators: %s is a URL */
1643
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1644
1645
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1646
		}
1647
	}
1648
1649
	/**
1650
	 * Whether Jetpack's version maps to a public release, or a development version.
1651
	 */
1652
	public static function is_development_version() {
1653
		/**
1654
		 * Allows filtering whether this is a development version of Jetpack.
1655
		 *
1656
		 * This filter is especially useful for tests.
1657
		 *
1658
		 * @since 4.3.0
1659
		 *
1660
		 * @param bool $development_version Is this a develoment version of Jetpack?
1661
		 */
1662
		return (bool) apply_filters(
1663
			'jetpack_development_version',
1664
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1665
		);
1666
	}
1667
1668
	/**
1669
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1670
	 */
1671
	public static function is_user_connected( $user_id = false ) {
1672
		return self::connection()->is_user_connected( $user_id );
1673
	}
1674
1675
	/**
1676
	 * Get the wpcom user data of the current|specified connected user.
1677
	 */
1678 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1679
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1680
		if ( ! $user_id ) {
1681
			$user_id = get_current_user_id();
1682
		}
1683
1684
		$transient_key = "jetpack_connected_user_data_$user_id";
1685
1686
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1687
			return $cached_user_data;
1688
		}
1689
1690
		$xml = new Jetpack_IXR_Client(
1691
			array(
1692
				'user_id' => $user_id,
1693
			)
1694
		);
1695
		$xml->query( 'wpcom.getUser' );
1696
		if ( ! $xml->isError() ) {
1697
			$user_data = $xml->getResponse();
1698
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1699
			return $user_data;
1700
		}
1701
1702
		return false;
1703
	}
1704
1705
	/**
1706
	 * Get the wpcom email of the current|specified connected user.
1707
	 */
1708 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1709
		if ( ! $user_id ) {
1710
			$user_id = get_current_user_id();
1711
		}
1712
1713
		$xml = new Jetpack_IXR_Client(
1714
			array(
1715
				'user_id' => $user_id,
1716
			)
1717
		);
1718
		$xml->query( 'wpcom.getUserEmail' );
1719
		if ( ! $xml->isError() ) {
1720
			return $xml->getResponse();
1721
		}
1722
		return false;
1723
	}
1724
1725
	/**
1726
	 * Get the wpcom email of the master user.
1727
	 */
1728
	public static function get_master_user_email() {
1729
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1730
		if ( $master_user_id ) {
1731
			return self::get_connected_user_email( $master_user_id );
1732
		}
1733
		return '';
1734
	}
1735
1736
	/**
1737
	 * Whether the current user is the connection owner.
1738
	 *
1739
	 * @deprecated since 7.7
1740
	 *
1741
	 * @return bool Whether the current user is the connection owner.
1742
	 */
1743
	public function current_user_is_connection_owner() {
1744
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1745
		return self::connection()->is_connection_owner();
1746
	}
1747
1748
	/**
1749
	 * Gets current user IP address.
1750
	 *
1751
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1752
	 *
1753
	 * @return string                  Current user IP address.
1754
	 */
1755
	public static function current_user_ip( $check_all_headers = false ) {
1756
		if ( $check_all_headers ) {
1757
			foreach ( array(
1758
				'HTTP_CF_CONNECTING_IP',
1759
				'HTTP_CLIENT_IP',
1760
				'HTTP_X_FORWARDED_FOR',
1761
				'HTTP_X_FORWARDED',
1762
				'HTTP_X_CLUSTER_CLIENT_IP',
1763
				'HTTP_FORWARDED_FOR',
1764
				'HTTP_FORWARDED',
1765
				'HTTP_VIA',
1766
			) as $key ) {
1767
				if ( ! empty( $_SERVER[ $key ] ) ) {
1768
					return $_SERVER[ $key ];
1769
				}
1770
			}
1771
		}
1772
1773
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1774
	}
1775
1776
	/**
1777
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1778
	 */
1779
	function extra_oembed_providers() {
1780
		// Cloudup: https://dev.cloudup.com/#oembed
1781
		wp_oembed_add_provider( 'https://cloudup.com/*', 'https://cloudup.com/oembed' );
1782
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1783
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1784
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1785
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1786
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1787
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1788
	}
1789
1790
	/**
1791
	 * Synchronize connected user role changes
1792
	 */
1793
	function user_role_change( $user_id ) {
1794
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1795
		Users::user_role_change( $user_id );
1796
	}
1797
1798
	/**
1799
	 * Loads the currently active modules.
1800
	 */
1801
	public static function load_modules() {
1802
		$is_development_mode = ( new Status() )->is_development_mode();
1803
		if (
1804
			! self::is_active()
1805
			&& ! $is_development_mode
1806
			&& ! self::is_onboarding()
1807
			&& (
1808
				! is_multisite()
1809
				|| ! get_site_option( 'jetpack_protect_active' )
1810
			)
1811
		) {
1812
			return;
1813
		}
1814
1815
		$version = Jetpack_Options::get_option( 'version' );
1816 View Code Duplication
		if ( ! $version ) {
1817
			$version = $old_version = JETPACK__VERSION . ':' . time();
1818
			/** This action is documented in class.jetpack.php */
1819
			do_action( 'updating_jetpack_version', $version, false );
1820
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1821
		}
1822
		list( $version ) = explode( ':', $version );
1823
1824
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1825
1826
		$modules_data = array();
1827
1828
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1829
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1830
			$updated_modules = array();
1831
			foreach ( $modules as $module ) {
1832
				$modules_data[ $module ] = self::get_module( $module );
1833
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1834
					continue;
1835
				}
1836
1837
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1838
					continue;
1839
				}
1840
1841
				$updated_modules[] = $module;
1842
			}
1843
1844
			$modules = array_diff( $modules, $updated_modules );
1845
		}
1846
1847
		foreach ( $modules as $index => $module ) {
1848
			// If we're in dev mode, disable modules requiring a connection
1849
			if ( $is_development_mode ) {
1850
				// Prime the pump if we need to
1851
				if ( empty( $modules_data[ $module ] ) ) {
1852
					$modules_data[ $module ] = self::get_module( $module );
1853
				}
1854
				// If the module requires a connection, but we're in local mode, don't include it.
1855
				if ( $modules_data[ $module ]['requires_connection'] ) {
1856
					continue;
1857
				}
1858
			}
1859
1860
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1861
				continue;
1862
			}
1863
1864
			if ( ! include_once self::get_module_path( $module ) ) {
1865
				unset( $modules[ $index ] );
1866
				self::update_active_modules( array_values( $modules ) );
1867
				continue;
1868
			}
1869
1870
			/**
1871
			 * Fires when a specific module is loaded.
1872
			 * The dynamic part of the hook, $module, is the module slug.
1873
			 *
1874
			 * @since 1.1.0
1875
			 */
1876
			do_action( 'jetpack_module_loaded_' . $module );
1877
		}
1878
1879
		/**
1880
		 * Fires when all the modules are loaded.
1881
		 *
1882
		 * @since 1.1.0
1883
		 */
1884
		do_action( 'jetpack_modules_loaded' );
1885
1886
		// 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.
1887
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1888
	}
1889
1890
	/**
1891
	 * Check if Jetpack's REST API compat file should be included
1892
	 *
1893
	 * @action plugins_loaded
1894
	 * @return null
1895
	 */
1896
	public function check_rest_api_compat() {
1897
		/**
1898
		 * Filters the list of REST API compat files to be included.
1899
		 *
1900
		 * @since 2.2.5
1901
		 *
1902
		 * @param array $args Array of REST API compat files to include.
1903
		 */
1904
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1905
1906
		if ( function_exists( 'bbpress' ) ) {
1907
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1908
		}
1909
1910
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1911
			require_once $_jetpack_rest_api_compat_include;
1912
		}
1913
	}
1914
1915
	/**
1916
	 * Gets all plugins currently active in values, regardless of whether they're
1917
	 * traditionally activated or network activated.
1918
	 *
1919
	 * @todo Store the result in core's object cache maybe?
1920
	 */
1921
	public static function get_active_plugins() {
1922
		$active_plugins = (array) get_option( 'active_plugins', array() );
1923
1924
		if ( is_multisite() ) {
1925
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1926
			// whereas active_plugins stores them in the values.
1927
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1928
			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...
1929
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1930
			}
1931
		}
1932
1933
		sort( $active_plugins );
1934
1935
		return array_unique( $active_plugins );
1936
	}
1937
1938
	/**
1939
	 * Gets and parses additional plugin data to send with the heartbeat data
1940
	 *
1941
	 * @since 3.8.1
1942
	 *
1943
	 * @return array Array of plugin data
1944
	 */
1945
	public static function get_parsed_plugin_data() {
1946
		if ( ! function_exists( 'get_plugins' ) ) {
1947
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
1948
		}
1949
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1950
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1951
		$active_plugins = self::get_active_plugins();
1952
1953
		$plugins = array();
1954
		foreach ( $all_plugins as $path => $plugin_data ) {
1955
			$plugins[ $path ] = array(
1956
				'is_active' => in_array( $path, $active_plugins ),
1957
				'file'      => $path,
1958
				'name'      => $plugin_data['Name'],
1959
				'version'   => $plugin_data['Version'],
1960
				'author'    => $plugin_data['Author'],
1961
			);
1962
		}
1963
1964
		return $plugins;
1965
	}
1966
1967
	/**
1968
	 * Gets and parses theme data to send with the heartbeat data
1969
	 *
1970
	 * @since 3.8.1
1971
	 *
1972
	 * @return array Array of theme data
1973
	 */
1974
	public static function get_parsed_theme_data() {
1975
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
1976
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1977
1978
		$themes = array();
1979
		foreach ( $all_themes as $slug => $theme_data ) {
1980
			$theme_headers = array();
1981
			foreach ( $header_keys as $header_key ) {
1982
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1983
			}
1984
1985
			$themes[ $slug ] = array(
1986
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
1987
				'slug'            => $slug,
1988
				'theme_root'      => $theme_data->get_theme_root_uri(),
1989
				'parent'          => $theme_data->parent(),
1990
				'headers'         => $theme_headers,
1991
			);
1992
		}
1993
1994
		return $themes;
1995
	}
1996
1997
	/**
1998
	 * Checks whether a specific plugin is active.
1999
	 *
2000
	 * We don't want to store these in a static variable, in case
2001
	 * there are switch_to_blog() calls involved.
2002
	 */
2003
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2004
		return in_array( $plugin, self::get_active_plugins() );
2005
	}
2006
2007
	/**
2008
	 * Check if Jetpack's Open Graph tags should be used.
2009
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2010
	 *
2011
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2012
	 * @action plugins_loaded
2013
	 * @return null
2014
	 */
2015
	public function check_open_graph() {
2016
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2017
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2018
		}
2019
2020
		$active_plugins = self::get_active_plugins();
2021
2022
		if ( ! empty( $active_plugins ) ) {
2023
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2024
				if ( in_array( $plugin, $active_plugins ) ) {
2025
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2026
					break;
2027
				}
2028
			}
2029
		}
2030
2031
		/**
2032
		 * Allow the addition of Open Graph Meta Tags to all pages.
2033
		 *
2034
		 * @since 2.0.3
2035
		 *
2036
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2037
		 */
2038
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2039
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2040
		}
2041
	}
2042
2043
	/**
2044
	 * Check if Jetpack's Twitter tags should be used.
2045
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2046
	 *
2047
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2048
	 * @action plugins_loaded
2049
	 * @return null
2050
	 */
2051
	public function check_twitter_tags() {
2052
2053
		$active_plugins = self::get_active_plugins();
2054
2055
		if ( ! empty( $active_plugins ) ) {
2056
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2057
				if ( in_array( $plugin, $active_plugins ) ) {
2058
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2059
					break;
2060
				}
2061
			}
2062
		}
2063
2064
		/**
2065
		 * Allow Twitter Card Meta tags to be disabled.
2066
		 *
2067
		 * @since 2.6.0
2068
		 *
2069
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2070
		 */
2071
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2072
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2073
		}
2074
	}
2075
2076
	/**
2077
	 * Allows plugins to submit security reports.
2078
	 *
2079
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2080
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2081
	 * @param array  $args         See definitions above
2082
	 */
2083
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2084
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2085
	}
2086
2087
	/* Jetpack Options API */
2088
2089
	public static function get_option_names( $type = 'compact' ) {
2090
		return Jetpack_Options::get_option_names( $type );
2091
	}
2092
2093
	/**
2094
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2095
	 *
2096
	 * @param string $name    Option name
2097
	 * @param mixed  $default (optional)
2098
	 */
2099
	public static function get_option( $name, $default = false ) {
2100
		return Jetpack_Options::get_option( $name, $default );
2101
	}
2102
2103
	/**
2104
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2105
	 *
2106
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2107
	 * @param string $name  Option name
2108
	 * @param mixed  $value Option value
2109
	 */
2110
	public static function update_option( $name, $value ) {
2111
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2112
		return Jetpack_Options::update_option( $name, $value );
2113
	}
2114
2115
	/**
2116
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2117
	 *
2118
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2119
	 * @param array $array array( option name => option value, ... )
2120
	 */
2121
	public static function update_options( $array ) {
2122
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2123
		return Jetpack_Options::update_options( $array );
2124
	}
2125
2126
	/**
2127
	 * Deletes the given option.  May be passed multiple option names as an array.
2128
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2129
	 *
2130
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2131
	 * @param string|array $names
2132
	 */
2133
	public static function delete_option( $names ) {
2134
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2135
		return Jetpack_Options::delete_option( $names );
2136
	}
2137
2138
	/**
2139
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2140
	 *
2141
	 * Enters a user token into the user_tokens option
2142
	 *
2143
	 * @param int    $user_id The user id.
2144
	 * @param string $token The user token.
2145
	 * @param bool   $is_master_user Whether the user is the master user.
2146
	 * @return bool
2147
	 */
2148
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2149
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2150
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2151
	}
2152
2153
	/**
2154
	 * Returns an array of all PHP files in the specified absolute path.
2155
	 * Equivalent to glob( "$absolute_path/*.php" ).
2156
	 *
2157
	 * @param string $absolute_path The absolute path of the directory to search.
2158
	 * @return array Array of absolute paths to the PHP files.
2159
	 */
2160
	public static function glob_php( $absolute_path ) {
2161
		if ( function_exists( 'glob' ) ) {
2162
			return glob( "$absolute_path/*.php" );
2163
		}
2164
2165
		$absolute_path = untrailingslashit( $absolute_path );
2166
		$files         = array();
2167
		if ( ! $dir = @opendir( $absolute_path ) ) {
2168
			return $files;
2169
		}
2170
2171
		while ( false !== $file = readdir( $dir ) ) {
2172
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2173
				continue;
2174
			}
2175
2176
			$file = "$absolute_path/$file";
2177
2178
			if ( ! is_file( $file ) ) {
2179
				continue;
2180
			}
2181
2182
			$files[] = $file;
2183
		}
2184
2185
		closedir( $dir );
2186
2187
		return $files;
2188
	}
2189
2190
	public static function activate_new_modules( $redirect = false ) {
2191
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2192
			return;
2193
		}
2194
2195
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2196 View Code Duplication
		if ( ! $jetpack_old_version ) {
2197
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2198
			/** This action is documented in class.jetpack.php */
2199
			do_action( 'updating_jetpack_version', $version, false );
2200
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2201
		}
2202
2203
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2204
2205
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2206
			return;
2207
		}
2208
2209
		$active_modules     = self::get_active_modules();
2210
		$reactivate_modules = array();
2211
		foreach ( $active_modules as $active_module ) {
2212
			$module = self::get_module( $active_module );
2213
			if ( ! isset( $module['changed'] ) ) {
2214
				continue;
2215
			}
2216
2217
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2218
				continue;
2219
			}
2220
2221
			$reactivate_modules[] = $active_module;
2222
			self::deactivate_module( $active_module );
2223
		}
2224
2225
		$new_version = JETPACK__VERSION . ':' . time();
2226
		/** This action is documented in class.jetpack.php */
2227
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2228
		Jetpack_Options::update_options(
2229
			array(
2230
				'version'     => $new_version,
2231
				'old_version' => $jetpack_old_version,
2232
			)
2233
		);
2234
2235
		self::state( 'message', 'modules_activated' );
2236
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
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...
2237
2238
		if ( $redirect ) {
2239
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2240
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2241
				$page = $_GET['page'];
2242
			}
2243
2244
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2245
			exit;
2246
		}
2247
	}
2248
2249
	/**
2250
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2251
	 * Make sure to tuck away module "library" files in a sub-directory.
2252
	 */
2253
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2254
		static $modules = null;
2255
2256
		if ( ! isset( $modules ) ) {
2257
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2258
			// Use the cache if we're on the front-end and it's available...
2259
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2260
				$modules = $available_modules_option[ JETPACK__VERSION ];
2261
			} else {
2262
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2263
2264
				$modules = array();
2265
2266
				foreach ( $files as $file ) {
2267
					if ( ! $headers = self::get_module( $file ) ) {
2268
						continue;
2269
					}
2270
2271
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2272
				}
2273
2274
				Jetpack_Options::update_option(
2275
					'available_modules',
2276
					array(
2277
						JETPACK__VERSION => $modules,
2278
					)
2279
				);
2280
			}
2281
		}
2282
2283
		/**
2284
		 * Filters the array of modules available to be activated.
2285
		 *
2286
		 * @since 2.4.0
2287
		 *
2288
		 * @param array $modules Array of available modules.
2289
		 * @param string $min_version Minimum version number required to use modules.
2290
		 * @param string $max_version Maximum version number required to use modules.
2291
		 */
2292
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2293
2294
		if ( ! $min_version && ! $max_version ) {
2295
			return array_keys( $mods );
2296
		}
2297
2298
		$r = array();
2299
		foreach ( $mods as $slug => $introduced ) {
2300
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2301
				continue;
2302
			}
2303
2304
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2305
				continue;
2306
			}
2307
2308
			$r[] = $slug;
2309
		}
2310
2311
		return $r;
2312
	}
2313
2314
	/**
2315
	 * Default modules loaded on activation.
2316
	 */
2317
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2318
		$return = array();
2319
2320
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2321
			$module_data = self::get_module( $module );
2322
2323
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2324
				case 'yes':
2325
					$return[] = $module;
2326
					break;
2327
				case 'public':
2328
					if ( Jetpack_Options::get_option( 'public' ) ) {
2329
						$return[] = $module;
2330
					}
2331
					break;
2332
				case 'no':
2333
				default:
2334
					break;
2335
			}
2336
		}
2337
		/**
2338
		 * Filters the array of default modules.
2339
		 *
2340
		 * @since 2.5.0
2341
		 *
2342
		 * @param array $return Array of default modules.
2343
		 * @param string $min_version Minimum version number required to use modules.
2344
		 * @param string $max_version Maximum version number required to use modules.
2345
		 */
2346
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2347
	}
2348
2349
	/**
2350
	 * Checks activated modules during auto-activation to determine
2351
	 * if any of those modules are being deprecated.  If so, close
2352
	 * them out, and add any replacement modules.
2353
	 *
2354
	 * Runs at priority 99 by default.
2355
	 *
2356
	 * This is run late, so that it can still activate a module if
2357
	 * the new module is a replacement for another that the user
2358
	 * currently has active, even if something at the normal priority
2359
	 * would kibosh everything.
2360
	 *
2361
	 * @since 2.6
2362
	 * @uses jetpack_get_default_modules filter
2363
	 * @param array $modules
2364
	 * @return array
2365
	 */
2366
	function handle_deprecated_modules( $modules ) {
2367
		$deprecated_modules = array(
2368
			'debug'            => null,  // Closed out and moved to the debugger library.
2369
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2370
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2371
		);
2372
2373
		// Don't activate SSO if they never completed activating WPCC.
2374
		if ( self::is_module_active( 'wpcc' ) ) {
2375
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2376
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2377
				$deprecated_modules['wpcc'] = null;
2378
			}
2379
		}
2380
2381
		foreach ( $deprecated_modules as $module => $replacement ) {
2382
			if ( self::is_module_active( $module ) ) {
2383
				self::deactivate_module( $module );
2384
				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...
2385
					$modules[] = $replacement;
2386
				}
2387
			}
2388
		}
2389
2390
		return array_unique( $modules );
2391
	}
2392
2393
	/**
2394
	 * Checks activated plugins during auto-activation to determine
2395
	 * if any of those plugins are in the list with a corresponding module
2396
	 * that is not compatible with the plugin. The module will not be allowed
2397
	 * to auto-activate.
2398
	 *
2399
	 * @since 2.6
2400
	 * @uses jetpack_get_default_modules filter
2401
	 * @param array $modules
2402
	 * @return array
2403
	 */
2404
	function filter_default_modules( $modules ) {
2405
2406
		$active_plugins = self::get_active_plugins();
2407
2408
		if ( ! empty( $active_plugins ) ) {
2409
2410
			// For each module we'd like to auto-activate...
2411
			foreach ( $modules as $key => $module ) {
2412
				// If there are potential conflicts for it...
2413
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2414
					// For each potential conflict...
2415
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2416
						// If that conflicting plugin is active...
2417
						if ( in_array( $plugin, $active_plugins ) ) {
2418
							// Remove that item from being auto-activated.
2419
							unset( $modules[ $key ] );
2420
						}
2421
					}
2422
				}
2423
			}
2424
		}
2425
2426
		return $modules;
2427
	}
2428
2429
	/**
2430
	 * Extract a module's slug from its full path.
2431
	 */
2432
	public static function get_module_slug( $file ) {
2433
		return str_replace( '.php', '', basename( $file ) );
2434
	}
2435
2436
	/**
2437
	 * Generate a module's path from its slug.
2438
	 */
2439
	public static function get_module_path( $slug ) {
2440
		/**
2441
		 * Filters the path of a modules.
2442
		 *
2443
		 * @since 7.4.0
2444
		 *
2445
		 * @param array $return The absolute path to a module's root php file
2446
		 * @param string $slug The module slug
2447
		 */
2448
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2449
	}
2450
2451
	/**
2452
	 * Load module data from module file. Headers differ from WordPress
2453
	 * plugin headers to avoid them being identified as standalone
2454
	 * plugins on the WordPress plugins page.
2455
	 */
2456
	public static function get_module( $module ) {
2457
		$headers = array(
2458
			'name'                      => 'Module Name',
2459
			'description'               => 'Module Description',
2460
			'sort'                      => 'Sort Order',
2461
			'recommendation_order'      => 'Recommendation Order',
2462
			'introduced'                => 'First Introduced',
2463
			'changed'                   => 'Major Changes In',
2464
			'deactivate'                => 'Deactivate',
2465
			'free'                      => 'Free',
2466
			'requires_connection'       => 'Requires Connection',
2467
			'auto_activate'             => 'Auto Activate',
2468
			'module_tags'               => 'Module Tags',
2469
			'feature'                   => 'Feature',
2470
			'additional_search_queries' => 'Additional Search Queries',
2471
			'plan_classes'              => 'Plans',
2472
		);
2473
2474
		$file = self::get_module_path( self::get_module_slug( $module ) );
2475
2476
		$mod = self::get_file_data( $file, $headers );
2477
		if ( empty( $mod['name'] ) ) {
2478
			return false;
2479
		}
2480
2481
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2482
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2483
		$mod['deactivate']           = empty( $mod['deactivate'] );
2484
		$mod['free']                 = empty( $mod['free'] );
2485
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2486
2487
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2488
			$mod['auto_activate'] = 'No';
2489
		} else {
2490
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2491
		}
2492
2493
		if ( $mod['module_tags'] ) {
2494
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2495
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2496
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2497
		} else {
2498
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2499
		}
2500
2501 View Code Duplication
		if ( $mod['plan_classes'] ) {
2502
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2503
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2504
		} else {
2505
			$mod['plan_classes'] = array( 'free' );
2506
		}
2507
2508 View Code Duplication
		if ( $mod['feature'] ) {
2509
			$mod['feature'] = explode( ',', $mod['feature'] );
2510
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2511
		} else {
2512
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2513
		}
2514
2515
		/**
2516
		 * Filters the feature array on a module.
2517
		 *
2518
		 * This filter allows you to control where each module is filtered: Recommended,
2519
		 * and the default "Other" listing.
2520
		 *
2521
		 * @since 3.5.0
2522
		 *
2523
		 * @param array   $mod['feature'] The areas to feature this module:
2524
		 *     'Recommended' shows on the main Jetpack admin screen.
2525
		 *     'Other' should be the default if no other value is in the array.
2526
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2527
		 * @param array   $mod All the currently assembled module data.
2528
		 */
2529
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2530
2531
		/**
2532
		 * Filter the returned data about a module.
2533
		 *
2534
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2535
		 * so please be careful.
2536
		 *
2537
		 * @since 3.6.0
2538
		 *
2539
		 * @param array   $mod    The details of the requested module.
2540
		 * @param string  $module The slug of the module, e.g. sharedaddy
2541
		 * @param string  $file   The path to the module source file.
2542
		 */
2543
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2544
	}
2545
2546
	/**
2547
	 * Like core's get_file_data implementation, but caches the result.
2548
	 */
2549
	public static function get_file_data( $file, $headers ) {
2550
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2551
		$file_name = basename( $file );
2552
2553
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2554
2555
		$file_data_option = get_transient( $cache_key );
2556
2557
		if ( ! is_array( $file_data_option ) ) {
2558
			delete_transient( $cache_key );
2559
			$file_data_option = false;
2560
		}
2561
2562
		if ( false === $file_data_option ) {
2563
			$file_data_option = array();
2564
		}
2565
2566
		$key           = md5( $file_name . serialize( $headers ) );
2567
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2568
2569
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2570
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2571
			return $file_data_option[ $key ];
2572
		}
2573
2574
		$data = get_file_data( $file, $headers );
2575
2576
		$file_data_option[ $key ] = $data;
2577
2578
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2579
2580
		return $data;
2581
	}
2582
2583
2584
	/**
2585
	 * Return translated module tag.
2586
	 *
2587
	 * @param string $tag Tag as it appears in each module heading.
2588
	 *
2589
	 * @return mixed
2590
	 */
2591
	public static function translate_module_tag( $tag ) {
2592
		return jetpack_get_module_i18n_tag( $tag );
2593
	}
2594
2595
	/**
2596
	 * Get i18n strings as a JSON-encoded string
2597
	 *
2598
	 * @return string The locale as JSON
2599
	 */
2600
	public static function get_i18n_data_json() {
2601
2602
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2603
		// JSON files with the file they should be included for. This is an md5
2604
		// of '_inc/build/admin.js'.
2605
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2606
2607
		$i18n_json =
2608
				   JETPACK__PLUGIN_DIR
2609
				   . 'languages/json/jetpack-'
2610
				   . get_user_locale()
2611
				   . '-'
2612
				   . $path_md5
2613
				   . '.json';
2614
2615
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2616
			$locale_data = @file_get_contents( $i18n_json );
2617
			if ( $locale_data ) {
2618
				return $locale_data;
2619
			}
2620
		}
2621
2622
		// Return valid empty Jed locale
2623
		return '{ "locale_data": { "messages": { "": {} } } }';
2624
	}
2625
2626
	/**
2627
	 * Add locale data setup to wp-i18n
2628
	 *
2629
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2630
	 *
2631
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2632
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2633
	 *
2634
	 * This method provides a safe way to request the setup multiple times but add the script at
2635
	 * most once.
2636
	 *
2637
	 * @since 6.7.0
2638
	 *
2639
	 * @return void
2640
	 */
2641
	public static function setup_wp_i18n_locale_data() {
2642
		static $script_added = false;
2643
		if ( ! $script_added ) {
2644
			$script_added = true;
2645
			wp_add_inline_script(
2646
				'wp-i18n',
2647
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2648
			);
2649
		}
2650
	}
2651
2652
	/**
2653
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2654
	 *
2655
	 * @since 3.9.2
2656
	 *
2657
	 * @param array $modules
2658
	 *
2659
	 * @return string|void
2660
	 */
2661
	public static function get_translated_modules( $modules ) {
2662
		foreach ( $modules as $index => $module ) {
2663
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2664
			if ( isset( $module['name'] ) ) {
2665
				$modules[ $index ]['name'] = $i18n_module['name'];
2666
			}
2667
			if ( isset( $module['description'] ) ) {
2668
				$modules[ $index ]['description']       = $i18n_module['description'];
2669
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2670
			}
2671
		}
2672
		return $modules;
2673
	}
2674
2675
	/**
2676
	 * Get a list of activated modules as an array of module slugs.
2677
	 */
2678
	public static function get_active_modules() {
2679
		$active = Jetpack_Options::get_option( 'active_modules' );
2680
2681
		if ( ! is_array( $active ) ) {
2682
			$active = array();
2683
		}
2684
2685
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2686
			$active[] = 'vaultpress';
2687
		} else {
2688
			$active = array_diff( $active, array( 'vaultpress' ) );
2689
		}
2690
2691
		// If protect is active on the main site of a multisite, it should be active on all sites.
2692
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2693
			$active[] = 'protect';
2694
		}
2695
2696
		/**
2697
		 * Allow filtering of the active modules.
2698
		 *
2699
		 * Gives theme and plugin developers the power to alter the modules that
2700
		 * are activated on the fly.
2701
		 *
2702
		 * @since 5.8.0
2703
		 *
2704
		 * @param array $active Array of active module slugs.
2705
		 */
2706
		$active = apply_filters( 'jetpack_active_modules', $active );
2707
2708
		return array_unique( $active );
2709
	}
2710
2711
	/**
2712
	 * Check whether or not a Jetpack module is active.
2713
	 *
2714
	 * @param string $module The slug of a Jetpack module.
2715
	 * @return bool
2716
	 *
2717
	 * @static
2718
	 */
2719
	public static function is_module_active( $module ) {
2720
		return in_array( $module, self::get_active_modules() );
2721
	}
2722
2723
	public static function is_module( $module ) {
2724
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2725
	}
2726
2727
	/**
2728
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2729
	 *
2730
	 * @param bool $catch True to start catching, False to stop.
2731
	 *
2732
	 * @static
2733
	 */
2734
	public static function catch_errors( $catch ) {
2735
		static $display_errors, $error_reporting;
2736
2737
		if ( $catch ) {
2738
			$display_errors  = @ini_set( 'display_errors', 1 );
2739
			$error_reporting = @error_reporting( E_ALL );
2740
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2741
		} else {
2742
			@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...
2743
			@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...
2744
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2745
		}
2746
	}
2747
2748
	/**
2749
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2750
	 */
2751
	public static function catch_errors_on_shutdown() {
2752
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2753
	}
2754
2755
	/**
2756
	 * Rewrite any string to make paths easier to read.
2757
	 *
2758
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2759
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2760
	 *
2761
	 * @param $string
2762
	 * @return mixed
2763
	 */
2764
	public static function alias_directories( $string ) {
2765
		// ABSPATH has a trailing slash.
2766
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2767
		// WP_CONTENT_DIR does not have a trailing slash.
2768
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2769
2770
		return $string;
2771
	}
2772
2773
	public static function activate_default_modules(
2774
		$min_version = false,
2775
		$max_version = false,
2776
		$other_modules = array(),
2777
		$redirect = null,
2778
		$send_state_messages = null
2779
	) {
2780
		$jetpack = self::init();
2781
2782
		if ( is_null( $redirect ) ) {
2783
			if (
2784
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2785
			||
2786
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2787
			||
2788
				( defined( 'WP_CLI' ) && WP_CLI )
2789
			||
2790
				( defined( 'DOING_CRON' ) && DOING_CRON )
2791
			||
2792
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2793
			) {
2794
				$redirect = false;
2795
			} elseif ( is_admin() ) {
2796
				$redirect = true;
2797
			} else {
2798
				$redirect = false;
2799
			}
2800
		}
2801
2802
		if ( is_null( $send_state_messages ) ) {
2803
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2804
		}
2805
2806
		$modules = self::get_default_modules( $min_version, $max_version );
2807
		$modules = array_merge( $other_modules, $modules );
2808
2809
		// Look for standalone plugins and disable if active.
2810
2811
		$to_deactivate = array();
2812
		foreach ( $modules as $module ) {
2813
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2814
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2815
			}
2816
		}
2817
2818
		$deactivated = array();
2819
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2820
			list( $probable_file, $probable_title ) = $deactivate_me;
2821
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2822
				$deactivated[] = $module;
2823
			}
2824
		}
2825
2826
		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...
2827
			if ( $send_state_messages ) {
2828
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2829
			}
2830
2831
			if ( $redirect ) {
2832
				$url = add_query_arg(
2833
					array(
2834
						'action'   => 'activate_default_modules',
2835
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2836
					),
2837
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2838
				);
2839
				wp_safe_redirect( $url );
2840
				exit;
2841
			}
2842
		}
2843
2844
		/**
2845
		 * Fires before default modules are activated.
2846
		 *
2847
		 * @since 1.9.0
2848
		 *
2849
		 * @param string $min_version Minimum version number required to use modules.
2850
		 * @param string $max_version Maximum version number required to use modules.
2851
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2852
		 */
2853
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2854
2855
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2856
		if ( $send_state_messages ) {
2857
			self::restate();
2858
			self::catch_errors( true );
2859
		}
2860
2861
		$active = self::get_active_modules();
2862
2863
		foreach ( $modules as $module ) {
2864
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2865
				$active[] = $module;
2866
				self::update_active_modules( $active );
2867
				continue;
2868
			}
2869
2870
			if ( $send_state_messages && in_array( $module, $active ) ) {
2871
				$module_info = self::get_module( $module );
2872 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2873
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2874
					if ( $active_state = self::state( $state ) ) {
2875
						$active_state = explode( ',', $active_state );
2876
					} else {
2877
						$active_state = array();
2878
					}
2879
					$active_state[] = $module;
2880
					self::state( $state, implode( ',', $active_state ) );
2881
				}
2882
				continue;
2883
			}
2884
2885
			$file = self::get_module_path( $module );
2886
			if ( ! file_exists( $file ) ) {
2887
				continue;
2888
			}
2889
2890
			// we'll override this later if the plugin can be included without fatal error
2891
			if ( $redirect ) {
2892
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2893
			}
2894
2895
			if ( $send_state_messages ) {
2896
				self::state( 'error', 'module_activation_failed' );
2897
				self::state( 'module', $module );
2898
			}
2899
2900
			ob_start();
2901
			require_once $file;
2902
2903
			$active[] = $module;
2904
2905 View Code Duplication
			if ( $send_state_messages ) {
2906
2907
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2908
				if ( $active_state = self::state( $state ) ) {
2909
					$active_state = explode( ',', $active_state );
2910
				} else {
2911
					$active_state = array();
2912
				}
2913
				$active_state[] = $module;
2914
				self::state( $state, implode( ',', $active_state ) );
2915
			}
2916
2917
			self::update_active_modules( $active );
2918
2919
			ob_end_clean();
2920
		}
2921
2922
		if ( $send_state_messages ) {
2923
			self::state( 'error', false );
0 ignored issues
show
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...
2924
			self::state( 'module', false );
0 ignored issues
show
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...
2925
		}
2926
2927
		self::catch_errors( false );
2928
		/**
2929
		 * Fires when default modules are activated.
2930
		 *
2931
		 * @since 1.9.0
2932
		 *
2933
		 * @param string $min_version Minimum version number required to use modules.
2934
		 * @param string $max_version Maximum version number required to use modules.
2935
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2936
		 */
2937
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2938
	}
2939
2940
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2941
		/**
2942
		 * Fires before a module is activated.
2943
		 *
2944
		 * @since 2.6.0
2945
		 *
2946
		 * @param string $module Module slug.
2947
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2948
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2949
		 */
2950
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2951
2952
		$jetpack = self::init();
2953
2954
		if ( ! strlen( $module ) ) {
2955
			return false;
2956
		}
2957
2958
		if ( ! self::is_module( $module ) ) {
2959
			return false;
2960
		}
2961
2962
		// If it's already active, then don't do it again
2963
		$active = self::get_active_modules();
2964
		foreach ( $active as $act ) {
2965
			if ( $act == $module ) {
2966
				return true;
2967
			}
2968
		}
2969
2970
		$module_data = self::get_module( $module );
2971
2972
		$is_development_mode = ( new Status() )->is_development_mode();
2973
		if ( ! self::is_active() ) {
2974
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
2975
				return false;
2976
			}
2977
2978
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2979
			if ( $is_development_mode && $module_data['requires_connection'] ) {
2980
				return false;
2981
			}
2982
		}
2983
2984
		// Check and see if the old plugin is active
2985
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2986
			// Deactivate the old plugin
2987
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2988
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2989
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2990
				self::state( 'deactivated_plugins', $module );
2991
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2992
				exit;
2993
			}
2994
		}
2995
2996
		// Protect won't work with mis-configured IPs
2997
		if ( 'protect' === $module ) {
2998
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2999
			if ( ! jetpack_protect_get_ip() ) {
3000
				self::state( 'message', 'protect_misconfigured_ip' );
3001
				return false;
3002
			}
3003
		}
3004
3005
		if ( ! Jetpack_Plan::supports( $module ) ) {
3006
			return false;
3007
		}
3008
3009
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3010
		self::state( 'module', $module );
3011
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3012
3013
		self::catch_errors( true );
3014
		ob_start();
3015
		require self::get_module_path( $module );
3016
		/** This action is documented in class.jetpack.php */
3017
		do_action( 'jetpack_activate_module', $module );
3018
		$active[] = $module;
3019
		self::update_active_modules( $active );
3020
3021
		self::state( 'error', false ); // the override
0 ignored issues
show
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...
3022
		ob_end_clean();
3023
		self::catch_errors( false );
3024
3025
		if ( $redirect ) {
3026
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3027
		}
3028
		if ( $exit ) {
3029
			exit;
3030
		}
3031
		return true;
3032
	}
3033
3034
	function activate_module_actions( $module ) {
3035
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3036
	}
3037
3038
	public static function deactivate_module( $module ) {
3039
		/**
3040
		 * Fires when a module is deactivated.
3041
		 *
3042
		 * @since 1.9.0
3043
		 *
3044
		 * @param string $module Module slug.
3045
		 */
3046
		do_action( 'jetpack_pre_deactivate_module', $module );
3047
3048
		$jetpack = self::init();
0 ignored issues
show
$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...
3049
3050
		$active = self::get_active_modules();
3051
		$new    = array_filter( array_diff( $active, (array) $module ) );
3052
3053
		return self::update_active_modules( $new );
3054
	}
3055
3056
	public static function enable_module_configurable( $module ) {
3057
		$module = self::get_module_slug( $module );
3058
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3059
	}
3060
3061
	/**
3062
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3063
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3064
	 *
3065
	 * @param string $module Module slug
3066
	 * @return string $url module configuration URL
3067
	 */
3068
	public static function module_configuration_url( $module ) {
3069
		$module      = self::get_module_slug( $module );
3070
		$default_url = self::admin_url() . "#/settings?term=$module";
3071
		/**
3072
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3073
		 *
3074
		 * @since 6.9.0
3075
		 *
3076
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3077
		 */
3078
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3079
3080
		return $url;
3081
	}
3082
3083
	/* Installation */
3084
	public static function bail_on_activation( $message, $deactivate = true ) {
3085
		?>
3086
<!doctype html>
3087
<html>
3088
<head>
3089
<meta charset="<?php bloginfo( 'charset' ); ?>">
3090
<style>
3091
* {
3092
	text-align: center;
3093
	margin: 0;
3094
	padding: 0;
3095
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3096
}
3097
p {
3098
	margin-top: 1em;
3099
	font-size: 18px;
3100
}
3101
</style>
3102
<body>
3103
<p><?php echo esc_html( $message ); ?></p>
3104
</body>
3105
</html>
3106
		<?php
3107
		if ( $deactivate ) {
3108
			$plugins = get_option( 'active_plugins' );
3109
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3110
			$update  = false;
3111
			foreach ( $plugins as $i => $plugin ) {
3112
				if ( $plugin === $jetpack ) {
3113
					$plugins[ $i ] = false;
3114
					$update        = true;
3115
				}
3116
			}
3117
3118
			if ( $update ) {
3119
				update_option( 'active_plugins', array_filter( $plugins ) );
3120
			}
3121
		}
3122
		exit;
3123
	}
3124
3125
	/**
3126
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3127
	 *
3128
	 * @static
3129
	 */
3130
	public static function plugin_activation( $network_wide ) {
3131
		Jetpack_Options::update_option( 'activated', 1 );
3132
3133
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3134
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3135
		}
3136
3137
		if ( $network_wide ) {
3138
			self::state( 'network_nag', true );
0 ignored issues
show
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...
3139
		}
3140
3141
		// For firing one-off events (notices) immediately after activation
3142
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3143
3144
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3145
3146
		self::plugin_initialize();
3147
	}
3148
3149
	public static function get_activation_source( $referer_url ) {
3150
3151
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3152
			return array( 'wp-cli', null );
3153
		}
3154
3155
		$referer = wp_parse_url( $referer_url );
3156
3157
		$source_type  = 'unknown';
3158
		$source_query = null;
3159
3160
		if ( ! is_array( $referer ) ) {
3161
			return array( $source_type, $source_query );
3162
		}
3163
3164
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3165
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3166
3167
		if ( isset( $referer['query'] ) ) {
3168
			parse_str( $referer['query'], $query_parts );
3169
		} else {
3170
			$query_parts = array();
3171
		}
3172
3173
		if ( $plugins_path === $referer['path'] ) {
3174
			$source_type = 'list';
3175
		} elseif ( $plugins_install_path === $referer['path'] ) {
3176
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3177
			switch ( $tab ) {
3178
				case 'popular':
3179
					$source_type = 'popular';
3180
					break;
3181
				case 'recommended':
3182
					$source_type = 'recommended';
3183
					break;
3184
				case 'favorites':
3185
					$source_type = 'favorites';
3186
					break;
3187
				case 'search':
3188
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3189
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3190
					break;
3191
				default:
3192
					$source_type = 'featured';
3193
			}
3194
		}
3195
3196
		return array( $source_type, $source_query );
3197
	}
3198
3199
	/**
3200
	 * Runs before bumping version numbers up to a new version
3201
	 *
3202
	 * @param  string $version    Version:timestamp
3203
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3204
	 * @return null              [description]
3205
	 */
3206
	public static function do_version_bump( $version, $old_version ) {
3207
		if ( ! $old_version ) { // For new sites
3208
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3209
		}
3210
	}
3211
3212
	/**
3213
	 * Sets the internal version number and activation state.
3214
	 *
3215
	 * @static
3216
	 */
3217
	public static function plugin_initialize() {
3218
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3219
			Jetpack_Options::update_option( 'activated', 2 );
3220
		}
3221
3222 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3223
			$version = $old_version = JETPACK__VERSION . ':' . time();
3224
			/** This action is documented in class.jetpack.php */
3225
			do_action( 'updating_jetpack_version', $version, false );
3226
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3227
		}
3228
3229
		self::load_modules();
3230
3231
		Jetpack_Options::delete_option( 'do_activate' );
3232
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3233
	}
3234
3235
	/**
3236
	 * Removes all connection options
3237
	 *
3238
	 * @static
3239
	 */
3240
	public static function plugin_deactivation() {
3241
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3242
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3243
			Jetpack_Network::init()->deactivate();
3244
		} else {
3245
			self::disconnect( false );
3246
			// Jetpack_Heartbeat::init()->deactivate();
3247
		}
3248
	}
3249
3250
	/**
3251
	 * Disconnects from the Jetpack servers.
3252
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3253
	 *
3254
	 * @static
3255
	 */
3256
	public static function disconnect( $update_activated_state = true ) {
3257
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3258
		$connection = self::connection();
3259
		$connection->clean_nonces( true );
3260
3261
		// If the site is in an IDC because sync is not allowed,
3262
		// let's make sure to not disconnect the production site.
3263
		if ( ! self::validate_sync_error_idc_option() ) {
3264
			$tracking = new Tracking();
3265
			$tracking->record_user_event( 'disconnect_site', array() );
3266
3267
			$connection->disconnect_site_wpcom();
3268
		}
3269
3270
		$connection->delete_all_connection_tokens();
3271
		Jetpack_IDC::clear_all_idc_options();
3272
3273
		if ( $update_activated_state ) {
3274
			Jetpack_Options::update_option( 'activated', 4 );
3275
		}
3276
3277
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3278
			// Check then record unique disconnection if site has never been disconnected previously
3279
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3280
				$jetpack_unique_connection['disconnected'] = 1;
3281
			} else {
3282
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3283
					// track unique disconnect
3284
					$jetpack = self::init();
3285
3286
					$jetpack->stat( 'connections', 'unique-disconnect' );
3287
					$jetpack->do_stats( 'server_side' );
3288
				}
3289
				// increment number of times disconnected
3290
				$jetpack_unique_connection['disconnected'] += 1;
3291
			}
3292
3293
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3294
		}
3295
3296
		// Delete all the sync related data. Since it could be taking up space.
3297
		Sender::get_instance()->uninstall();
3298
3299
		// Disable the Heartbeat cron
3300
		Jetpack_Heartbeat::init()->deactivate();
3301
	}
3302
3303
	/**
3304
	 * Unlinks the current user from the linked WordPress.com user.
3305
	 *
3306
	 * @deprecated since 7.7
3307
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3308
	 *
3309
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
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...
3310
	 * @return Boolean Whether the disconnection of the user was successful.
3311
	 */
3312
	public static function unlink_user( $user_id = null ) {
3313
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3314
		return Connection_Manager::disconnect_user( $user_id );
3315
	}
3316
3317
	/**
3318
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3319
	 */
3320
	public static function try_registration() {
3321
		$terms_of_service = new Terms_Of_Service();
3322
		// The user has agreed to the TOS at some point by now.
3323
		$terms_of_service->agree();
3324
3325
		// Let's get some testing in beta versions and such.
3326
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3327
			// Before attempting to connect, let's make sure that the domains are viable.
3328
			$domains_to_check = array_unique(
3329
				array(
3330
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3331
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3332
				)
3333
			);
3334
			foreach ( $domains_to_check as $domain ) {
3335
				$result = self::connection()->is_usable_domain( $domain );
3336
				if ( is_wp_error( $result ) ) {
3337
					return $result;
3338
				}
3339
			}
3340
		}
3341
3342
		$result = self::register();
3343
3344
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3345
		if ( ! $result || is_wp_error( $result ) ) {
3346
			return $result;
3347
		} else {
3348
			return true;
3349
		}
3350
	}
3351
3352
	/**
3353
	 * Tracking an internal event log. Try not to put too much chaff in here.
3354
	 *
3355
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3356
	 */
3357
	public static function log( $code, $data = null ) {
3358
		// only grab the latest 200 entries
3359
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3360
3361
		// Append our event to the log
3362
		$log_entry = array(
3363
			'time'    => time(),
3364
			'user_id' => get_current_user_id(),
3365
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3366
			'code'    => $code,
3367
		);
3368
		// Don't bother storing it unless we've got some.
3369
		if ( ! is_null( $data ) ) {
3370
			$log_entry['data'] = $data;
3371
		}
3372
		$log[] = $log_entry;
3373
3374
		// Try add_option first, to make sure it's not autoloaded.
3375
		// @todo: Add an add_option method to Jetpack_Options
3376
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3377
			Jetpack_Options::update_option( 'log', $log );
3378
		}
3379
3380
		/**
3381
		 * Fires when Jetpack logs an internal event.
3382
		 *
3383
		 * @since 3.0.0
3384
		 *
3385
		 * @param array $log_entry {
3386
		 *  Array of details about the log entry.
3387
		 *
3388
		 *  @param string time Time of the event.
3389
		 *  @param int user_id ID of the user who trigerred the event.
3390
		 *  @param int blog_id Jetpack Blog ID.
3391
		 *  @param string code Unique name for the event.
3392
		 *  @param string data Data about the event.
3393
		 * }
3394
		 */
3395
		do_action( 'jetpack_log_entry', $log_entry );
3396
	}
3397
3398
	/**
3399
	 * Get the internal event log.
3400
	 *
3401
	 * @param $event (string) - only return the specific log events
3402
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3403
	 *
3404
	 * @return array of log events || WP_Error for invalid params
3405
	 */
3406
	public static function get_log( $event = false, $num = false ) {
3407
		if ( $event && ! is_string( $event ) ) {
3408
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
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...
3409
		}
3410
3411
		if ( $num && ! is_numeric( $num ) ) {
3412
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
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...
3413
		}
3414
3415
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3416
3417
		// If nothing set - act as it did before, otherwise let's start customizing the output
3418
		if ( ! $num && ! $event ) {
3419
			return $entire_log;
3420
		} else {
3421
			$entire_log = array_reverse( $entire_log );
3422
		}
3423
3424
		$custom_log_output = array();
3425
3426
		if ( $event ) {
3427
			foreach ( $entire_log as $log_event ) {
3428
				if ( $event == $log_event['code'] ) {
3429
					$custom_log_output[] = $log_event;
3430
				}
3431
			}
3432
		} else {
3433
			$custom_log_output = $entire_log;
3434
		}
3435
3436
		if ( $num ) {
3437
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3438
		}
3439
3440
		return $custom_log_output;
3441
	}
3442
3443
	/**
3444
	 * Log modification of important settings.
3445
	 */
3446
	public static function log_settings_change( $option, $old_value, $value ) {
3447
		switch ( $option ) {
3448
			case 'jetpack_sync_non_public_post_stati':
3449
				self::log( $option, $value );
3450
				break;
3451
		}
3452
	}
3453
3454
	/**
3455
	 * Return stat data for WPCOM sync
3456
	 */
3457
	public static function get_stat_data( $encode = true, $extended = true ) {
3458
		$data = Jetpack_Heartbeat::generate_stats_array();
3459
3460
		if ( $extended ) {
3461
			$additional_data = self::get_additional_stat_data();
3462
			$data            = array_merge( $data, $additional_data );
3463
		}
3464
3465
		if ( $encode ) {
3466
			return json_encode( $data );
3467
		}
3468
3469
		return $data;
3470
	}
3471
3472
	/**
3473
	 * Get additional stat data to sync to WPCOM
3474
	 */
3475
	public static function get_additional_stat_data( $prefix = '' ) {
3476
		$return[ "{$prefix}themes" ]        = self::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...
3477
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3478
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3479
		$return[ "{$prefix}site-count" ]    = 0;
3480
3481
		if ( function_exists( 'get_blog_count' ) ) {
3482
			$return[ "{$prefix}site-count" ] = get_blog_count();
3483
		}
3484
		return $return;
3485
	}
3486
3487
	private static function get_site_user_count() {
3488
		global $wpdb;
3489
3490
		if ( function_exists( 'wp_is_large_network' ) ) {
3491
			if ( wp_is_large_network( 'users' ) ) {
3492
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3493
			}
3494
		}
3495
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3496
			// It wasn't there, so regenerate the data and save the transient
3497
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3498
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3499
		}
3500
		return $user_count;
3501
	}
3502
3503
	/* Admin Pages */
3504
3505
	function admin_init() {
3506
		// If the plugin is not connected, display a connect message.
3507
		if (
3508
			// the plugin was auto-activated and needs its candy
3509
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3510
		||
3511
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3512
			! Jetpack_Options::get_option( 'activated' )
3513
		) {
3514
			self::plugin_initialize();
3515
		}
3516
3517
		$is_development_mode = ( new Status() )->is_development_mode();
3518
		if ( ! self::is_active() && ! $is_development_mode ) {
3519
			Jetpack_Connection_Banner::init();
3520
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3521
			// Upgrade: 1.1 -> 1.1.1
3522
			// Check and see if host can verify the Jetpack servers' SSL certificate
3523
			$args       = array();
3524
			$connection = self::connection();
3525
			Client::_wp_remote_request(
3526
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3527
				$args,
3528
				true
3529
			);
3530
		}
3531
3532
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3533
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3534
		}
3535
3536
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3537
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3538
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3539
3540
		if ( self::is_active() || $is_development_mode ) {
3541
			// Artificially throw errors in certain whitelisted cases during plugin activation
3542
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3543
		}
3544
3545
		// Add custom column in wp-admin/users.php to show whether user is linked.
3546
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3547
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3548
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3549
	}
3550
3551
	function admin_body_class( $admin_body_class = '' ) {
3552
		$classes = explode( ' ', trim( $admin_body_class ) );
3553
3554
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3555
3556
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3557
		return " $admin_body_class ";
3558
	}
3559
3560
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3561
		return $admin_body_class . ' jetpack-pagestyles ';
3562
	}
3563
3564
	/**
3565
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3566
	 * This function artificially throws errors for such cases (whitelisted).
3567
	 *
3568
	 * @param string $plugin The activated plugin.
3569
	 */
3570
	function throw_error_on_activate_plugin( $plugin ) {
3571
		$active_modules = self::get_active_modules();
3572
3573
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3574
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3575
			$throw = false;
3576
3577
			// Try and make sure it really was the stats plugin
3578
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3579
				if ( 'stats.php' == basename( $plugin ) ) {
3580
					$throw = true;
3581
				}
3582
			} else {
3583
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3584
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3585
					$throw = true;
3586
				}
3587
			}
3588
3589
			if ( $throw ) {
3590
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3591
			}
3592
		}
3593
	}
3594
3595
	function intercept_plugin_error_scrape_init() {
3596
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3597
	}
3598
3599
	function intercept_plugin_error_scrape( $action, $result ) {
3600
		if ( ! $result ) {
3601
			return;
3602
		}
3603
3604
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3605
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3606
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3607
			}
3608
		}
3609
	}
3610
3611
	/**
3612
	 * Register the remote file upload request handlers, if needed.
3613
	 *
3614
	 * @access public
3615
	 */
3616
	public function add_remote_request_handlers() {
3617
		// Remote file uploads are allowed only via AJAX requests.
3618
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3619
			return;
3620
		}
3621
3622
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3623
		$remote_request_actions = array(
3624
			'jetpack_upload_file',
3625
			'jetpack_update_file',
3626
		);
3627
3628
		// phpcs:ignore WordPress.Security.NonceVerification
3629
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3630
			return;
3631
		}
3632
3633
		// Require Jetpack authentication for the remote file upload AJAX requests.
3634
		$this->connection_manager->require_jetpack_authentication();
3635
3636
		// Register the remote file upload AJAX handlers.
3637
		foreach ( $remote_request_actions as $action ) {
3638
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3639
		}
3640
	}
3641
3642
	/**
3643
	 * Handler for Jetpack remote file uploads.
3644
	 *
3645
	 * @access public
3646
	 */
3647
	public function remote_request_handlers() {
3648
		$action = current_filter();
0 ignored issues
show
$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...
3649
3650
		switch ( current_filter() ) {
3651
			case 'wp_ajax_nopriv_jetpack_upload_file':
3652
				$response = $this->upload_handler();
3653
				break;
3654
3655
			case 'wp_ajax_nopriv_jetpack_update_file':
3656
				$response = $this->upload_handler( true );
3657
				break;
3658
			default:
3659
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
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...
3660
				break;
3661
		}
3662
3663
		if ( ! $response ) {
3664
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
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...
3665
		}
3666
3667
		if ( is_wp_error( $response ) ) {
3668
			$status_code       = $response->get_error_data();
0 ignored issues
show
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...
3669
			$error             = $response->get_error_code();
0 ignored issues
show
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...
3670
			$error_description = $response->get_error_message();
0 ignored issues
show
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...
3671
3672
			if ( ! is_int( $status_code ) ) {
3673
				$status_code = 400;
3674
			}
3675
3676
			status_header( $status_code );
3677
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3678
		}
3679
3680
		status_header( 200 );
3681
		if ( true === $response ) {
3682
			exit;
3683
		}
3684
3685
		die( json_encode( (object) $response ) );
3686
	}
3687
3688
	/**
3689
	 * Uploads a file gotten from the global $_FILES.
3690
	 * If `$update_media_item` is true and `post_id` is defined
3691
	 * the attachment file of the media item (gotten through of the post_id)
3692
	 * will be updated instead of add a new one.
3693
	 *
3694
	 * @param  boolean $update_media_item - update media attachment
3695
	 * @return array - An array describing the uploadind files process
3696
	 */
3697
	function upload_handler( $update_media_item = false ) {
3698
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3699
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
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...
3700
		}
3701
3702
		$user = wp_authenticate( '', '' );
3703
		if ( ! $user || is_wp_error( $user ) ) {
3704
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
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...
3705
		}
3706
3707
		wp_set_current_user( $user->ID );
3708
3709
		if ( ! current_user_can( 'upload_files' ) ) {
3710
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
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...
3711
		}
3712
3713
		if ( empty( $_FILES ) ) {
3714
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
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...
3715
		}
3716
3717
		foreach ( array_keys( $_FILES ) as $files_key ) {
3718
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3719
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
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...
3720
			}
3721
		}
3722
3723
		$media_keys = array_keys( $_FILES['media'] );
3724
3725
		$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...
3726
		if ( ! $token || is_wp_error( $token ) ) {
3727
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
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...
3728
		}
3729
3730
		$uploaded_files = array();
3731
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3732
		unset( $GLOBALS['post'] );
3733
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3734
			$file = array();
3735
			foreach ( $media_keys as $media_key ) {
3736
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3737
			}
3738
3739
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3740
3741
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3742
			if ( $hmac_provided !== $hmac_file ) {
3743
				$uploaded_files[ $index ] = (object) array(
3744
					'error'             => 'invalid_hmac',
3745
					'error_description' => 'The corresponding HMAC for this file does not match',
3746
				);
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
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(
3797
					'error'             => 'unknown',
3798
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3799
				);
3800
			} elseif ( is_wp_error( $attachment_id ) ) {
3801
				$uploaded_files[ $index ] = (object) array(
3802
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3803
					'error_description' => $attachment_id->get_error_message(),
3804
				);
3805
			} else {
3806
				$attachment               = get_post( $attachment_id );
3807
				$uploaded_files[ $index ] = (object) array(
3808
					'id'   => (string) $attachment_id,
3809
					'file' => $attachment->post_title,
3810
					'url'  => wp_get_attachment_url( $attachment_id ),
3811
					'type' => $attachment->post_mime_type,
3812
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3813
				);
3814
				// Zip files uploads are not supported unless they are done for installation purposed
3815
				// lets delete them in case something goes wrong in this whole process
3816
				if ( 'application/zip' === $attachment->post_mime_type ) {
3817
					// Schedule a cleanup for 2 hours from now in case of failed install.
3818
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3819
				}
3820
			}
3821
		}
3822
		if ( ! is_null( $global_post ) ) {
3823
			$GLOBALS['post'] = $global_post;
3824
		}
3825
3826
		return $uploaded_files;
3827
	}
3828
3829
	/**
3830
	 * Add help to the Jetpack page
3831
	 *
3832
	 * @since Jetpack (1.2.3)
3833
	 * @return false if not the Jetpack page
3834
	 */
3835
	function admin_help() {
3836
		$current_screen = get_current_screen();
3837
3838
		// Overview
3839
		$current_screen->add_help_tab(
3840
			array(
3841
				'id'      => 'home',
3842
				'title'   => __( 'Home', 'jetpack' ),
3843
				'content' =>
3844
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3845
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3846
					'<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>',
3847
			)
3848
		);
3849
3850
		// Screen Content
3851
		if ( current_user_can( 'manage_options' ) ) {
3852
			$current_screen->add_help_tab(
3853
				array(
3854
					'id'      => 'settings',
3855
					'title'   => __( 'Settings', 'jetpack' ),
3856
					'content' =>
3857
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3858
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3859
						'<ol>' .
3860
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3861
							'<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>' .
3862
						'</ol>' .
3863
						'<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>',
3864
				)
3865
			);
3866
		}
3867
3868
		// Help Sidebar
3869
		$current_screen->set_help_sidebar(
3870
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3871
			'<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3872
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3873
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3874
		);
3875
	}
3876
3877
	function admin_menu_css() {
3878
		wp_enqueue_style( 'jetpack-icons' );
3879
	}
3880
3881
	function admin_menu_order() {
3882
		return true;
3883
	}
3884
3885 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3886
		$jp_menu_order = array();
3887
3888
		foreach ( $menu_order as $index => $item ) {
3889
			if ( $item != 'jetpack' ) {
3890
				$jp_menu_order[] = $item;
3891
			}
3892
3893
			if ( $index == 0 ) {
3894
				$jp_menu_order[] = 'jetpack';
3895
			}
3896
		}
3897
3898
		return $jp_menu_order;
3899
	}
3900
3901
	function admin_banner_styles() {
3902
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3903
3904 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3905
			wp_register_style(
3906
				'jetpack-dops-style',
3907
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3908
				array(),
3909
				JETPACK__VERSION
3910
			);
3911
		}
3912
3913
		wp_enqueue_style(
3914
			'jetpack',
3915
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3916
			array( 'jetpack-dops-style' ),
3917
			JETPACK__VERSION . '-20121016'
3918
		);
3919
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3920
		wp_style_add_data( 'jetpack', 'suffix', $min );
3921
	}
3922
3923
	function plugin_action_links( $actions ) {
3924
3925
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3926
3927
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
3928
			return array_merge(
3929
				$jetpack_home,
3930
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3931
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3932
				$actions
3933
			);
3934
		}
3935
3936
		return array_merge( $jetpack_home, $actions );
3937
	}
3938
3939
	/*
3940
	 * Registration flow:
3941
	 * 1 - ::admin_page_load() action=register
3942
	 * 2 - ::try_registration()
3943
	 * 3 - ::register()
3944
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3945
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3946
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3947
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3948
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3949
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3950
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3951
	 *       jetpack_id, jetpack_secret, jetpack_public
3952
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3953
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3954
	 * 5 - user logs in with WP.com account
3955
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3956
	 *		- Manager::authorize()
3957
	 *		- Manager::get_token()
3958
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3959
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3960
	 *			- which responds with access_token, token_type, scope
3961
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
3962
	 *		- Jetpack::activate_default_modules()
3963
	 *     		- Deactivates deprecated plugins
3964
	 *     		- Activates all default modules
3965
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3966
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3967
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3968
	 *     Done!
3969
	 */
3970
3971
	/**
3972
	 * Handles the page load events for the Jetpack admin page
3973
	 */
3974
	function admin_page_load() {
3975
		$error = false;
3976
3977
		// Make sure we have the right body class to hook stylings for subpages off of.
3978
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
3979
3980
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3981
			// Should only be used in intermediate redirects to preserve state across redirects
3982
			self::restate();
3983
		}
3984
3985
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3986
			// @todo: Add validation against a known whitelist
3987
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3988
			// User clicked in the iframe to link their accounts
3989
			if ( ! self::is_user_connected() ) {
3990
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3991
3992
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3993
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3994
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3995
3996
				if ( isset( $_GET['notes_iframe'] ) ) {
3997
					$connect_url .= '&notes_iframe';
3998
				}
3999
				wp_redirect( $connect_url );
4000
				exit;
4001
			} else {
4002
				if ( ! isset( $_GET['calypso_env'] ) ) {
4003
					self::state( 'message', 'already_authorized' );
4004
					wp_safe_redirect( self::admin_url() );
4005
					exit;
4006
				} else {
4007
					$connect_url  = $this->build_connect_url( true, false, $from );
4008
					$connect_url .= '&already_authorized=true';
4009
					wp_redirect( $connect_url );
4010
					exit;
4011
				}
4012
			}
4013
		}
4014
4015
		if ( isset( $_GET['action'] ) ) {
4016
			switch ( $_GET['action'] ) {
4017
				case 'authorize':
4018
					if ( self::is_active() && self::is_user_connected() ) {
4019
						self::state( 'message', 'already_authorized' );
4020
						wp_safe_redirect( self::admin_url() );
4021
						exit;
4022
					}
4023
					self::log( 'authorize' );
4024
					$client_server = new Jetpack_Client_Server();
4025
					$client_server->client_authorize();
4026
					exit;
4027
				case 'register':
4028
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4029
						$error = 'cheatin';
4030
						break;
4031
					}
4032
					check_admin_referer( 'jetpack-register' );
4033
					self::log( 'register' );
4034
					self::maybe_set_version_option();
4035
					$registered = self::try_registration();
4036
					if ( is_wp_error( $registered ) ) {
4037
						$error = $registered->get_error_code();
0 ignored issues
show
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...
4038
						self::state( 'error', $error );
4039
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
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...
4040
4041
						/**
4042
						 * Jetpack registration Error.
4043
						 *
4044
						 * @since 7.5.0
4045
						 *
4046
						 * @param string|int $error The error code.
4047
						 * @param \WP_Error $registered The error object.
4048
						 */
4049
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4050
						break;
4051
					}
4052
4053
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4054
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4055
4056
					/**
4057
					 * Jetpack registration Success.
4058
					 *
4059
					 * @since 7.5.0
4060
					 *
4061
					 * @param string $from 'from' GET parameter;
4062
					 */
4063
					do_action( 'jetpack_connection_register_success', $from );
4064
4065
					$url = $this->build_connect_url( true, $redirect, $from );
4066
4067
					if ( ! empty( $_GET['onboarding'] ) ) {
4068
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4069
					}
4070
4071
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4072
						$url = add_query_arg( 'auth_approved', 'true', $url );
4073
					}
4074
4075
					wp_redirect( $url );
4076
					exit;
4077
				case 'activate':
4078
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4079
						$error = 'cheatin';
4080
						break;
4081
					}
4082
4083
					$module = stripslashes( $_GET['module'] );
4084
					check_admin_referer( "jetpack_activate-$module" );
4085
					self::log( 'activate', $module );
4086
					if ( ! self::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::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...
4087
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4088
					}
4089
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4090
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4091
					exit;
4092
				case 'activate_default_modules':
4093
					check_admin_referer( 'activate_default_modules' );
4094
					self::log( 'activate_default_modules' );
4095
					self::restate();
4096
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4097
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4098
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4099
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4100
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4101
					exit;
4102
				case 'disconnect':
4103
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4104
						$error = 'cheatin';
4105
						break;
4106
					}
4107
4108
					check_admin_referer( 'jetpack-disconnect' );
4109
					self::log( 'disconnect' );
4110
					self::disconnect();
4111
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4112
					exit;
4113
				case 'reconnect':
4114
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4115
						$error = 'cheatin';
4116
						break;
4117
					}
4118
4119
					check_admin_referer( 'jetpack-reconnect' );
4120
					self::log( 'reconnect' );
4121
					$this->disconnect();
4122
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4123
					exit;
4124 View Code Duplication
				case 'deactivate':
4125
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4126
						$error = 'cheatin';
4127
						break;
4128
					}
4129
4130
					$modules = stripslashes( $_GET['module'] );
4131
					check_admin_referer( "jetpack_deactivate-$modules" );
4132
					foreach ( explode( ',', $modules ) as $module ) {
4133
						self::log( 'deactivate', $module );
4134
						self::deactivate_module( $module );
4135
						self::state( 'message', 'module_deactivated' );
4136
					}
4137
					self::state( 'module', $modules );
4138
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4139
					exit;
4140
				case 'unlink':
4141
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4142
					check_admin_referer( 'jetpack-unlink' );
4143
					self::log( 'unlink' );
4144
					Connection_Manager::disconnect_user();
4145
					self::state( 'message', 'unlinked' );
4146
					if ( 'sub-unlink' == $redirect ) {
4147
						wp_safe_redirect( admin_url() );
4148
					} else {
4149
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4150
					}
4151
					exit;
4152
				case 'onboard':
4153
					if ( ! current_user_can( 'manage_options' ) ) {
4154
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4155
					} else {
4156
						self::create_onboarding_token();
4157
						$url = $this->build_connect_url( true );
4158
4159
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4160
							$url = add_query_arg( 'onboarding', $token, $url );
4161
						}
4162
4163
						$calypso_env = $this->get_calypso_env();
4164
						if ( ! empty( $calypso_env ) ) {
4165
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4166
						}
4167
4168
						wp_redirect( $url );
4169
						exit;
4170
					}
4171
					exit;
4172
				default:
4173
					/**
4174
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4175
					 *
4176
					 * @since 2.6.0
4177
					 *
4178
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4179
					 */
4180
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4181
			}
4182
		}
4183
4184
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4185
			self::activate_new_modules( true );
4186
		}
4187
4188
		$message_code = self::state( 'message' );
4189
		if ( self::state( 'optin-manage' ) ) {
4190
			$activated_manage = $message_code;
4191
			$message_code     = 'jetpack-manage';
4192
		}
4193
4194
		switch ( $message_code ) {
4195
			case 'jetpack-manage':
4196
				$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>';
4197
				if ( $activated_manage ) {
0 ignored issues
show
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...
4198
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4199
				}
4200
				break;
4201
4202
		}
4203
4204
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4205
4206
		if ( ! empty( $deactivated_plugins ) ) {
4207
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4208
			$deactivated_titles  = array();
4209
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4210
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4211
					continue;
4212
				}
4213
4214
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4215
			}
4216
4217
			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...
4218
				if ( $this->message ) {
4219
					$this->message .= "<br /><br />\n";
4220
				}
4221
4222
				$this->message .= wp_sprintf(
4223
					_n(
4224
						'Jetpack contains the most recent version of the old %l plugin.',
4225
						'Jetpack contains the most recent versions of the old %l plugins.',
4226
						count( $deactivated_titles ),
4227
						'jetpack'
4228
					),
4229
					$deactivated_titles
4230
				);
4231
4232
				$this->message .= "<br />\n";
4233
4234
				$this->message .= _n(
4235
					'The old version has been deactivated and can be removed from your site.',
4236
					'The old versions have been deactivated and can be removed from your site.',
4237
					count( $deactivated_titles ),
4238
					'jetpack'
4239
				);
4240
			}
4241
		}
4242
4243
		$this->privacy_checks = self::state( 'privacy_checks' );
4244
4245
		if ( $this->message || $this->error || $this->privacy_checks ) {
4246
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4247
		}
4248
4249
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4250
	}
4251
4252
	function admin_notices() {
4253
4254
		if ( $this->error ) {
4255
			?>
4256
<div id="message" class="jetpack-message jetpack-err">
4257
	<div class="squeezer">
4258
		<h2>
4259
			<?php
4260
			echo wp_kses(
4261
				$this->error,
4262
				array(
4263
					'a'      => array( 'href' => array() ),
4264
					'small'  => true,
4265
					'code'   => true,
4266
					'strong' => true,
4267
					'br'     => true,
4268
					'b'      => true,
4269
				)
4270
			);
4271
			?>
4272
			</h2>
4273
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4274
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4275
<?php	endif; ?>
4276
	</div>
4277
</div>
4278
			<?php
4279
		}
4280
4281
		if ( $this->message ) {
4282
			?>
4283
<div id="message" class="jetpack-message">
4284
	<div class="squeezer">
4285
		<h2>
4286
			<?php
4287
			echo wp_kses(
4288
				$this->message,
4289
				array(
4290
					'strong' => array(),
4291
					'a'      => array( 'href' => true ),
4292
					'br'     => true,
4293
				)
4294
			);
4295
			?>
4296
			</h2>
4297
	</div>
4298
</div>
4299
			<?php
4300
		}
4301
4302
		if ( $this->privacy_checks ) :
4303
			$module_names = $module_slugs = array();
4304
4305
			$privacy_checks = explode( ',', $this->privacy_checks );
4306
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4307
			foreach ( $privacy_checks as $module_slug ) {
4308
				$module = self::get_module( $module_slug );
4309
				if ( ! $module ) {
4310
					continue;
4311
				}
4312
4313
				$module_slugs[] = $module_slug;
4314
				$module_names[] = "<strong>{$module['name']}</strong>";
4315
			}
4316
4317
			$module_slugs = join( ',', $module_slugs );
4318
			?>
4319
<div id="message" class="jetpack-message jetpack-err">
4320
	<div class="squeezer">
4321
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4322
		<p>
4323
			<?php
4324
			echo wp_kses(
4325
				wptexturize(
4326
					wp_sprintf(
4327
						_nx(
4328
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4329
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4330
							count( $privacy_checks ),
4331
							'%l = list of Jetpack module/feature names',
4332
							'jetpack'
4333
						),
4334
						$module_names
4335
					)
4336
				),
4337
				array( 'strong' => true )
4338
			);
4339
4340
			echo "\n<br />\n";
4341
4342
			echo wp_kses(
4343
				sprintf(
4344
					_nx(
4345
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4346
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4347
						count( $privacy_checks ),
4348
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4349
						'jetpack'
4350
					),
4351
					wp_nonce_url(
4352
						self::admin_url(
4353
							array(
4354
								'page'   => 'jetpack',
4355
								'action' => 'deactivate',
4356
								'module' => urlencode( $module_slugs ),
4357
							)
4358
						),
4359
						"jetpack_deactivate-$module_slugs"
4360
					),
4361
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4362
				),
4363
				array(
4364
					'a' => array(
4365
						'href'  => true,
4366
						'title' => true,
4367
					),
4368
				)
4369
			);
4370
			?>
4371
		</p>
4372
	</div>
4373
</div>
4374
			<?php
4375
endif;
4376
	}
4377
4378
	/**
4379
	 * We can't always respond to a signed XML-RPC request with a
4380
	 * helpful error message. In some circumstances, doing so could
4381
	 * leak information.
4382
	 *
4383
	 * Instead, track that the error occurred via a Jetpack_Option,
4384
	 * and send that data back in the heartbeat.
4385
	 * All this does is increment a number, but it's enough to find
4386
	 * trends.
4387
	 *
4388
	 * @param WP_Error $xmlrpc_error The error produced during
4389
	 *                               signature validation.
4390
	 */
4391
	function track_xmlrpc_error( $xmlrpc_error ) {
4392
		$code = is_wp_error( $xmlrpc_error )
4393
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
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...
4394
			: 'should-not-happen';
4395
4396
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4397
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4398
			// No need to update the option if we already have
4399
			// this code stored.
4400
			return;
4401
		}
4402
		$xmlrpc_errors[ $code ] = true;
4403
4404
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
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...
4405
	}
4406
4407
	/**
4408
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4409
	 */
4410
	function stat( $group, $detail ) {
4411
		if ( ! isset( $this->stats[ $group ] ) ) {
4412
			$this->stats[ $group ] = array();
4413
		}
4414
		$this->stats[ $group ][] = $detail;
4415
	}
4416
4417
	/**
4418
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4419
	 */
4420
	function do_stats( $method = '' ) {
4421
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4422
			foreach ( $this->stats as $group => $stats ) {
4423
				if ( is_array( $stats ) && count( $stats ) ) {
4424
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4425
					if ( 'server_side' === $method ) {
4426
						self::do_server_side_stat( $args );
4427
					} else {
4428
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4429
					}
4430
				}
4431
				unset( $this->stats[ $group ] );
4432
			}
4433
		}
4434
	}
4435
4436
	/**
4437
	 * Runs stats code for a one-off, server-side.
4438
	 *
4439
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4440
	 *
4441
	 * @return bool If it worked.
4442
	 */
4443
	static function do_server_side_stat( $args ) {
4444
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4445
		if ( is_wp_error( $response ) ) {
4446
			return false;
4447
		}
4448
4449
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4450
			return false;
4451
		}
4452
4453
		return true;
4454
	}
4455
4456
	/**
4457
	 * Builds the stats url.
4458
	 *
4459
	 * @param $args array|string The arguments to append to the URL.
4460
	 *
4461
	 * @return string The URL to be pinged.
4462
	 */
4463
	static function build_stats_url( $args ) {
4464
		$defaults = array(
4465
			'v'    => 'wpcom2',
4466
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4467
		);
4468
		$args     = wp_parse_args( $args, $defaults );
4469
		/**
4470
		 * Filter the URL used as the Stats tracking pixel.
4471
		 *
4472
		 * @since 2.3.2
4473
		 *
4474
		 * @param string $url Base URL used as the Stats tracking pixel.
4475
		 */
4476
		$base_url = apply_filters(
4477
			'jetpack_stats_base_url',
4478
			'https://pixel.wp.com/g.gif'
4479
		);
4480
		$url      = add_query_arg( $args, $base_url );
4481
		return $url;
4482
	}
4483
4484
	/**
4485
	 * Get the role of the current user.
4486
	 *
4487
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4488
	 *
4489
	 * @access public
4490
	 * @static
4491
	 *
4492
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4493
	 */
4494
	public static function translate_current_user_to_role() {
4495
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4496
4497
		$roles = new Roles();
4498
		return $roles->translate_current_user_to_role();
4499
	}
4500
4501
	/**
4502
	 * Get the role of a particular user.
4503
	 *
4504
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4505
	 *
4506
	 * @access public
4507
	 * @static
4508
	 *
4509
	 * @param \WP_User $user User object.
4510
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4511
	 */
4512
	public static function translate_user_to_role( $user ) {
4513
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4514
4515
		$roles = new Roles();
4516
		return $roles->translate_user_to_role( $user );
4517
	}
4518
4519
	/**
4520
	 * Get the minimum capability for a role.
4521
	 *
4522
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4523
	 *
4524
	 * @access public
4525
	 * @static
4526
	 *
4527
	 * @param string $role Role name.
4528
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4529
	 */
4530
	public static function translate_role_to_cap( $role ) {
4531
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4532
4533
		$roles = new Roles();
4534
		return $roles->translate_role_to_cap( $role );
4535
	}
4536
4537
	/**
4538
	 * Sign a user role with the master access token.
4539
	 * If not specified, will default to the current user.
4540
	 *
4541
	 * @deprecated since 7.7
4542
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4543
	 *
4544
	 * @access public
4545
	 * @static
4546
	 *
4547
	 * @param string $role    User role.
4548
	 * @param int    $user_id ID of the user.
0 ignored issues
show
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...
4549
	 * @return string Signed user role.
4550
	 */
4551
	public static function sign_role( $role, $user_id = null ) {
4552
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4553
		return self::connection()->sign_role( $role, $user_id );
4554
	}
4555
4556
	/**
4557
	 * Builds a URL to the Jetpack connection auth page
4558
	 *
4559
	 * @since 3.9.5
4560
	 *
4561
	 * @param bool        $raw If true, URL will not be escaped.
4562
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4563
	 *                              If string, will be a custom redirect.
4564
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4565
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4566
	 *
4567
	 * @return string Connect URL
4568
	 */
4569
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4570
		$site_id    = Jetpack_Options::get_option( 'id' );
4571
		$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...
4572
4573
		if ( $register || ! $blog_token || ! $site_id ) {
4574
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4575
4576
			if ( ! empty( $redirect ) ) {
4577
				$url = add_query_arg(
4578
					'redirect',
4579
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4580
					$url
4581
				);
4582
			}
4583
4584
			if ( is_network_admin() ) {
4585
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4586
			}
4587
4588
			$calypso_env = self::get_calypso_env();
4589
4590
			if ( ! empty( $calypso_env ) ) {
4591
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4592
			}
4593
		} else {
4594
4595
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4596
			// because otherwise this logic can get us in to a loop.
4597
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4598
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4599
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4600
4601
				$response = Client::wpcom_json_api_request_as_blog(
4602
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4603
					'1.1'
4604
				);
4605
4606
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4607
4608
					// Generating a register URL instead to refresh the existing token
4609
					return $this->build_connect_url( $raw, $redirect, $from, true );
4610
				}
4611
			}
4612
4613
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4569 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...
4614
		}
4615
4616
		if ( $from ) {
4617
			$url = add_query_arg( 'from', $from, $url );
4618
		}
4619
4620
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4621
		/**
4622
		 * Filter the URL used when connecting a user to a WordPress.com account.
4623
		 *
4624
		 * @since 8.1.0
4625
		 *
4626
		 * @param string $url Connection URL.
4627
		 * @param bool   $raw If true, URL will not be escaped.
4628
		 */
4629
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4630
	}
4631
4632
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4633
4634
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4635
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4636
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4637
4638
		if ( $iframe ) {
4639
			add_filter( 'jetpack_api_url', array( __CLASS__, 'filter_connect_api_iframe_url' ), 10, 2 );
4640
		}
4641
4642
		$c8n = self::connection();
4643
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
$redirect 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...
4644
4645
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4646
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4647
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4648
4649
		if ( $iframe ) {
4650
			remove_filter( 'jetpack_api_url', array( __CLASS__, 'filter_connect_api_iframe_url' ) );
4651
		}
4652
4653
		return $url;
4654
	}
4655
4656
	/**
4657
	 * Filters the connection URL parameter array.
4658
	 *
4659
	 * @param Array $args default URL parameters used by the package.
4660
	 * @return Array the modified URL arguments array.
4661
	 */
4662
	public static function filter_connect_request_body( $args ) {
4663
		if (
4664
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4665
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4666
		) {
4667
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4668
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4669
				? $gp_locale->slug
4670
				: '';
4671
		}
4672
4673
		$tracking        = new Tracking();
4674
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4675
4676
		$args = array_merge(
4677
			$args,
4678
			array(
4679
				'_ui' => $tracks_identity['_ui'],
4680
				'_ut' => $tracks_identity['_ut'],
4681
			)
4682
		);
4683
4684
		$calypso_env = self::get_calypso_env();
4685
4686
		if ( ! empty( $calypso_env ) ) {
4687
			$args['calypso_env'] = $calypso_env;
4688
		}
4689
4690
		return $args;
4691
	}
4692
4693
	/**
4694
	 * Filters the URL that will process the connection data. It can be different from the URL
4695
	 * that we send the user to after everything is done.
4696
	 *
4697
	 * @param String $processing_url the default redirect URL used by the package.
4698
	 * @return String the modified URL.
4699
	 */
4700
	public static function filter_connect_processing_url( $processing_url ) {
4701
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4702
		return $processing_url;
4703
	}
4704
4705
	/**
4706
	 * Filters the redirection URL that is used for connect requests. The redirect
4707
	 * URL should return the user back to the Jetpack console.
4708
	 *
4709
	 * @param String $redirect the default redirect URL used by the package.
4710
	 * @return String the modified URL.
4711
	 */
4712
	public static function filter_connect_redirect_url( $redirect ) {
4713
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4714
		$redirect           = $redirect
4715
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4716
			: $jetpack_admin_page;
4717
4718
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4719
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4720
		}
4721
4722
		return $redirect;
4723
	}
4724
4725
	/**
4726
	 * Filters the API URL that is used for connect requests. The method
4727
	 * intercepts only the authorize URL and replaces it with another if needed.
4728
	 *
4729
	 * @param String $api_url the default redirect API URL used by the package.
4730
	 * @param String $relative_url the path of the URL that's being used.
4731
	 * @return String the modified URL.
4732
	 */
4733
	public static function filter_connect_api_iframe_url( $api_url, $relative_url ) {
4734
4735
		// Short-circuit on anything that is not related to connect requests.
4736
		if ( 'authorize' !== $relative_url ) {
4737
			return $api_url;
4738
		}
4739
4740
		$c8n = self::connection();
4741
4742
		return $c8n->api_url( 'authorize_iframe' );
4743
	}
4744
4745
	/**
4746
	 * This action fires at the beginning of the Manager::authorize method.
4747
	 */
4748
	public static function authorize_starting() {
4749
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4750
		// Checking if site has been active/connected previously before recording unique connection.
4751
		if ( ! $jetpack_unique_connection ) {
4752
			// jetpack_unique_connection option has never been set.
4753
			$jetpack_unique_connection = array(
4754
				'connected'    => 0,
4755
				'disconnected' => 0,
4756
				'version'      => '3.6.1',
4757
			);
4758
4759
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4760
4761
			// Track unique connection.
4762
			$jetpack = self::init();
4763
4764
			$jetpack->stat( 'connections', 'unique-connection' );
4765
			$jetpack->do_stats( 'server_side' );
4766
		}
4767
4768
		// Increment number of times connected.
4769
		$jetpack_unique_connection['connected'] += 1;
4770
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4771
	}
4772
4773
	/**
4774
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4775
	 * linked.
4776
	 */
4777
	public static function authorize_ending_linked() {
4778
		// Don't activate anything since we are just connecting a user.
4779
		self::state( 'message', 'linked' );
4780
	}
4781
4782
	/**
4783
	 * This action fires at the end of the Manager::authorize method when the master user is
4784
	 * authorized.
4785
	 *
4786
	 * @param array $data The request data.
4787
	 */
4788
	public static function authorize_ending_authorized( $data ) {
4789
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4790
		self::invalidate_onboarding_token();
4791
4792
		// If redirect_uri is SSO, ensure SSO module is enabled.
4793
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4794
4795
		/** This filter is documented in class.jetpack-cli.php */
4796
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4797
4798
		$activate_sso = (
4799
			isset( $redirect_options['action'] ) &&
4800
			'jetpack-sso' === $redirect_options['action'] &&
4801
			$jetpack_start_enable_sso
4802
		);
4803
4804
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4805
4806
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4807
	}
4808
4809
	/**
4810
	 * Get our assumed site creation date.
4811
	 * Calculated based on the earlier date of either:
4812
	 * - Earliest admin user registration date.
4813
	 * - Earliest date of post of any post type.
4814
	 *
4815
	 * @since 7.2.0
4816
	 * @deprecated since 7.8.0
4817
	 *
4818
	 * @return string Assumed site creation date and time.
4819
	 */
4820
	public static function get_assumed_site_creation_date() {
4821
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4822
		return self::connection()->get_assumed_site_creation_date();
4823
	}
4824
4825 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4826
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4827
4828
		if ( $activation_source_name ) {
4829
			$args['_as'] = urlencode( $activation_source_name );
4830
		}
4831
4832
		if ( $activation_source_keyword ) {
4833
			$args['_ak'] = urlencode( $activation_source_keyword );
4834
		}
4835
	}
4836
4837
	function build_reconnect_url( $raw = false ) {
4838
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4839
		return $raw ? $url : esc_url( $url );
4840
	}
4841
4842
	public static function admin_url( $args = null ) {
4843
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4844
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4845
		return $url;
4846
	}
4847
4848
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4849
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4850
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4851
	}
4852
4853
	function dismiss_jetpack_notice() {
4854
4855
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4856
			return;
4857
		}
4858
4859
		switch ( $_GET['jetpack-notice'] ) {
4860
			case 'dismiss':
4861
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4862
4863
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4864
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4865
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4866
				}
4867
				break;
4868
		}
4869
	}
4870
4871
	public static function sort_modules( $a, $b ) {
4872
		if ( $a['sort'] == $b['sort'] ) {
4873
			return 0;
4874
		}
4875
4876
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4877
	}
4878
4879
	function ajax_recheck_ssl() {
4880
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4881
		$result = self::permit_ssl( true );
4882
		wp_send_json(
4883
			array(
4884
				'enabled' => $result,
4885
				'message' => get_transient( 'jetpack_https_test_message' ),
4886
			)
4887
		);
4888
	}
4889
4890
	/* Client API */
4891
4892
	/**
4893
	 * Returns the requested Jetpack API URL
4894
	 *
4895
	 * @deprecated since 7.7
4896
	 * @return string
4897
	 */
4898
	public static function api_url( $relative_url ) {
4899
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4900
		$connection = self::connection();
4901
		return $connection->api_url( $relative_url );
4902
	}
4903
4904
	/**
4905
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
4906
	 *
4907
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4908
	 */
4909
	public static function fix_url_for_bad_hosts( $url ) {
4910
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
4911
		return Connection_Utils::fix_url_for_bad_hosts( $url );
4912
	}
4913
4914
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4915
		// Default to a blog token.
4916
		$token_type = 'blog';
4917
4918
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4919
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4920
			if ( ! empty( $_GET['onboarding'] ) ) {
4921
				$jpo = $_GET;
4922
			} else {
4923
				$jpo = json_decode( $request_data, true );
4924
			}
4925
4926
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4927
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4928
4929
			if (
4930
				isset( $jpo_user )
4931
				&& isset( $jpo_token )
4932
				&& is_email( $jpo_user )
4933
				&& ctype_alnum( $jpo_token )
4934
				&& isset( $_GET['rest_route'] )
4935
				&& self::validate_onboarding_token_action(
4936
					$jpo_token,
4937
					$_GET['rest_route']
4938
				)
4939
			) {
4940
				$jp_user = get_user_by( 'email', $jpo_user );
4941
				if ( is_a( $jp_user, 'WP_User' ) ) {
4942
					wp_set_current_user( $jp_user->ID );
4943
					$user_can = is_multisite()
4944
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4945
						: current_user_can( 'manage_options' );
4946
					if ( $user_can ) {
4947
						$token_type              = 'user';
4948
						$token->external_user_id = $jp_user->ID;
4949
					}
4950
				}
4951
			}
4952
4953
			$token_data['type']    = $token_type;
4954
			$token_data['user_id'] = $token->external_user_id;
4955
		}
4956
4957
		return $token_data;
4958
	}
4959
4960
	/**
4961
	 * Create a random secret for validating onboarding payload
4962
	 *
4963
	 * @return string Secret token
4964
	 */
4965
	public static function create_onboarding_token() {
4966
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4967
			$token = wp_generate_password( 32, false );
4968
			Jetpack_Options::update_option( 'onboarding', $token );
4969
		}
4970
4971
		return $token;
4972
	}
4973
4974
	/**
4975
	 * Remove the onboarding token
4976
	 *
4977
	 * @return bool True on success, false on failure
4978
	 */
4979
	public static function invalidate_onboarding_token() {
4980
		return Jetpack_Options::delete_option( 'onboarding' );
4981
	}
4982
4983
	/**
4984
	 * Validate an onboarding token for a specific action
4985
	 *
4986
	 * @return boolean True if token/action pair is accepted, false if not
4987
	 */
4988
	public static function validate_onboarding_token_action( $token, $action ) {
4989
		// Compare tokens, bail if tokens do not match
4990
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4991
			return false;
4992
		}
4993
4994
		// List of valid actions we can take
4995
		$valid_actions = array(
4996
			'/jetpack/v4/settings',
4997
		);
4998
4999
		// Whitelist the action
5000
		if ( ! in_array( $action, $valid_actions ) ) {
5001
			return false;
5002
		}
5003
5004
		return true;
5005
	}
5006
5007
	/**
5008
	 * Checks to see if the URL is using SSL to connect with Jetpack
5009
	 *
5010
	 * @since 2.3.3
5011
	 * @return boolean
5012
	 */
5013
	public static function permit_ssl( $force_recheck = false ) {
5014
		// Do some fancy tests to see if ssl is being supported
5015
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5016
			$message = '';
5017
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5018
				$ssl = 0;
5019
			} else {
5020
				switch ( JETPACK_CLIENT__HTTPS ) {
5021
					case 'NEVER':
5022
						$ssl     = 0;
5023
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5024
						break;
5025
					case 'ALWAYS':
5026
					case 'AUTO':
5027
					default:
5028
						$ssl = 1;
5029
						break;
5030
				}
5031
5032
				// If it's not 'NEVER', test to see
5033
				if ( $ssl ) {
5034
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5035
						$ssl     = 0;
5036
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5037
					} else {
5038
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5039
						if ( is_wp_error( $response ) ) {
5040
							$ssl     = 0;
5041
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5042
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5043
							$ssl     = 0;
5044
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5045
						}
5046
					}
5047
				}
5048
			}
5049
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5050
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5051
		}
5052
5053
		return (bool) $ssl;
5054
	}
5055
5056
	/*
5057
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5058
	 */
5059
	public function alert_auto_ssl_fail() {
5060
		if ( ! current_user_can( 'manage_options' ) ) {
5061
			return;
5062
		}
5063
5064
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5065
		?>
5066
5067
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5068
			<div class="jp-banner__content">
5069
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5070
				<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>
5071
				<p>
5072
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5073
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5074
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5075
				</p>
5076
				<p>
5077
					<?php
5078
					printf(
5079
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5080
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5081
						esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' )
5082
					);
5083
					?>
5084
				</p>
5085
			</div>
5086
		</div>
5087
		<style>
5088
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5089
		</style>
5090
		<script type="text/javascript">
5091
			jQuery( document ).ready( function( $ ) {
5092
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5093
					var $this = $( this );
5094
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5095
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5096
					e.preventDefault();
5097
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5098
					$.post( ajaxurl, data )
5099
					  .done( function( response ) {
5100
						  if ( response.enabled ) {
5101
							  $( '#jetpack-ssl-warning' ).hide();
5102
						  } else {
5103
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5104
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5105
						  }
5106
					  }.bind( $this ) );
5107
				} );
5108
			} );
5109
		</script>
5110
5111
		<?php
5112
	}
5113
5114
	/**
5115
	 * Returns the Jetpack XML-RPC API
5116
	 *
5117
	 * @deprecated 8.0 Use Connection_Manager instead.
5118
	 * @return string
5119
	 */
5120
	public static function xmlrpc_api_url() {
5121
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5122
		return self::connection()->xmlrpc_api_url();
5123
	}
5124
5125
	public static function connection() {
5126
		return self::init()->connection_manager;
5127
	}
5128
5129
	/**
5130
	 * Creates two secret tokens and the end of life timestamp for them.
5131
	 *
5132
	 * Note these tokens are unique per call, NOT static per site for connecting.
5133
	 *
5134
	 * @since 2.6
5135
	 * @param String  $action  The action name.
5136
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be false|integer?

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...
5137
	 * @param Integer $exp     Expiration time in seconds.
5138
	 * @return array
5139
	 */
5140
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5141
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5142
	}
5143
5144
	public static function get_secrets( $action, $user_id ) {
5145
		$secrets = self::connection()->get_secrets( $action, $user_id );
5146
5147
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5148
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
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...
5149
		}
5150
5151
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5152
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
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...
5153
		}
5154
5155
		return $secrets;
5156
	}
5157
5158
	/**
5159
	 * @deprecated 7.5 Use Connection_Manager instead.
5160
	 *
5161
	 * @param $action
5162
	 * @param $user_id
5163
	 */
5164
	public static function delete_secrets( $action, $user_id ) {
5165
		return self::connection()->delete_secrets( $action, $user_id );
5166
	}
5167
5168
	/**
5169
	 * Builds the timeout limit for queries talking with the wpcom servers.
5170
	 *
5171
	 * Based on local php max_execution_time in php.ini
5172
	 *
5173
	 * @since 2.6
5174
	 * @return int
5175
	 * @deprecated
5176
	 **/
5177
	public function get_remote_query_timeout_limit() {
5178
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5179
		return self::get_max_execution_time();
5180
	}
5181
5182
	/**
5183
	 * Builds the timeout limit for queries talking with the wpcom servers.
5184
	 *
5185
	 * Based on local php max_execution_time in php.ini
5186
	 *
5187
	 * @since 5.4
5188
	 * @return int
5189
	 **/
5190
	public static function get_max_execution_time() {
5191
		$timeout = (int) ini_get( 'max_execution_time' );
5192
5193
		// Ensure exec time set in php.ini
5194
		if ( ! $timeout ) {
5195
			$timeout = 30;
5196
		}
5197
		return $timeout;
5198
	}
5199
5200
	/**
5201
	 * Sets a minimum request timeout, and returns the current timeout
5202
	 *
5203
	 * @since 5.4
5204
	 **/
5205 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5206
		$timeout = self::get_max_execution_time();
5207
		if ( $timeout < $min_timeout ) {
5208
			$timeout = $min_timeout;
5209
			set_time_limit( $timeout );
5210
		}
5211
		return $timeout;
5212
	}
5213
5214
	/**
5215
	 * Takes the response from the Jetpack register new site endpoint and
5216
	 * verifies it worked properly.
5217
	 *
5218
	 * @since 2.6
5219
	 * @deprecated since 7.7.0
5220
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5221
	 **/
5222
	public function validate_remote_register_response() {
5223
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5224
	}
5225
5226
	/**
5227
	 * @return bool|WP_Error
5228
	 */
5229
	public static function register() {
5230
		$tracking = new Tracking();
5231
		$tracking->record_user_event( 'jpc_register_begin' );
5232
5233
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5234
5235
		$connection   = self::connection();
5236
		$registration = $connection->register();
5237
5238
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5239
5240
		if ( ! $registration || is_wp_error( $registration ) ) {
5241
			return $registration;
5242
		}
5243
5244
		return true;
5245
	}
5246
5247
	/**
5248
	 * Filters the registration request body to include tracking properties.
5249
	 *
5250
	 * @param Array $properties
5251
	 * @return Array amended properties.
5252
	 */
5253 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5254
		$tracking        = new Tracking();
5255
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5256
5257
		return array_merge(
5258
			$properties,
5259
			array(
5260
				'_ui' => $tracks_identity['_ui'],
5261
				'_ut' => $tracks_identity['_ut'],
5262
			)
5263
		);
5264
	}
5265
5266
	/**
5267
	 * Filters the token request body to include tracking properties.
5268
	 *
5269
	 * @param Array $properties
5270
	 * @return Array amended properties.
5271
	 */
5272 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5273
		$tracking        = new Tracking();
5274
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5275
5276
		return array_merge(
5277
			$properties,
5278
			array(
5279
				'_ui' => $tracks_identity['_ui'],
5280
				'_ut' => $tracks_identity['_ut'],
5281
			)
5282
		);
5283
	}
5284
5285
	/**
5286
	 * If the db version is showing something other that what we've got now, bump it to current.
5287
	 *
5288
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
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...
5289
	 */
5290
	public static function maybe_set_version_option() {
5291
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5292
		if ( JETPACK__VERSION != $version ) {
5293
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5294
5295
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5296
				/** This action is documented in class.jetpack.php */
5297
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5298
			}
5299
5300
			return true;
5301
		}
5302
		return false;
5303
	}
5304
5305
	/* Client Server API */
5306
5307
	/**
5308
	 * Loads the Jetpack XML-RPC client.
5309
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5310
	 *
5311
	 * @deprecated since 7.7.0
5312
	 */
5313
	public static function load_xml_rpc_client() {
5314
		// Removed the php notice that shows up in order to give time to Akismet and VaultPress time to update.
5315
		// _deprecated_function( __METHOD__, 'jetpack-7.7' );
5316
	}
5317
5318
	/**
5319
	 * Resets the saved authentication state in between testing requests.
5320
	 */
5321
	public function reset_saved_auth_state() {
5322
		$this->rest_authentication_status = null;
5323
		$this->connection_manager->reset_saved_auth_state();
5324
	}
5325
5326
	/**
5327
	 * Verifies the signature of the current request.
5328
	 *
5329
	 * @deprecated since 7.7.0
5330
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5331
	 *
5332
	 * @return false|array
5333
	 */
5334
	public function verify_xml_rpc_signature() {
5335
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5336
		return self::connection()->verify_xml_rpc_signature();
5337
	}
5338
5339
	/**
5340
	 * Verifies the signature of the current request.
5341
	 *
5342
	 * This function has side effects and should not be used. Instead,
5343
	 * use the memoized version `->verify_xml_rpc_signature()`.
5344
	 *
5345
	 * @deprecated since 7.7.0
5346
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5347
	 * @internal
5348
	 */
5349
	private function internal_verify_xml_rpc_signature() {
5350
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5351
	}
5352
5353
	/**
5354
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5355
	 *
5356
	 * @deprecated since 7.7.0
5357
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5358
	 *
5359
	 * @param \WP_User|mixed $user     User object if authenticated.
5360
	 * @param string         $username Username.
5361
	 * @param string         $password Password string.
5362
	 * @return \WP_User|mixed Authenticated user or error.
5363
	 */
5364
	public function authenticate_jetpack( $user, $username, $password ) {
5365
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5366
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5367
	}
5368
5369
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5370
	// Uses the existing XMLRPC request signing implementation.
5371
	function wp_rest_authenticate( $user ) {
5372
		if ( ! empty( $user ) ) {
5373
			// Another authentication method is in effect.
5374
			return $user;
5375
		}
5376
5377
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5378
			// Nothing to do for this authentication method.
5379
			return null;
5380
		}
5381
5382
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5383
			// Nothing to do for this authentication method.
5384
			return null;
5385
		}
5386
5387
		// Ensure that we always have the request body available.  At this
5388
		// point, the WP REST API code to determine the request body has not
5389
		// run yet.  That code may try to read from 'php://input' later, but
5390
		// this can only be done once per request in PHP versions prior to 5.6.
5391
		// So we will go ahead and perform this read now if needed, and save
5392
		// the request body where both the Jetpack signature verification code
5393
		// and the WP REST API code can see it.
5394
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5395
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5396
		}
5397
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5398
5399
		// Only support specific request parameters that have been tested and
5400
		// are known to work with signature verification.  A different method
5401
		// can be passed to the WP REST API via the '?_method=' parameter if
5402
		// needed.
5403
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5404
			$this->rest_authentication_status = new WP_Error(
5405
				'rest_invalid_request',
0 ignored issues
show
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...
5406
				__( 'This request method is not supported.', 'jetpack' ),
5407
				array( 'status' => 400 )
5408
			);
5409
			return null;
5410
		}
5411
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5412
			$this->rest_authentication_status = new WP_Error(
5413
				'rest_invalid_request',
0 ignored issues
show
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...
5414
				__( 'This request method does not support body parameters.', 'jetpack' ),
5415
				array( 'status' => 400 )
5416
			);
5417
			return null;
5418
		}
5419
5420
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5421
5422
		if (
5423
			$verified &&
5424
			isset( $verified['type'] ) &&
5425
			'user' === $verified['type'] &&
5426
			! empty( $verified['user_id'] )
5427
		) {
5428
			// Authentication successful.
5429
			$this->rest_authentication_status = true;
5430
			return $verified['user_id'];
5431
		}
5432
5433
		// Something else went wrong.  Probably a signature error.
5434
		$this->rest_authentication_status = new WP_Error(
5435
			'rest_invalid_signature',
0 ignored issues
show
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...
5436
			__( 'The request is not signed correctly.', 'jetpack' ),
5437
			array( 'status' => 400 )
5438
		);
5439
		return null;
5440
	}
5441
5442
	/**
5443
	 * Report authentication status to the WP REST API.
5444
	 *
5445
	 * @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
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...
5446
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5447
	 */
5448
	public function wp_rest_authentication_errors( $value ) {
5449
		if ( $value !== null ) {
5450
			return $value;
5451
		}
5452
		return $this->rest_authentication_status;
5453
	}
5454
5455
	/**
5456
	 * Add our nonce to this request.
5457
	 *
5458
	 * @deprecated since 7.7.0
5459
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5460
	 *
5461
	 * @param int    $timestamp Timestamp of the request.
5462
	 * @param string $nonce     Nonce string.
5463
	 */
5464
	public function add_nonce( $timestamp, $nonce ) {
5465
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5466
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5467
	}
5468
5469
	/**
5470
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5471
	 * Capture it here so we can verify the signature later.
5472
	 *
5473
	 * @deprecated since 7.7.0
5474
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5475
	 *
5476
	 * @param array $methods XMLRPC methods.
5477
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5478
	 */
5479
	public function xmlrpc_methods( $methods ) {
5480
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5481
		return $this->connection_manager->xmlrpc_methods( $methods );
5482
	}
5483
5484
	/**
5485
	 * Register additional public XMLRPC methods.
5486
	 *
5487
	 * @deprecated since 7.7.0
5488
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5489
	 *
5490
	 * @param array $methods Public XMLRPC methods.
5491
	 * @return array Public XMLRPC methods, with the getOptions one.
5492
	 */
5493
	public function public_xmlrpc_methods( $methods ) {
5494
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5495
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5496
	}
5497
5498
	/**
5499
	 * Handles a getOptions XMLRPC method call.
5500
	 *
5501
	 * @deprecated since 7.7.0
5502
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5503
	 *
5504
	 * @param array $args method call arguments.
5505
	 * @return array an amended XMLRPC server options array.
5506
	 */
5507
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5508
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5509
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
5510
	}
5511
5512
	/**
5513
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5514
	 *
5515
	 * @deprecated since 7.7.0
5516
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5517
	 *
5518
	 * @param array $options Standard Core options.
5519
	 * @return array Amended options.
5520
	 */
5521
	public function xmlrpc_options( $options ) {
5522
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5523
		return $this->connection_manager->xmlrpc_options( $options );
5524
	}
5525
5526
	/**
5527
	 * Cleans nonces that were saved when calling ::add_nonce.
5528
	 *
5529
	 * @deprecated since 7.7.0
5530
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5531
	 *
5532
	 * @param bool $all whether to clean even non-expired nonces.
5533
	 */
5534
	public static function clean_nonces( $all = false ) {
5535
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5536
		return self::connection()->clean_nonces( $all );
5537
	}
5538
5539
	/**
5540
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5541
	 * SET: state( $key, $value );
5542
	 * GET: $value = state( $key );
5543
	 *
5544
	 * @param string $key
0 ignored issues
show
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...
5545
	 * @param string $value
0 ignored issues
show
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...
5546
	 * @param bool   $restate private
5547
	 */
5548
	public static function state( $key = null, $value = null, $restate = false ) {
5549
		static $state = array();
5550
		static $path, $domain;
5551
		if ( ! isset( $path ) ) {
5552
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5553
			$admin_url = self::admin_url();
5554
			$bits      = wp_parse_url( $admin_url );
5555
5556
			if ( is_array( $bits ) ) {
5557
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5558
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5559
			} else {
5560
				$path = $domain = null;
5561
			}
5562
		}
5563
5564
		// Extract state from cookies and delete cookies
5565
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5566
			$yum = $_COOKIE['jetpackState'];
5567
			unset( $_COOKIE['jetpackState'] );
5568
			foreach ( $yum as $k => $v ) {
5569
				if ( strlen( $v ) ) {
5570
					$state[ $k ] = $v;
5571
				}
5572
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5573
			}
5574
		}
5575
5576
		if ( $restate ) {
5577
			foreach ( $state as $k => $v ) {
5578
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5579
			}
5580
			return;
5581
		}
5582
5583
		// Get a state variable
5584
		if ( isset( $key ) && ! isset( $value ) ) {
5585
			if ( array_key_exists( $key, $state ) ) {
5586
				return $state[ $key ];
5587
			}
5588
			return null;
5589
		}
5590
5591
		// Set a state variable
5592
		if ( isset( $key ) && isset( $value ) ) {
5593
			if ( is_array( $value ) && isset( $value[0] ) ) {
5594
				$value = $value[0];
5595
			}
5596
			$state[ $key ] = $value;
5597
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5598
		}
5599
	}
5600
5601
	public static function restate() {
5602
		self::state( null, null, true );
5603
	}
5604
5605
	public static function check_privacy( $file ) {
5606
		static $is_site_publicly_accessible = null;
5607
5608
		if ( is_null( $is_site_publicly_accessible ) ) {
5609
			$is_site_publicly_accessible = false;
5610
5611
			$rpc = new Jetpack_IXR_Client();
5612
5613
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5614
			if ( $success ) {
5615
				$response = $rpc->getResponse();
5616
				if ( $response ) {
5617
					$is_site_publicly_accessible = true;
5618
				}
5619
			}
5620
5621
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5622
		}
5623
5624
		if ( $is_site_publicly_accessible ) {
5625
			return;
5626
		}
5627
5628
		$module_slug = self::get_module_slug( $file );
5629
5630
		$privacy_checks = self::state( 'privacy_checks' );
5631
		if ( ! $privacy_checks ) {
5632
			$privacy_checks = $module_slug;
5633
		} else {
5634
			$privacy_checks .= ",$module_slug";
5635
		}
5636
5637
		self::state( 'privacy_checks', $privacy_checks );
5638
	}
5639
5640
	/**
5641
	 * Helper method for multicall XMLRPC.
5642
	 *
5643
	 * @param ...$args Args for the async_call.
5644
	 */
5645
	public static function xmlrpc_async_call( ...$args ) {
5646
		global $blog_id;
5647
		static $clients = array();
5648
5649
		$client_blog_id = is_multisite() ? $blog_id : 0;
5650
5651
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5652
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5653
			if ( function_exists( 'ignore_user_abort' ) ) {
5654
				ignore_user_abort( true );
5655
			}
5656
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5657
		}
5658
5659
		if ( ! empty( $args[0] ) ) {
5660
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5661
		} elseif ( is_multisite() ) {
5662
			foreach ( $clients as $client_blog_id => $client ) {
5663
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5664
					continue;
5665
				}
5666
5667
				$switch_success = switch_to_blog( $client_blog_id, true );
5668
				if ( ! $switch_success ) {
5669
					continue;
5670
				}
5671
5672
				flush();
5673
				$client->query();
5674
5675
				restore_current_blog();
5676
			}
5677
		} else {
5678
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5679
				flush();
5680
				$clients[0]->query();
5681
			}
5682
		}
5683
	}
5684
5685
	public static function staticize_subdomain( $url ) {
5686
5687
		// Extract hostname from URL
5688
		$host = wp_parse_url( $url, PHP_URL_HOST );
5689
5690
		// Explode hostname on '.'
5691
		$exploded_host = explode( '.', $host );
5692
5693
		// Retrieve the name and TLD
5694
		if ( count( $exploded_host ) > 1 ) {
5695
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5696
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5697
			// Rebuild domain excluding subdomains
5698
			$domain = $name . '.' . $tld;
5699
		} else {
5700
			$domain = $host;
5701
		}
5702
		// Array of Automattic domains
5703
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5704
5705
		// Return $url if not an Automattic domain
5706
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5707
			return $url;
5708
		}
5709
5710
		if ( is_ssl() ) {
5711
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5712
		}
5713
5714
		srand( crc32( basename( $url ) ) );
5715
		$static_counter = rand( 0, 2 );
5716
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5717
5718
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5719
	}
5720
5721
	/* JSON API Authorization */
5722
5723
	/**
5724
	 * Handles the login action for Authorizing the JSON API
5725
	 */
5726
	function login_form_json_api_authorization() {
5727
		$this->verify_json_api_authorization_request();
5728
5729
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5730
5731
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5732
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5733
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5734
	}
5735
5736
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5737
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5738
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5739
			return $url;
5740
		}
5741
5742
		$parsed_url = wp_parse_url( $url );
5743
		$url        = strtok( $url, '?' );
5744
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5745
		if ( ! empty( $parsed_url['query'] ) ) {
5746
			$url .= "&{$parsed_url['query']}";
5747
		}
5748
5749
		return $url;
5750
	}
5751
5752
	// Make sure the POSTed request is handled by the same action
5753
	function preserve_action_in_login_form_for_json_api_authorization() {
5754
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5755
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5756
	}
5757
5758
	// If someone logs in to approve API access, store the Access Code in usermeta
5759
	function store_json_api_authorization_token( $user_login, $user ) {
5760
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5761
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5762
		$token = wp_generate_password( 32, false );
5763
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5764
	}
5765
5766
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5767
	function allow_wpcom_public_api_domain( $domains ) {
5768
		$domains[] = 'public-api.wordpress.com';
5769
		return $domains;
5770
	}
5771
5772
	static function is_redirect_encoded( $redirect_url ) {
5773
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5774
	}
5775
5776
	// Add all wordpress.com environments to the safe redirect whitelist
5777
	function allow_wpcom_environments( $domains ) {
5778
		$domains[] = 'wordpress.com';
5779
		$domains[] = 'wpcalypso.wordpress.com';
5780
		$domains[] = 'horizon.wordpress.com';
5781
		$domains[] = 'calypso.localhost';
5782
		return $domains;
5783
	}
5784
5785
	// Add the Access Code details to the public-api.wordpress.com redirect
5786
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5787
		return add_query_arg(
5788
			urlencode_deep(
5789
				array(
5790
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5791
					'jetpack-user-id' => (int) $user->ID,
5792
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5793
				)
5794
			),
5795
			$redirect_to
5796
		);
5797
	}
5798
5799
5800
	/**
5801
	 * Verifies the request by checking the signature
5802
	 *
5803
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5804
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5805
	 *
5806
	 * @param null|array $environment
5807
	 */
5808
	function verify_json_api_authorization_request( $environment = null ) {
5809
		$environment = is_null( $environment )
5810
			? $_REQUEST
5811
			: $environment;
5812
5813
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
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...
5814
		$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...
5815
		if ( ! $token || empty( $token->secret ) ) {
5816
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5817
		}
5818
5819
		$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' );
5820
5821
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5822
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5823
			/**
5824
			 * Jetpack authorisation request Error.
5825
			 *
5826
			 * @since 7.5.0
5827
			 */
5828
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5829
			$die_error = sprintf(
5830
				/* translators: %s is a URL */
5831
				__( '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' ),
5832
				'https://jetpack.com/support/double-encoding/'
5833
			);
5834
		}
5835
5836
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5837
5838
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5839
			$signature = $jetpack_signature->sign_request(
5840
				$environment['token'],
5841
				$environment['timestamp'],
5842
				$environment['nonce'],
5843
				'',
5844
				'GET',
5845
				$environment['jetpack_json_api_original_query'],
5846
				null,
5847
				true
5848
			);
5849
		} else {
5850
			$signature = $jetpack_signature->sign_current_request(
5851
				array(
5852
					'body'   => null,
5853
					'method' => 'GET',
5854
				)
5855
			);
5856
		}
5857
5858
		if ( ! $signature ) {
5859
			wp_die( $die_error );
5860
		} elseif ( is_wp_error( $signature ) ) {
5861
			wp_die( $die_error );
5862
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5863
			if ( is_ssl() ) {
5864
				// 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
5865
				$signature = $jetpack_signature->sign_current_request(
5866
					array(
5867
						'scheme' => 'http',
5868
						'body'   => null,
5869
						'method' => 'GET',
5870
					)
5871
				);
5872
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5873
					wp_die( $die_error );
5874
				}
5875
			} else {
5876
				wp_die( $die_error );
5877
			}
5878
		}
5879
5880
		$timestamp = (int) $environment['timestamp'];
5881
		$nonce     = stripslashes( (string) $environment['nonce'] );
5882
5883
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5884
			// De-nonce the nonce, at least for 5 minutes.
5885
			// 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)
5886
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5887
			if ( $old_nonce_time < time() - 300 ) {
5888
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5889
			}
5890
		}
5891
5892
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5893
		$data_filters = array(
5894
			'state'        => 'opaque',
5895
			'client_id'    => 'int',
5896
			'client_title' => 'string',
5897
			'client_image' => 'url',
5898
		);
5899
5900
		foreach ( $data_filters as $key => $sanitation ) {
5901
			if ( ! isset( $data->$key ) ) {
5902
				wp_die( $die_error );
5903
			}
5904
5905
			switch ( $sanitation ) {
5906
				case 'int':
5907
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5908
					break;
5909
				case 'opaque':
5910
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5911
					break;
5912
				case 'string':
5913
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5914
					break;
5915
				case 'url':
5916
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5917
					break;
5918
			}
5919
		}
5920
5921
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5922
			wp_die( $die_error );
5923
		}
5924
	}
5925
5926
	function login_message_json_api_authorization( $message ) {
5927
		return '<p class="message">' . sprintf(
5928
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5929
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5930
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5931
	}
5932
5933
	/**
5934
	 * Get $content_width, but with a <s>twist</s> filter.
5935
	 */
5936
	public static function get_content_width() {
5937
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5938
			? $GLOBALS['content_width']
5939
			: false;
5940
		/**
5941
		 * Filter the Content Width value.
5942
		 *
5943
		 * @since 2.2.3
5944
		 *
5945
		 * @param string $content_width Content Width value.
5946
		 */
5947
		return apply_filters( 'jetpack_content_width', $content_width );
5948
	}
5949
5950
	/**
5951
	 * Pings the WordPress.com Mirror Site for the specified options.
5952
	 *
5953
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5954
	 *
5955
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5956
	 */
5957
	public function get_cloud_site_options( $option_names ) {
5958
		$option_names = array_filter( (array) $option_names, 'is_string' );
5959
5960
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
5961
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5962
		if ( $xml->isError() ) {
5963
			return array(
5964
				'error_code' => $xml->getErrorCode(),
5965
				'error_msg'  => $xml->getErrorMessage(),
5966
			);
5967
		}
5968
		$cloud_site_options = $xml->getResponse();
5969
5970
		return $cloud_site_options;
5971
	}
5972
5973
	/**
5974
	 * Checks if the site is currently in an identity crisis.
5975
	 *
5976
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5977
	 */
5978
	public static function check_identity_crisis() {
5979
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5980
			return false;
5981
		}
5982
5983
		return Jetpack_Options::get_option( 'sync_error_idc' );
5984
	}
5985
5986
	/**
5987
	 * Checks whether the home and siteurl specifically are whitelisted
5988
	 * Written so that we don't have re-check $key and $value params every time
5989
	 * we want to check if this site is whitelisted, for example in footer.php
5990
	 *
5991
	 * @since  3.8.0
5992
	 * @return bool True = already whitelisted False = not whitelisted
5993
	 */
5994
	public static function is_staging_site() {
5995
		$is_staging = false;
5996
5997
		$known_staging = array(
5998
			'urls'      => array(
5999
				'#\.staging\.wpengine\.com$#i', // WP Engine
6000
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6001
				'#\.stage\.site$#i',            // DreamPress
6002
			),
6003
			'constants' => array(
6004
				'IS_WPE_SNAPSHOT',      // WP Engine
6005
				'KINSTA_DEV_ENV',       // Kinsta.com
6006
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6007
				'JETPACK_STAGING_MODE', // Generic
6008
			),
6009
		);
6010
		/**
6011
		 * Filters the flags of known staging sites.
6012
		 *
6013
		 * @since 3.9.0
6014
		 *
6015
		 * @param array $known_staging {
6016
		 *     An array of arrays that each are used to check if the current site is staging.
6017
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6018
		 *     @type array $constants PHP constants of known staging/developement environments.
6019
		 *  }
6020
		 */
6021
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6022
6023
		if ( isset( $known_staging['urls'] ) ) {
6024
			foreach ( $known_staging['urls'] as $url ) {
6025
				if ( preg_match( $url, site_url() ) ) {
6026
					$is_staging = true;
6027
					break;
6028
				}
6029
			}
6030
		}
6031
6032
		if ( isset( $known_staging['constants'] ) ) {
6033
			foreach ( $known_staging['constants'] as $constant ) {
6034
				if ( defined( $constant ) && constant( $constant ) ) {
6035
					$is_staging = true;
6036
				}
6037
			}
6038
		}
6039
6040
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6041
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6042
			$is_staging = true;
6043
		}
6044
6045
		/**
6046
		 * Filters is_staging_site check.
6047
		 *
6048
		 * @since 3.9.0
6049
		 *
6050
		 * @param bool $is_staging If the current site is a staging site.
6051
		 */
6052
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6053
	}
6054
6055
	/**
6056
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6057
	 *
6058
	 * @since 4.4.0
6059
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6060
	 *
6061
	 * @return bool
6062
	 */
6063
	public static function validate_sync_error_idc_option() {
6064
		$is_valid = false;
6065
6066
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6067
		if ( false === $idc_allowed ) {
6068
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6069
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6070
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6071
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6072
				$transient_duration = HOUR_IN_SECONDS;
6073
			} else {
6074
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6075
				$idc_allowed        = '1';
6076
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6077
			}
6078
6079
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6080
		}
6081
6082
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6083
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6084
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6085
			$local_options = self::get_sync_error_idc_option();
6086
			// Ensure all values are set.
6087
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6088
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6089
					$is_valid = true;
6090
				}
6091
			}
6092
6093
		}
6094
6095
		/**
6096
		 * Filters whether the sync_error_idc option is valid.
6097
		 *
6098
		 * @since 4.4.0
6099
		 *
6100
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6101
		 */
6102
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6103
6104
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6105
			// Since the option exists, and did not validate, delete it
6106
			Jetpack_Options::delete_option( 'sync_error_idc' );
6107
		}
6108
6109
		return $is_valid;
6110
	}
6111
6112
	/**
6113
	 * Normalizes a url by doing three things:
6114
	 *  - Strips protocol
6115
	 *  - Strips www
6116
	 *  - Adds a trailing slash
6117
	 *
6118
	 * @since 4.4.0
6119
	 * @param string $url
6120
	 * @return WP_Error|string
6121
	 */
6122
	public static function normalize_url_protocol_agnostic( $url ) {
6123
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6124
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6125
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
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...
6126
		}
6127
6128
		// Strip www and protocols
6129
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6130
		return $url;
6131
	}
6132
6133
	/**
6134
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6135
	 *
6136
	 * @since 4.4.0
6137
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6138
	 *
6139
	 * @param array $response
6140
	 * @return array Array of the local urls, wpcom urls, and error code
6141
	 */
6142
	public static function get_sync_error_idc_option( $response = array() ) {
6143
		// Since the local options will hit the database directly, store the values
6144
		// in a transient to allow for autoloading and caching on subsequent views.
6145
		$local_options = get_transient( 'jetpack_idc_local' );
6146
		if ( false === $local_options ) {
6147
			$local_options = array(
6148
				'home'    => Functions::home_url(),
6149
				'siteurl' => Functions::site_url(),
6150
			);
6151
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6152
		}
6153
6154
		$options = array_merge( $local_options, $response );
6155
6156
		$returned_values = array();
6157
		foreach ( $options as $key => $option ) {
6158
			if ( 'error_code' === $key ) {
6159
				$returned_values[ $key ] = $option;
6160
				continue;
6161
			}
6162
6163
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6164
				continue;
6165
			}
6166
6167
			$returned_values[ $key ] = $normalized_url;
6168
		}
6169
6170
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6171
6172
		return $returned_values;
6173
	}
6174
6175
	/**
6176
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6177
	 * If set to true, the site will be put into staging mode.
6178
	 *
6179
	 * @since 4.3.2
6180
	 * @return bool
6181
	 */
6182
	public static function sync_idc_optin() {
6183
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6184
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6185
		} else {
6186
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6187
		}
6188
6189
		/**
6190
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6191
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6192
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6193
		 *
6194
		 * @since 4.3.2
6195
		 *
6196
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6197
		 */
6198
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6199
	}
6200
6201
	/**
6202
	 * Maybe Use a .min.css stylesheet, maybe not.
6203
	 *
6204
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6205
	 */
6206
	public static function maybe_min_asset( $url, $path, $plugin ) {
6207
		// Short out on things trying to find actual paths.
6208
		if ( ! $path || empty( $plugin ) ) {
6209
			return $url;
6210
		}
6211
6212
		$path = ltrim( $path, '/' );
6213
6214
		// Strip out the abspath.
6215
		$base = dirname( plugin_basename( $plugin ) );
6216
6217
		// Short out on non-Jetpack assets.
6218
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6219
			return $url;
6220
		}
6221
6222
		// File name parsing.
6223
		$file              = "{$base}/{$path}";
6224
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6225
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6226
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6227
		$extension         = array_shift( $file_name_parts_r );
6228
6229
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6230
			// Already pointing at the minified version.
6231
			if ( 'min' === $file_name_parts_r[0] ) {
6232
				return $url;
6233
			}
6234
6235
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6236
			if ( file_exists( $min_full_path ) ) {
6237
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6238
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6239
				if ( 'css' === $extension ) {
6240
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6241
					self::$min_assets[ $key ] = $path;
6242
				}
6243
			}
6244
		}
6245
6246
		return $url;
6247
	}
6248
6249
	/**
6250
	 * If the asset is minified, let's flag .min as the suffix.
6251
	 *
6252
	 * Attached to `style_loader_src` filter.
6253
	 *
6254
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
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...
6255
	 * @param string $handle The registered handle of the script in question.
6256
	 * @param string $href The url of the asset in question.
0 ignored issues
show
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...
6257
	 */
6258
	public static function set_suffix_on_min( $src, $handle ) {
6259
		if ( false === strpos( $src, '.min.css' ) ) {
6260
			return $src;
6261
		}
6262
6263
		if ( ! empty( self::$min_assets ) ) {
6264
			foreach ( self::$min_assets as $file => $path ) {
6265
				if ( false !== strpos( $src, $file ) ) {
6266
					wp_style_add_data( $handle, 'suffix', '.min' );
6267
					return $src;
6268
				}
6269
			}
6270
		}
6271
6272
		return $src;
6273
	}
6274
6275
	/**
6276
	 * Maybe inlines a stylesheet.
6277
	 *
6278
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6279
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6280
	 *
6281
	 * Attached to `style_loader_tag` filter.
6282
	 *
6283
	 * @param string $tag The tag that would link to the external asset.
6284
	 * @param string $handle The registered handle of the script in question.
6285
	 *
6286
	 * @return string
6287
	 */
6288
	public static function maybe_inline_style( $tag, $handle ) {
6289
		global $wp_styles;
6290
		$item = $wp_styles->registered[ $handle ];
6291
6292
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6293
			return $tag;
6294
		}
6295
6296
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6297
			$href = $matches[1];
6298
			// Strip off query string
6299
			if ( $pos = strpos( $href, '?' ) ) {
6300
				$href = substr( $href, 0, $pos );
6301
			}
6302
			// Strip off fragment
6303
			if ( $pos = strpos( $href, '#' ) ) {
6304
				$href = substr( $href, 0, $pos );
6305
			}
6306
		} else {
6307
			return $tag;
6308
		}
6309
6310
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6311
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6312
			return $tag;
6313
		}
6314
6315
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6316
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6317
			// And this isn't the pass that actually deals with the RTL version...
6318
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6319
				// Short out, as the RTL version will deal with it in a moment.
6320
				return $tag;
6321
			}
6322
		}
6323
6324
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6325
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6326
		if ( $css ) {
6327
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6328
			if ( empty( $item->extra['after'] ) ) {
6329
				wp_add_inline_style( $handle, $css );
6330
			} else {
6331
				array_unshift( $item->extra['after'], $css );
6332
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6333
			}
6334
		}
6335
6336
		return $tag;
6337
	}
6338
6339
	/**
6340
	 * Loads a view file from the views
6341
	 *
6342
	 * Data passed in with the $data parameter will be available in the
6343
	 * template file as $data['value']
6344
	 *
6345
	 * @param string $template - Template file to load
6346
	 * @param array  $data - Any data to pass along to the template
6347
	 * @return boolean - If template file was found
6348
	 **/
6349
	public function load_view( $template, $data = array() ) {
6350
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6351
6352
		if ( file_exists( $views_dir . $template ) ) {
6353
			require_once $views_dir . $template;
6354
			return true;
6355
		}
6356
6357
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6358
		return false;
6359
	}
6360
6361
	/**
6362
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6363
	 */
6364
	public function deprecated_hooks() {
6365
		global $wp_filter;
6366
6367
		/*
6368
		 * Format:
6369
		 * deprecated_filter_name => replacement_name
6370
		 *
6371
		 * If there is no replacement, use null for replacement_name
6372
		 */
6373
		$deprecated_list = array(
6374
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6375
			'wpl_sharing_2014_1'                           => null,
6376
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6377
			'jetpack_identity_crisis_options_to_check'     => null,
6378
			'update_option_jetpack_single_user_site'       => null,
6379
			'audio_player_default_colors'                  => null,
6380
			'add_option_jetpack_featured_images_enabled'   => null,
6381
			'add_option_jetpack_update_details'            => null,
6382
			'add_option_jetpack_updates'                   => null,
6383
			'add_option_jetpack_network_name'              => null,
6384
			'add_option_jetpack_network_allow_new_registrations' => null,
6385
			'add_option_jetpack_network_add_new_users'     => null,
6386
			'add_option_jetpack_network_site_upload_space' => null,
6387
			'add_option_jetpack_network_upload_file_types' => null,
6388
			'add_option_jetpack_network_enable_administration_menus' => null,
6389
			'add_option_jetpack_is_multi_site'             => null,
6390
			'add_option_jetpack_is_main_network'           => null,
6391
			'add_option_jetpack_main_network_site'         => null,
6392
			'jetpack_sync_all_registered_options'          => null,
6393
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6394
			'jetpack_is_post_mailable'                     => null,
6395
			'jetpack_seo_site_host'                        => null,
6396
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6397
			'jetpack_holiday_snow_option_name'             => null,
6398
			'jetpack_holiday_chance_of_snow'               => null,
6399
			'jetpack_holiday_snow_js_url'                  => null,
6400
			'jetpack_is_holiday_snow_season'               => null,
6401
			'jetpack_holiday_snow_option_updated'          => null,
6402
			'jetpack_holiday_snowing'                      => null,
6403
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6404
			'jetpack_cache_plans'                          => null,
6405
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6406
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6407
			'jetpack_enable_site_verification'             => null,
6408
			'can_display_jetpack_manage_notice'            => null,
6409
			// Removed in Jetpack 7.3.0
6410
			'atd_load_scripts'                             => null,
6411
			'atd_http_post_timeout'                        => null,
6412
			'atd_http_post_error'                          => null,
6413
			'atd_service_domain'                           => null,
6414
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6415
			// Removed in Jetpack 7.9.0
6416
			'jetpack_pwa_manifest'                         => null,
6417
			'jetpack_pwa_background_color'                 => null,
6418
		);
6419
6420
		// This is a silly loop depth. Better way?
6421
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6422
			if ( has_action( $hook ) ) {
6423
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6424
					foreach ( $values as $hooked ) {
6425
						if ( is_callable( $hooked['function'] ) ) {
6426
							$function_name = 'an anonymous function';
6427
						} else {
6428
							$function_name = $hooked['function'];
6429
						}
6430
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6431
					}
6432
				}
6433
			}
6434
		}
6435
	}
6436
6437
	/**
6438
	 * Converts any url in a stylesheet, to the correct absolute url.
6439
	 *
6440
	 * Considerations:
6441
	 *  - Normal, relative URLs     `feh.png`
6442
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6443
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6444
	 *  - Absolute URLs             `http://domain.com/feh.png`
6445
	 *  - Domain root relative URLs `/feh.png`
6446
	 *
6447
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6448
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6449
	 *
6450
	 * @return mixed|string
6451
	 */
6452
	public static function absolutize_css_urls( $css, $css_file_url ) {
6453
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6454
		$css_dir = dirname( $css_file_url );
6455
		$p       = wp_parse_url( $css_dir );
6456
		$domain  = sprintf(
6457
			'%1$s//%2$s%3$s%4$s',
6458
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6459
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6460
			$p['host'],
6461
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6462
		);
6463
6464
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6465
			$find = $replace = array();
6466
			foreach ( $matches as $match ) {
6467
				$url = trim( $match['path'], "'\" \t" );
6468
6469
				// If this is a data url, we don't want to mess with it.
6470
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6471
					continue;
6472
				}
6473
6474
				// If this is an absolute or protocol-agnostic url,
6475
				// we don't want to mess with it.
6476
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6477
					continue;
6478
				}
6479
6480
				switch ( substr( $url, 0, 1 ) ) {
6481
					case '/':
6482
						$absolute = $domain . $url;
6483
						break;
6484
					default:
6485
						$absolute = $css_dir . '/' . $url;
6486
				}
6487
6488
				$find[]    = $match[0];
6489
				$replace[] = sprintf( 'url("%s")', $absolute );
6490
			}
6491
			$css = str_replace( $find, $replace, $css );
6492
		}
6493
6494
		return $css;
6495
	}
6496
6497
	/**
6498
	 * This methods removes all of the registered css files on the front end
6499
	 * from Jetpack in favor of using a single file. In effect "imploding"
6500
	 * all the files into one file.
6501
	 *
6502
	 * Pros:
6503
	 * - Uses only ONE css asset connection instead of 15
6504
	 * - Saves a minimum of 56k
6505
	 * - Reduces server load
6506
	 * - Reduces time to first painted byte
6507
	 *
6508
	 * Cons:
6509
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6510
	 *      should not cause any issues with themes.
6511
	 * - Plugins/themes dequeuing styles no longer do anything. See
6512
	 *      jetpack_implode_frontend_css filter for a workaround
6513
	 *
6514
	 * For some situations developers may wish to disable css imploding and
6515
	 * instead operate in legacy mode where each file loads seperately and
6516
	 * can be edited individually or dequeued. This can be accomplished with
6517
	 * the following line:
6518
	 *
6519
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6520
	 *
6521
	 * @since 3.2
6522
	 **/
6523
	public function implode_frontend_css( $travis_test = false ) {
6524
		$do_implode = true;
6525
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6526
			$do_implode = false;
6527
		}
6528
6529
		// Do not implode CSS when the page loads via the AMP plugin.
6530
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6531
			$do_implode = false;
6532
		}
6533
6534
		/**
6535
		 * Allow CSS to be concatenated into a single jetpack.css file.
6536
		 *
6537
		 * @since 3.2.0
6538
		 *
6539
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6540
		 */
6541
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6542
6543
		// Do not use the imploded file when default behavior was altered through the filter
6544
		if ( ! $do_implode ) {
6545
			return;
6546
		}
6547
6548
		// We do not want to use the imploded file in dev mode, or if not connected
6549
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6550
			if ( ! $travis_test ) {
6551
				return;
6552
			}
6553
		}
6554
6555
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6556
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6557
			return;
6558
		}
6559
6560
		/*
6561
		 * Now we assume Jetpack is connected and able to serve the single
6562
		 * file.
6563
		 *
6564
		 * In the future there will be a check here to serve the file locally
6565
		 * or potentially from the Jetpack CDN
6566
		 *
6567
		 * For now:
6568
		 * - Enqueue a single imploded css file
6569
		 * - Zero out the style_loader_tag for the bundled ones
6570
		 * - Be happy, drink scotch
6571
		 */
6572
6573
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6574
6575
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6576
6577
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6578
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6579
	}
6580
6581
	function concat_remove_style_loader_tag( $tag, $handle ) {
6582
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6583
			$tag = '';
6584
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6585
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6586
			}
6587
		}
6588
6589
		return $tag;
6590
	}
6591
6592
	/**
6593
	 * Add an async attribute to scripts that can be loaded asynchronously.
6594
	 * https://www.w3schools.com/tags/att_script_async.asp
6595
	 *
6596
	 * @since 7.7.0
6597
	 *
6598
	 * @param string $tag    The <script> tag for the enqueued script.
6599
	 * @param string $handle The script's registered handle.
6600
	 * @param string $src    The script's source URL.
6601
	 */
6602
	public function script_add_async( $tag, $handle, $src ) {
6603
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6604
			return preg_replace( '/^<script /i', '<script async ', $tag );
6605
		}
6606
6607
		return $tag;
6608
	}
6609
6610
	/*
6611
	 * Check the heartbeat data
6612
	 *
6613
	 * Organizes the heartbeat data by severity.  For example, if the site
6614
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6615
	 *
6616
	 * Data will be added to "caution" array, if it either:
6617
	 *  - Out of date Jetpack version
6618
	 *  - Out of date WP version
6619
	 *  - Out of date PHP version
6620
	 *
6621
	 * $return array $filtered_data
6622
	 */
6623
	public static function jetpack_check_heartbeat_data() {
6624
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6625
6626
		$good    = array();
6627
		$caution = array();
6628
		$bad     = array();
6629
6630
		foreach ( $raw_data as $stat => $value ) {
6631
6632
			// Check jetpack version
6633
			if ( 'version' == $stat ) {
6634
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6635
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6636
					continue;
6637
				}
6638
			}
6639
6640
			// Check WP version
6641
			if ( 'wp-version' == $stat ) {
6642
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6643
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6644
					continue;
6645
				}
6646
			}
6647
6648
			// Check PHP version
6649
			if ( 'php-version' == $stat ) {
6650
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6651
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6652
					continue;
6653
				}
6654
			}
6655
6656
			// Check ID crisis
6657
			if ( 'identitycrisis' == $stat ) {
6658
				if ( 'yes' == $value ) {
6659
					$bad[ $stat ] = $value;
6660
					continue;
6661
				}
6662
			}
6663
6664
			// The rest are good :)
6665
			$good[ $stat ] = $value;
6666
		}
6667
6668
		$filtered_data = array(
6669
			'good'    => $good,
6670
			'caution' => $caution,
6671
			'bad'     => $bad,
6672
		);
6673
6674
		return $filtered_data;
6675
	}
6676
6677
6678
	/*
6679
	 * This method is used to organize all options that can be reset
6680
	 * without disconnecting Jetpack.
6681
	 *
6682
	 * It is used in class.jetpack-cli.php to reset options
6683
	 *
6684
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6685
	 *
6686
	 * @return array of options to delete.
6687
	 */
6688
	public static function get_jetpack_options_for_reset() {
6689
		return Jetpack_Options::get_options_for_reset();
6690
	}
6691
6692
	/*
6693
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6694
	 * so we can bring them directly to their site in calypso.
6695
	 *
6696
	 * @param string | url
6697
	 * @return string | url without the guff
6698
	 */
6699
	public static function build_raw_urls( $url ) {
6700
		$strip_http = '/.*?:\/\//i';
6701
		$url        = preg_replace( $strip_http, '', $url );
6702
		$url        = str_replace( '/', '::', $url );
6703
		return $url;
6704
	}
6705
6706
	/**
6707
	 * Stores and prints out domains to prefetch for page speed optimization.
6708
	 *
6709
	 * @param mixed $new_urls
6710
	 */
6711
	public static function dns_prefetch( $new_urls = null ) {
6712
		static $prefetch_urls = array();
6713
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6714
			echo "\r\n";
6715
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6716
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6717
			}
6718
		} elseif ( ! empty( $new_urls ) ) {
6719
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6720
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6721
			}
6722
			foreach ( (array) $new_urls as $this_new_url ) {
6723
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6724
			}
6725
			$prefetch_urls = array_unique( $prefetch_urls );
6726
		}
6727
	}
6728
6729
	public function wp_dashboard_setup() {
6730
		if ( self::is_active() ) {
6731
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6732
		}
6733
6734
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6735
			$jetpack_logo = new Jetpack_Logo();
6736
			$widget_title = sprintf(
6737
				wp_kses(
6738
					/* translators: Placeholder is a Jetpack logo. */
6739
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6740
					array( 'span' => array() )
6741
				),
6742
				$jetpack_logo->get_jp_emblem( true )
6743
			);
6744
6745
			wp_add_dashboard_widget(
6746
				'jetpack_summary_widget',
6747
				$widget_title,
6748
				array( __CLASS__, 'dashboard_widget' )
6749
			);
6750
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6751
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6752
6753
			// If we're inactive and not in development mode, sort our box to the top.
6754
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6755
				global $wp_meta_boxes;
6756
6757
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6758
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6759
6760
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6761
			}
6762
		}
6763
	}
6764
6765
	/**
6766
	 * @param mixed $result Value for the user's option
0 ignored issues
show
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...
6767
	 * @return mixed
6768
	 */
6769
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6770
		if ( ! is_array( $sorted ) ) {
6771
			return $sorted;
6772
		}
6773
6774
		foreach ( $sorted as $box_context => $ids ) {
6775
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6776
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6777
				continue;
6778
			}
6779
6780
			$ids_array = explode( ',', $ids );
6781
			$key       = array_search( 'dashboard_stats', $ids_array );
6782
6783
			if ( false !== $key ) {
6784
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6785
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6786
				$sorted[ $box_context ] = implode( ',', $ids_array );
6787
				// We've found it, stop searching, and just return.
6788
				break;
6789
			}
6790
		}
6791
6792
		return $sorted;
6793
	}
6794
6795
	public static function dashboard_widget() {
6796
		/**
6797
		 * Fires when the dashboard is loaded.
6798
		 *
6799
		 * @since 3.4.0
6800
		 */
6801
		do_action( 'jetpack_dashboard_widget' );
6802
	}
6803
6804
	public static function dashboard_widget_footer() {
6805
		?>
6806
		<footer>
6807
6808
		<div class="protect">
6809
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6810
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6811
				<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>
6812
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6813
				<a href="
6814
				<?php
6815
				echo esc_url(
6816
					wp_nonce_url(
6817
						self::admin_url(
6818
							array(
6819
								'action' => 'activate',
6820
								'module' => 'protect',
6821
							)
6822
						),
6823
						'jetpack_activate-protect'
6824
					)
6825
				);
6826
				?>
6827
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6828
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6829
				</a>
6830
			<?php else : ?>
6831
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6832
			<?php endif; ?>
6833
		</div>
6834
6835
		<div class="akismet">
6836
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6837
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6838
				<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>
6839
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6840
				<a href="
6841
				<?php
6842
				echo esc_url(
6843
					wp_nonce_url(
6844
						add_query_arg(
6845
							array(
6846
								'action' => 'activate',
6847
								'plugin' => 'akismet/akismet.php',
6848
							),
6849
							admin_url( 'plugins.php' )
6850
						),
6851
						'activate-plugin_akismet/akismet.php'
6852
					)
6853
				);
6854
				?>
6855
							" class="button button-jetpack">
6856
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6857
				</a>
6858
			<?php else : ?>
6859
				<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>
6860
			<?php endif; ?>
6861
		</div>
6862
6863
		</footer>
6864
		<?php
6865
	}
6866
6867
	/*
6868
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6869
	 */
6870
	function jetpack_icon_user_connected( $columns ) {
6871
		$columns['user_jetpack'] = '';
6872
		return $columns;
6873
	}
6874
6875
	/*
6876
	 * Show Jetpack icon if the user is linked.
6877
	 */
6878
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6879
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6880
			$jetpack_logo = new Jetpack_Logo();
6881
			$emblem_html  = sprintf(
6882
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6883
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6884
				$jetpack_logo->get_jp_emblem()
6885
			);
6886
			return $emblem_html;
6887
		}
6888
6889
		return $val;
6890
	}
6891
6892
	/*
6893
	 * Style the Jetpack user column
6894
	 */
6895
	function jetpack_user_col_style() {
6896
		global $current_screen;
6897
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6898
			?>
6899
			<style>
6900
				.fixed .column-user_jetpack {
6901
					width: 21px;
6902
				}
6903
				.jp-emblem-user-admin svg {
6904
					width: 20px;
6905
					height: 20px;
6906
				}
6907
				.jp-emblem-user-admin path {
6908
					fill: #00BE28;
6909
				}
6910
			</style>
6911
			<?php
6912
		}
6913
	}
6914
6915
	/**
6916
	 * Checks if Akismet is active and working.
6917
	 *
6918
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6919
	 * that implied usage of methods present since more recent version.
6920
	 * See https://github.com/Automattic/jetpack/pull/9585
6921
	 *
6922
	 * @since  5.1.0
6923
	 *
6924
	 * @return bool True = Akismet available. False = Aksimet not available.
6925
	 */
6926
	public static function is_akismet_active() {
6927
		static $status = null;
6928
6929
		if ( ! is_null( $status ) ) {
6930
			return $status;
6931
		}
6932
6933
		// Check if a modern version of Akismet is active.
6934
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6935
			$status = false;
6936
			return $status;
6937
		}
6938
6939
		// Make sure there is a key known to Akismet at all before verifying key.
6940
		$akismet_key = Akismet::get_api_key();
6941
		if ( ! $akismet_key ) {
6942
			$status = false;
6943
			return $status;
6944
		}
6945
6946
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6947
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6948
6949
		// 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.
6950
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6951
		// We cache the result of the Akismet key verification for ten minutes.
6952
		if ( ! $akismet_key_state || $recheck ) {
6953
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6954
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6955
		}
6956
6957
		$status = 'valid' === $akismet_key_state;
6958
6959
		return $status;
6960
	}
6961
6962
	/**
6963
	 * @deprecated
6964
	 *
6965
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6966
	 */
6967
	public static function is_function_in_backtrace() {
6968
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6969
	}
6970
6971
	/**
6972
	 * Given a minified path, and a non-minified path, will return
6973
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6974
	 *
6975
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6976
	 * root Jetpack directory.
6977
	 *
6978
	 * @since 5.6.0
6979
	 *
6980
	 * @param string $min_path
6981
	 * @param string $non_min_path
6982
	 * @return string The URL to the file
6983
	 */
6984
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6985
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6986
	}
6987
6988
	/**
6989
	 * Checks for whether Jetpack Backup & Scan is enabled.
6990
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6991
	 *
6992
	 * @return bool|int|mixed
6993
	 */
6994
	public static function is_rewind_enabled() {
6995
		if ( ! self::is_active() ) {
6996
			return false;
6997
		}
6998
6999
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7000
		if ( false === $rewind_enabled ) {
7001
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7002
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7003
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7004
				&& ! empty( $rewind_data['state'] )
7005
				&& 'active' === $rewind_data['state'] )
7006
				? 1
7007
				: 0;
7008
7009
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7010
		}
7011
		return $rewind_enabled;
7012
	}
7013
7014
	/**
7015
	 * Return Calypso environment value; used for developing Jetpack and pairing
7016
	 * it with different Calypso enrionments, such as localhost.
7017
	 *
7018
	 * @since 7.4.0
7019
	 *
7020
	 * @return string Calypso environment
7021
	 */
7022
	public static function get_calypso_env() {
7023
		if ( isset( $_GET['calypso_env'] ) ) {
7024
			return sanitize_key( $_GET['calypso_env'] );
7025
		}
7026
7027
		if ( getenv( 'CALYPSO_ENV' ) ) {
7028
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7029
		}
7030
7031
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7032
			return sanitize_key( CALYPSO_ENV );
7033
		}
7034
7035
		return '';
7036
	}
7037
7038
	/**
7039
	 * Checks whether or not TOS has been agreed upon.
7040
	 * Will return true if a user has clicked to register, or is already connected.
7041
	 */
7042
	public static function jetpack_tos_agreed() {
7043
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7044
7045
		$terms_of_service = new Terms_Of_Service();
7046
		return $terms_of_service->has_agreed();
7047
7048
	}
7049
7050
	/**
7051
	 * Handles activating default modules as well general cleanup for the new connection.
7052
	 *
7053
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7054
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7055
	 * @param boolean $send_state_messages          Whether to send state messages.
7056
	 * @return void
7057
	 */
7058
	public static function handle_post_authorization_actions(
7059
		$activate_sso = false,
7060
		$redirect_on_activation_error = false,
7061
		$send_state_messages = true
7062
	) {
7063
		$other_modules = $activate_sso
7064
			? array( 'sso' )
7065
			: array();
7066
7067
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7068
			self::delete_active_modules();
7069
7070
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
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...
7071
		} else {
7072
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7073
		}
7074
7075
		// Since this is a fresh connection, be sure to clear out IDC options
7076
		Jetpack_IDC::clear_all_idc_options();
7077
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7078
7079
		// Start nonce cleaner
7080
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7081
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7082
7083
		if ( $send_state_messages ) {
7084
			self::state( 'message', 'authorized' );
7085
		}
7086
	}
7087
7088
	/**
7089
	 * Returns a boolean for whether backups UI should be displayed or not.
7090
	 *
7091
	 * @return bool Should backups UI be displayed?
7092
	 */
7093
	public static function show_backups_ui() {
7094
		/**
7095
		 * Whether UI for backups should be displayed.
7096
		 *
7097
		 * @since 6.5.0
7098
		 *
7099
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7100
		 */
7101
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7102
	}
7103
7104
	/*
7105
	 * Deprecated manage functions
7106
	 */
7107
	function prepare_manage_jetpack_notice() {
7108
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7109
	}
7110
	function manage_activate_screen() {
7111
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7112
	}
7113
	function admin_jetpack_manage_notice() {
7114
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7115
	}
7116
	function opt_out_jetpack_manage_url() {
7117
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7118
	}
7119
	function opt_in_jetpack_manage_url() {
7120
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7121
	}
7122
	function opt_in_jetpack_manage_notice() {
7123
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7124
	}
7125
	function can_display_jetpack_manage_notice() {
7126
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7127
	}
7128
7129
	/**
7130
	 * Clean leftoveruser meta.
7131
	 *
7132
	 * Delete Jetpack-related user meta when it is no longer needed.
7133
	 *
7134
	 * @since 7.3.0
7135
	 *
7136
	 * @param int $user_id User ID being updated.
7137
	 */
7138
	public static function user_meta_cleanup( $user_id ) {
7139
		$meta_keys = array(
7140
			// AtD removed from Jetpack 7.3
7141
			'AtD_options',
7142
			'AtD_check_when',
7143
			'AtD_guess_lang',
7144
			'AtD_ignored_phrases',
7145
		);
7146
7147
		foreach ( $meta_keys as $meta_key ) {
7148
			if ( get_user_meta( $user_id, $meta_key ) ) {
7149
				delete_user_meta( $user_id, $meta_key );
7150
			}
7151
		}
7152
	}
7153
7154
	/**
7155
	 * Checks if a Jetpack site is both active and not in development.
7156
	 *
7157
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7158
	 *
7159
	 * @return bool True if Jetpack is active and not in development.
7160
	 */
7161
	public static function is_active_and_not_development_mode() {
7162
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7163
			return false;
7164
		}
7165
		return true;
7166
	}
7167
}
7168