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