Completed
Push — add/setup-wizard-url-states ( 52201a...042f0b )
by
unknown
08:12
created

class.jetpack.php (81 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
use Automattic\Jetpack\Redirect;
20
21
/*
22
Options:
23
jetpack_options (array)
24
	An array of options.
25
	@see Jetpack_Options::get_option_names()
26
27
jetpack_register (string)
28
	Temporary verification secrets.
29
30
jetpack_activated (int)
31
	1: the plugin was activated normally
32
	2: the plugin was activated on this site because of a network-wide activation
33
	3: the plugin was auto-installed
34
	4: the plugin was manually disconnected (but is still installed)
35
36
jetpack_active_modules (array)
37
	Array of active module slugs.
38
39
jetpack_do_activate (bool)
40
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
41
*/
42
43
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
44
45
class Jetpack {
46
	public $xmlrpc_server = null;
47
48
	private $rest_authentication_status = null;
49
50
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
51
52
	/**
53
	 * @var array The handles of styles that are concatenated into jetpack.css.
54
	 *
55
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
56
	 */
57
	public $concatenated_style_handles = array(
58
		'jetpack-carousel',
59
		'grunion.css',
60
		'the-neverending-homepage',
61
		'jetpack_likes',
62
		'jetpack_related-posts',
63
		'sharedaddy',
64
		'jetpack-slideshow',
65
		'presentations',
66
		'quiz',
67
		'jetpack-subscriptions',
68
		'jetpack-responsive-videos-style',
69
		'jetpack-social-menu',
70
		'tiled-gallery',
71
		'jetpack_display_posts_widget',
72
		'gravatar-profile-widget',
73
		'goodreads-widget',
74
		'jetpack_social_media_icons_widget',
75
		'jetpack-top-posts-widget',
76
		'jetpack_image_widget',
77
		'jetpack-my-community-widget',
78
		'jetpack-authors-widget',
79
		'wordads',
80
		'eu-cookie-law-style',
81
		'flickr-widget-style',
82
		'jetpack-search-widget',
83
		'jetpack-simple-payments-widget-style',
84
		'jetpack-widget-social-icons-styles',
85
	);
86
87
	/**
88
	 * Contains all assets that have had their URL rewritten to minified versions.
89
	 *
90
	 * @var array
91
	 */
92
	static $min_assets = array();
93
94
	public $plugins_to_deactivate = array(
95
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
96
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
97
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
98
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
99
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
100
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
101
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
102
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
103
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
104
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
105
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
106
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
107
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
108
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
109
	);
110
111
	/**
112
	 * Map of roles we care about, and their corresponding minimum capabilities.
113
	 *
114
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
115
	 *
116
	 * @access public
117
	 * @static
118
	 *
119
	 * @var array
120
	 */
121
	public static $capability_translations = array(
122
		'administrator' => 'manage_options',
123
		'editor'        => 'edit_others_posts',
124
		'author'        => 'publish_posts',
125
		'contributor'   => 'edit_posts',
126
		'subscriber'    => 'read',
127
	);
128
129
	/**
130
	 * Map of modules that have conflicts with plugins and should not be auto-activated
131
	 * if the plugins are active.  Used by filter_default_modules
132
	 *
133
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
134
	 * change `module-slug` and add this to your plugin:
135
	 *
136
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
137
	 * function my_jetpack_get_default_modules( $modules ) {
138
	 *     return array_diff( $modules, array( 'module-slug' ) );
139
	 * }
140
	 *
141
	 * @var array
142
	 */
143
	private $conflicting_plugins = array(
144
		'comments'           => array(
145
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
146
			'Disqus'                         => 'disqus-comment-system/disqus.php',
147
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
148
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
149
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
150
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
151
		),
152
		'comment-likes'      => array(
153
			'Epoch' => 'epoch/plugincore.php',
154
		),
155
		'contact-form'       => array(
156
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
157
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
158
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
159
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
160
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
161
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
162
		),
163
		'latex'              => array(
164
			'LaTeX for WordPress'     => 'latex/latex.php',
165
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
166
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
167
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
168
			'Enable Latex'            => 'enable-latex/enable-latex.php',
169
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
170
		),
171
		'protect'            => array(
172
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
173
			'Captcha'                           => 'captcha/captcha.php',
174
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
175
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
176
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
177
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
178
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
179
			'Security-protection'               => 'security-protection/security-protection.php',
180
			'Login Security'                    => 'login-security/login-security.php',
181
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
182
			'Wordfence Security'                => 'wordfence/wordfence.php',
183
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
184
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
185
		),
186
		'random-redirect'    => array(
187
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
188
		),
189
		'related-posts'      => array(
190
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
191
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
192
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
193
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
194
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
195
			'outbrain'                    => 'outbrain/outbrain.php',
196
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
197
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
198
		),
199
		'sharedaddy'         => array(
200
			'AddThis'     => 'addthis/addthis_social_widget.php',
201
			'Add To Any'  => 'add-to-any/add-to-any.php',
202
			'ShareThis'   => 'share-this/sharethis.php',
203
			'Shareaholic' => 'shareaholic/shareaholic.php',
204
		),
205
		'seo-tools'          => array(
206
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
207
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
208
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
209
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
210
			'The SEO Framework'              => 'autodescription/autodescription.php',
211
		),
212
		'verification-tools' => array(
213
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
214
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
215
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
216
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
217
			'The SEO Framework'              => 'autodescription/autodescription.php',
218
		),
219
		'widget-visibility'  => array(
220
			'Widget Logic'    => 'widget-logic/widget_logic.php',
221
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
222
		),
223
		'sitemaps'           => array(
224
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
225
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
226
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
227
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
228
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
229
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
230
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
231
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
232
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
233
			'The SEO Framework'                    => 'autodescription/autodescription.php',
234
			'Sitemap'                              => 'sitemap/sitemap.php',
235
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
236
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
237
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
238
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
239
		),
240
		'lazy-images'        => array(
241
			'Lazy Load'              => 'lazy-load/lazy-load.php',
242
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
243
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
244
		),
245
	);
246
247
	/**
248
	 * Plugins for which we turn off our Facebook OG Tags implementation.
249
	 *
250
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
251
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
252
	 *
253
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
254
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
255
	 */
256
	private $open_graph_conflicting_plugins = array(
257
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
258
		// 2 Click Social Media Buttons
259
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
260
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
261
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
262
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
263
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
264
		// Open Graph Meta Tags by Heateor
265
		'facebook/facebook.php',                                 // Facebook (official plugin)
266
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
267
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
268
		// Facebook Featured Image & OG Meta Tags
269
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
270
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
271
		// Facebook Open Graph Meta Tags for WordPress
272
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
273
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
274
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
275
		// Fedmich's Facebook Open Graph Meta
276
		'network-publisher/networkpub.php',                      // Network Publisher
277
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
278
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
279
		// NextScripts SNAP
280
		'og-tags/og-tags.php',                                   // OG Tags
281
		'opengraph/opengraph.php',                               // Open Graph
282
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
283
		// Open Graph Protocol Framework
284
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
285
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
286
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
287
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
288
		'sharepress/sharepress.php',                             // SharePress
289
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
290
		'social-discussions/social-discussions.php',             // Social Discussions
291
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
292
		'socialize/socialize.php',                               // Socialize
293
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
294
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
295
		// Tweet, Like, Google +1 and Share
296
		'wordbooker/wordbooker.php',                             // Wordbooker
297
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
298
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
299
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
300
		// WP Facebook Like Send & Open Graph Meta
301
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
302
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
303
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
304
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
305
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
306
	);
307
308
	/**
309
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
310
	 */
311
	private $twitter_cards_conflicting_plugins = array(
312
		// 'twitter/twitter.php',                       // The official one handles this on its own.
313
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
314
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
315
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
316
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
317
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
318
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
319
		'twitter-cards/twitter-cards.php',           // Twitter Cards
320
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
321
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
322
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
323
	);
324
325
	/**
326
	 * Message to display in admin_notice
327
	 *
328
	 * @var string
329
	 */
330
	public $message = '';
331
332
	/**
333
	 * Error to display in admin_notice
334
	 *
335
	 * @var string
336
	 */
337
	public $error = '';
338
339
	/**
340
	 * Modules that need more privacy description.
341
	 *
342
	 * @var string
343
	 */
344
	public $privacy_checks = '';
345
346
	/**
347
	 * Stats to record once the page loads
348
	 *
349
	 * @var array
350
	 */
351
	public $stats = array();
352
353
	/**
354
	 * Jetpack_Sync object
355
	 */
356
	public $sync;
357
358
	/**
359
	 * Verified data for JSON authorization request
360
	 */
361
	public $json_api_authorization_request = array();
362
363
	/**
364
	 * @var Automattic\Jetpack\Connection\Manager
365
	 */
366
	protected $connection_manager;
367
368
	/**
369
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
370
	 */
371
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
372
373
	/**
374
	 * Constant for login redirect key.
375
	 *
376
	 * @var string
377
	 * @since 8.4.0
378
	 */
379
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
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
				/*
439
				 * Minileven deprecation. 8.3.0.
440
				 * Only delete options if not using
441
				 * the replacement standalone Minileven plugin.
442
				 */
443
				if (
444
					! self::is_plugin_active( 'minileven-master/minileven.php' )
445
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
446
				) {
447
					if ( get_option( 'wp_mobile_custom_css' ) ) {
448
						delete_option( 'wp_mobile_custom_css' );
449
					}
450
					if ( get_option( 'wp_mobile_excerpt' ) ) {
451
						delete_option( 'wp_mobile_excerpt' );
452
					}
453
					if ( get_option( 'wp_mobile_featured_images' ) ) {
454
						delete_option( 'wp_mobile_featured_images' );
455
					}
456
					if ( get_option( 'wp_mobile_app_promos' ) ) {
457
						delete_option( 'wp_mobile_app_promos' );
458
					}
459
				}
460
461
				// Upgrade to 8.4.0.
462
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
463
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
464
				}
465
466
				if ( did_action( 'wp_loaded' ) ) {
467
					self::upgrade_on_load();
468
				} else {
469
					add_action(
470
						'wp_loaded',
471
						array( __CLASS__, 'upgrade_on_load' )
472
					);
473
				}
474
			}
475
		}
476
	}
477
478
	/**
479
	 * Runs upgrade routines that need to have modules loaded.
480
	 */
481
	static function upgrade_on_load() {
482
483
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
484
		// This can happen in case Jetpack has been just upgraded and is
485
		// being initialized late during the page load. In this case we wait
486
		// until the next proper admin page load with Jetpack active.
487
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
488
			delete_transient( self::$plugin_upgrade_lock_key );
489
490
			return;
491
		}
492
493
		self::maybe_set_version_option();
494
495
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
496
			Jetpack_Widget_Conditions::migrate_post_type_rules();
497
		}
498
499
		if (
500
			class_exists( 'Jetpack_Sitemap_Manager' )
501
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
502
		) {
503
			do_action( 'jetpack_sitemaps_purge_data' );
504
		}
505
506
		// Delete old stats cache
507
		delete_option( 'jetpack_restapi_stats_cache' );
508
509
		delete_transient( self::$plugin_upgrade_lock_key );
510
	}
511
512
	/**
513
	 * Saves all the currently active modules to options.
514
	 * Also fires Action hooks for each newly activated and deactivated module.
515
	 *
516
	 * @param $modules Array Array of active modules to be saved in options.
517
	 *
518
	 * @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...
519
	 */
520
	static function update_active_modules( $modules ) {
521
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
522
		$active_modules       = self::get_active_modules();
523
		$new_active_modules   = array_diff( $modules, $current_modules );
524
		$new_inactive_modules = array_diff( $active_modules, $modules );
525
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
526
		$reindexed_modules    = array_values( $new_current_modules );
527
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
528
529
		foreach ( $new_active_modules as $module ) {
530
			/**
531
			 * Fires when a specific module is activated.
532
			 *
533
			 * @since 1.9.0
534
			 *
535
			 * @param string $module Module slug.
536
			 * @param boolean $success whether the module was activated. @since 4.2
537
			 */
538
			do_action( 'jetpack_activate_module', $module, $success );
539
			/**
540
			 * Fires when a module is activated.
541
			 * The dynamic part of the filter, $module, is the module slug.
542
			 *
543
			 * @since 1.9.0
544
			 *
545
			 * @param string $module Module slug.
546
			 */
547
			do_action( "jetpack_activate_module_$module", $module );
548
		}
549
550
		foreach ( $new_inactive_modules as $module ) {
551
			/**
552
			 * Fired after a module has been deactivated.
553
			 *
554
			 * @since 4.2.0
555
			 *
556
			 * @param string $module Module slug.
557
			 * @param boolean $success whether the module was deactivated.
558
			 */
559
			do_action( 'jetpack_deactivate_module', $module, $success );
560
			/**
561
			 * Fires when a module is deactivated.
562
			 * The dynamic part of the filter, $module, is the module slug.
563
			 *
564
			 * @since 1.9.0
565
			 *
566
			 * @param string $module Module slug.
567
			 */
568
			do_action( "jetpack_deactivate_module_$module", $module );
569
		}
570
571
		return $success;
572
	}
573
574
	static function delete_active_modules() {
575
		self::update_active_modules( array() );
576
	}
577
578
	/**
579
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
580
	 * available.
581
	 */
582
	public function add_configure_hook() {
583
		global $wp_filter;
584
585
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
586
		if ( false !== $current_priority ) {
587
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
588
		}
589
590
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
591
		sort( $taken_priorities );
592
593
		$first_priority = array_shift( $taken_priorities );
594
595
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
596
			$new_priority = - PHP_INT_MAX;
597
		} else {
598
			$new_priority = $first_priority - 1;
599
		}
600
601
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
602
	}
603
604
	/**
605
	 * Constructor.  Initializes WordPress hooks
606
	 */
607
	private function __construct() {
608
		/*
609
		 * Check for and alert any deprecated hooks
610
		 */
611
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
612
613
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
614
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
615
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
616
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
617
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
618
619
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
620
621
		add_filter(
622
			'jetpack_signature_check_token',
623
			array( __CLASS__, 'verify_onboarding_token' ),
624
			10,
625
			3
626
		);
627
628
		/**
629
		 * Prepare Gutenberg Editor functionality
630
		 */
631
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
632
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
633
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
634
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
635
636
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
637
638
		// Unlink user before deleting the user from WP.com.
639
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
640
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
641
642
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
643
644
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
645
		add_action( 'login_init', array( $this, 'login_init' ) );
646
647
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
648
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
649
650
		add_action( 'admin_init', array( $this, 'admin_init' ) );
651
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
652
653
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
654
655
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
656
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
657
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
658
659
		// returns HTTPS support status
660
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
661
662
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
663
664
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
665
666
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
667
668
		/**
669
		 * These actions run checks to load additional files.
670
		 * They check for external files or plugins, so they need to run as late as possible.
671
		 */
672
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
673
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
674
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
675
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
676
677
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
678
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
679
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
680
681
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
682
683
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
684
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
685
686
		// A filter to control all just in time messages
687
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
688
689
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
690
691
		/*
692
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
693
		 * We should make sure to only do this for front end links.
694
		 */
695
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
696
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
697
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
698
699
			/*
700
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
701
			 * so they point moderation links on emails to Calypso.
702
			 */
703
			jetpack_require_lib( 'functions.wp-notify' );
704
		}
705
706
		// Hide edit post link if mobile app.
707
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
708
			add_filter( 'get_edit_post_link', '__return_empty_string' );
709
		}
710
711
		// Update the Jetpack plan from API on heartbeats.
712
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
713
714
		/**
715
		 * This is the hack to concatenate all css files into one.
716
		 * For description and reasoning see the implode_frontend_css method.
717
		 *
718
		 * Super late priority so we catch all the registered styles.
719
		 */
720
		if ( ! is_admin() ) {
721
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
722
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
723
		}
724
725
		/**
726
		 * These are sync actions that we need to keep track of for jitms
727
		 */
728
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
729
730
		// Actually push the stats on shutdown.
731
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
732
			add_action( 'shutdown', array( $this, 'push_stats' ) );
733
		}
734
735
		// Actions for Manager::authorize().
736
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
737
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
738
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
739
740
		// Filters for the Manager::get_token() urls and request body.
741
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
742
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
743
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
744
	}
745
746
	/**
747
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
748
	 * Config object.
749
	 */
750
	public function configure() {
751
		$config = new Config();
752
753
		foreach (
754
			array(
755
				'sync',
756
				'tracking',
757
				'tos',
758
			)
759
			as $feature
760
		) {
761
			$config->ensure( $feature );
762
		}
763
764
		$config->ensure(
765
			'connection',
766
			array(
767
				'slug' => 'jetpack',
768
				'name' => 'Jetpack',
769
			)
770
		);
771
772
		if ( is_admin() ) {
773
			$config->ensure( 'jitm' );
774
		}
775
776
		if ( ! $this->connection_manager ) {
777
			$this->connection_manager = new Connection_Manager( 'jetpack' );
778
		}
779
780
		/*
781
		 * Load things that should only be in Network Admin.
782
		 *
783
		 * For now blow away everything else until a more full
784
		 * understanding of what is needed at the network level is
785
		 * available
786
		 */
787
		if ( is_multisite() ) {
788
			$network = Jetpack_Network::init();
789
			$network->set_connection( $this->connection_manager );
790
		}
791
792
		if ( $this->connection_manager->is_active() ) {
793
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
794
795
			Jetpack_Heartbeat::init();
796
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
797
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
798
				Jetpack_Search_Performance_Logger::init();
799
			}
800
		}
801
802
		// Initialize remote file upload request handlers.
803
		$this->add_remote_request_handlers();
804
805
		/*
806
		 * Enable enhanced handling of previewing sites in Calypso
807
		 */
808
		if ( self::is_active() ) {
809
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
810
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
811
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
812
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
813
		}
814
	}
815
816
	/**
817
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
818
	 * initialization code.
819
	 *
820
	 * @action plugins_loaded
821
	 */
822
	public function late_initialization() {
823
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
824
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
825
826
		Partner::init();
827
828
		/**
829
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
830
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
831
		 *
832
		 * @since 8.1.0
833
		 *
834
		 * @param Jetpack $jetpack the main plugin class object.
835
		 */
836
		do_action( 'jetpack_loaded', $this );
837
838
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
839
	}
840
841
	/**
842
	 * Sets up the XMLRPC request handlers.
843
	 *
844
	 * @deprecated since 7.7.0
845
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
846
	 *
847
	 * @param array                 $request_params Incoming request parameters.
848
	 * @param Boolean               $is_active      Whether the connection is currently active.
849
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
850
	 * @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...
851
	 */
852 View Code Duplication
	public function setup_xmlrpc_handlers(
853
		$request_params,
854
		$is_active,
855
		$is_signed,
856
		Jetpack_XMLRPC_Server $xmlrpc_server = null
857
	) {
858
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
859
860
		if ( ! $this->connection_manager ) {
861
			$this->connection_manager = new Connection_Manager();
862
		}
863
864
		return $this->connection_manager->setup_xmlrpc_handlers(
865
			$request_params,
866
			$is_active,
867
			$is_signed,
868
			$xmlrpc_server
869
		);
870
	}
871
872
	/**
873
	 * Initialize REST API registration connector.
874
	 *
875
	 * @deprecated since 7.7.0
876
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
877
	 */
878 View Code Duplication
	public function initialize_rest_api_registration_connector() {
879
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
880
881
		if ( ! $this->connection_manager ) {
882
			$this->connection_manager = new Connection_Manager();
883
		}
884
885
		$this->connection_manager->initialize_rest_api_registration_connector();
886
	}
887
888
	/**
889
	 * This is ported over from the manage module, which has been deprecated and baked in here.
890
	 *
891
	 * @param $domains
892
	 */
893
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
894
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
895
	}
896
897
	/**
898
	 * Return $domains, with 'wordpress.com' appended.
899
	 * This is ported over from the manage module, which has been deprecated and baked in here.
900
	 *
901
	 * @param $domains
902
	 * @return array
903
	 */
904
	function allow_wpcom_domain( $domains ) {
905
		if ( empty( $domains ) ) {
906
			$domains = array();
907
		}
908
		$domains[] = 'wordpress.com';
909
		return array_unique( $domains );
910
	}
911
912
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
913
		$post = get_post( $post_id );
914
915
		if ( empty( $post ) ) {
916
			return $default_url;
917
		}
918
919
		$post_type = $post->post_type;
920
921
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
922
		// https://en.support.wordpress.com/custom-post-types/
923
		$allowed_post_types = array(
924
			'post',
925
			'page',
926
			'jetpack-portfolio',
927
			'jetpack-testimonial',
928
		);
929
930
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
931
			return $default_url;
932
		}
933
934
		return esc_url(
935
			Redirect::get_url(
936
				'calypso-edit-' . $post_type,
937
				array(
938
					'path' => $post_id,
939
				)
940
			)
941
		);
942
	}
943
944
	function point_edit_comment_links_to_calypso( $url ) {
945
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
946
		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...
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
947
948
		return esc_url(
949
			Redirect::get_url(
950
				'calypso-edit-comment',
951
				array(
952
					'path' => $query_args['amp;c'],
953
				)
954
			)
955
		);
956
957
	}
958
959
	function jetpack_track_last_sync_callback( $params ) {
960
		/**
961
		 * Filter to turn off jitm caching
962
		 *
963
		 * @since 5.4.0
964
		 *
965
		 * @param bool false Whether to cache just in time messages
966
		 */
967
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
968
			return $params;
969
		}
970
971
		if ( is_array( $params ) && isset( $params[0] ) ) {
972
			$option = $params[0];
973
			if ( 'active_plugins' === $option ) {
974
				// use the cache if we can, but not terribly important if it gets evicted
975
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
976
			}
977
		}
978
979
		return $params;
980
	}
981
982 View Code Duplication
	function jetpack_connection_banner_callback() {
983
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
984
985
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
986
		if (
987
			isset( $_REQUEST['dismissBanner'] ) &&
988
			! Jetpack_Connection_Banner::force_display()
989
		) {
990
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
991
			wp_send_json_success();
992
		}
993
994
		wp_die();
995
	}
996
997
	/**
998
	 * Removes all XML-RPC methods that are not `jetpack.*`.
999
	 * Only used in our alternate XML-RPC endpoint, where we want to
1000
	 * ensure that Core and other plugins' methods are not exposed.
1001
	 *
1002
	 * @deprecated since 7.7.0
1003
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1004
	 *
1005
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1006
	 * @return array Filtered $methods
1007
	 */
1008 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1009
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1010
1011
		if ( ! $this->connection_manager ) {
1012
			$this->connection_manager = new Connection_Manager();
1013
		}
1014
1015
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1016
	}
1017
1018
	/**
1019
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1020
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1021
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1022
	 * which is accessible via a different URI. Most of the below is copied directly
1023
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1024
	 *
1025
	 * @deprecated since 7.7.0
1026
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1027
	 */
1028 View Code Duplication
	public function alternate_xmlrpc() {
1029
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1030
1031
		if ( ! $this->connection_manager ) {
1032
			$this->connection_manager = new Connection_Manager();
1033
		}
1034
1035
		$this->connection_manager->alternate_xmlrpc();
1036
	}
1037
1038
	/**
1039
	 * The callback for the JITM ajax requests.
1040
	 *
1041
	 * @deprecated since 7.9.0
1042
	 */
1043
	function jetpack_jitm_ajax_callback() {
1044
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1045
	}
1046
1047
	/**
1048
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1049
	 */
1050
	function push_stats() {
1051
		if ( ! empty( $this->stats ) ) {
1052
			$this->do_stats( 'server_side' );
1053
		}
1054
	}
1055
1056
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1057
		$is_development_mode = ( new Status() )->is_development_mode();
1058
		switch ( $cap ) {
1059
			case 'jetpack_connect':
1060
			case 'jetpack_reconnect':
1061
				if ( $is_development_mode ) {
1062
					$caps = array( 'do_not_allow' );
1063
					break;
1064
				}
1065
				/**
1066
				 * Pass through. If it's not development mode, these should match disconnect.
1067
				 * Let users disconnect if it's development mode, just in case things glitch.
1068
				 */
1069
			case 'jetpack_disconnect':
1070
				/**
1071
				 * In multisite, can individual site admins manage their own connection?
1072
				 *
1073
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1074
				 */
1075
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1076
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1077
						/**
1078
						 * We need to update the option name -- it's terribly unclear which
1079
						 * direction the override goes.
1080
						 *
1081
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1082
						 */
1083
						$caps = array( 'do_not_allow' );
1084
						break;
1085
					}
1086
				}
1087
1088
				$caps = array( 'manage_options' );
1089
				break;
1090
			case 'jetpack_manage_modules':
1091
			case 'jetpack_activate_modules':
1092
			case 'jetpack_deactivate_modules':
1093
				$caps = array( 'manage_options' );
1094
				break;
1095
			case 'jetpack_configure_modules':
1096
				$caps = array( 'manage_options' );
1097
				break;
1098
			case 'jetpack_manage_autoupdates':
1099
				$caps = array(
1100
					'manage_options',
1101
					'update_plugins',
1102
				);
1103
				break;
1104
			case 'jetpack_network_admin_page':
1105
			case 'jetpack_network_settings_page':
1106
				$caps = array( 'manage_network_plugins' );
1107
				break;
1108
			case 'jetpack_network_sites_page':
1109
				$caps = array( 'manage_sites' );
1110
				break;
1111
			case 'jetpack_admin_page':
1112
				if ( $is_development_mode ) {
1113
					$caps = array( 'manage_options' );
1114
					break;
1115
				} else {
1116
					$caps = array( 'read' );
1117
				}
1118
				break;
1119
			case 'jetpack_connect_user':
1120
				if ( $is_development_mode ) {
1121
					$caps = array( 'do_not_allow' );
1122
					break;
1123
				}
1124
				$caps = array( 'read' );
1125
				break;
1126
		}
1127
		return $caps;
1128
	}
1129
1130
	/**
1131
	 * Require a Jetpack authentication.
1132
	 *
1133
	 * @deprecated since 7.7.0
1134
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1135
	 */
1136 View Code Duplication
	public function require_jetpack_authentication() {
1137
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1138
1139
		if ( ! $this->connection_manager ) {
1140
			$this->connection_manager = new Connection_Manager();
1141
		}
1142
1143
		$this->connection_manager->require_jetpack_authentication();
1144
	}
1145
1146
	/**
1147
	 * Load language files
1148
	 *
1149
	 * @action plugins_loaded
1150
	 */
1151
	public static function plugin_textdomain() {
1152
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1153
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1154
	}
1155
1156
	/**
1157
	 * Register assets for use in various modules and the Jetpack admin page.
1158
	 *
1159
	 * @uses wp_script_is, wp_register_script, plugins_url
1160
	 * @action wp_loaded
1161
	 * @return null
1162
	 */
1163
	public function register_assets() {
1164
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1165
			wp_register_script(
1166
				'spin',
1167
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1168
				false,
1169
				'1.3'
1170
			);
1171
		}
1172
1173 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1174
			wp_register_script(
1175
				'jquery.spin',
1176
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1177
				array( 'jquery', 'spin' ),
1178
				'1.3'
1179
			);
1180
		}
1181
1182 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1183
			wp_register_script(
1184
				'jetpack-gallery-settings',
1185
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1186
				array( 'media-views' ),
1187
				'20121225'
1188
			);
1189
		}
1190
1191 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1192
			wp_register_script(
1193
				'jetpack-twitter-timeline',
1194
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1195
				array( 'jquery' ),
1196
				'4.0.0',
1197
				true
1198
			);
1199
		}
1200
1201
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1202
			wp_register_script(
1203
				'jetpack-facebook-embed',
1204
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1205
				array(),
1206
				null,
1207
				true
1208
			);
1209
1210
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1211
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1212
			if ( ! is_numeric( $fb_app_id ) ) {
1213
				$fb_app_id = '';
1214
			}
1215
			wp_localize_script(
1216
				'jetpack-facebook-embed',
1217
				'jpfbembed',
1218
				array(
1219
					'appid'  => $fb_app_id,
1220
					'locale' => $this->get_locale(),
1221
				)
1222
			);
1223
		}
1224
1225
		/**
1226
		 * As jetpack_register_genericons is by default fired off a hook,
1227
		 * the hook may have already fired by this point.
1228
		 * So, let's just trigger it manually.
1229
		 */
1230
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1231
		jetpack_register_genericons();
1232
1233
		/**
1234
		 * Register the social logos
1235
		 */
1236
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1237
		jetpack_register_social_logos();
1238
1239 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1240
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1241
		}
1242
	}
1243
1244
	/**
1245
	 * Guess locale from language code.
1246
	 *
1247
	 * @param string $lang Language code.
1248
	 * @return string|bool
1249
	 */
1250 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1251
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1252
			return 'en_US';
1253
		}
1254
1255
		if ( ! class_exists( 'GP_Locales' ) ) {
1256
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1257
				return false;
1258
			}
1259
1260
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1261
		}
1262
1263
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1264
			// WP.com: get_locale() returns 'it'
1265
			$locale = GP_Locales::by_slug( $lang );
1266
		} else {
1267
			// Jetpack: get_locale() returns 'it_IT';
1268
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1269
		}
1270
1271
		if ( ! $locale ) {
1272
			return false;
1273
		}
1274
1275
		if ( empty( $locale->facebook_locale ) ) {
1276
			if ( empty( $locale->wp_locale ) ) {
1277
				return false;
1278
			} else {
1279
				// Facebook SDK is smart enough to fall back to en_US if a
1280
				// locale isn't supported. Since supported Facebook locales
1281
				// can fall out of sync, we'll attempt to use the known
1282
				// wp_locale value and rely on said fallback.
1283
				return $locale->wp_locale;
1284
			}
1285
		}
1286
1287
		return $locale->facebook_locale;
1288
	}
1289
1290
	/**
1291
	 * Get the locale.
1292
	 *
1293
	 * @return string|bool
1294
	 */
1295
	function get_locale() {
1296
		$locale = $this->guess_locale_from_lang( get_locale() );
1297
1298
		if ( ! $locale ) {
1299
			$locale = 'en_US';
1300
		}
1301
1302
		return $locale;
1303
	}
1304
1305
	/**
1306
	 * Return the network_site_url so that .com knows what network this site is a part of.
1307
	 *
1308
	 * @param  bool $option
1309
	 * @return string
1310
	 */
1311
	public function jetpack_main_network_site_option( $option ) {
1312
		return network_site_url();
1313
	}
1314
	/**
1315
	 * Network Name.
1316
	 */
1317
	static function network_name( $option = null ) {
1318
		global $current_site;
1319
		return $current_site->site_name;
1320
	}
1321
	/**
1322
	 * Does the network allow new user and site registrations.
1323
	 *
1324
	 * @return string
1325
	 */
1326
	static function network_allow_new_registrations( $option = null ) {
1327
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1328
	}
1329
	/**
1330
	 * Does the network allow admins to add new users.
1331
	 *
1332
	 * @return boolian
1333
	 */
1334
	static function network_add_new_users( $option = null ) {
1335
		return (bool) get_site_option( 'add_new_users' );
1336
	}
1337
	/**
1338
	 * File upload psace left per site in MB.
1339
	 *  -1 means NO LIMIT.
1340
	 *
1341
	 * @return number
1342
	 */
1343
	static function network_site_upload_space( $option = null ) {
1344
		// value in MB
1345
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1346
	}
1347
1348
	/**
1349
	 * Network allowed file types.
1350
	 *
1351
	 * @return string
1352
	 */
1353
	static function network_upload_file_types( $option = null ) {
1354
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1355
	}
1356
1357
	/**
1358
	 * Maximum file upload size set by the network.
1359
	 *
1360
	 * @return number
1361
	 */
1362
	static function network_max_upload_file_size( $option = null ) {
1363
		// value in KB
1364
		return get_site_option( 'fileupload_maxk', 300 );
1365
	}
1366
1367
	/**
1368
	 * Lets us know if a site allows admins to manage the network.
1369
	 *
1370
	 * @return array
1371
	 */
1372
	static function network_enable_administration_menus( $option = null ) {
1373
		return get_site_option( 'menu_items' );
1374
	}
1375
1376
	/**
1377
	 * If a user has been promoted to or demoted from admin, we need to clear the
1378
	 * jetpack_other_linked_admins transient.
1379
	 *
1380
	 * @since 4.3.2
1381
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1382
	 *
1383
	 * @param int    $user_id   The user ID whose role changed.
1384
	 * @param string $role      The new role.
1385
	 * @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...
1386
	 */
1387
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1388
		if ( 'administrator' == $role
1389
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1390
			|| is_null( $old_roles )
1391
		) {
1392
			delete_transient( 'jetpack_other_linked_admins' );
1393
		}
1394
	}
1395
1396
	/**
1397
	 * Checks to see if there are any other users available to become primary
1398
	 * Users must both:
1399
	 * - Be linked to wpcom
1400
	 * - Be an admin
1401
	 *
1402
	 * @return mixed False if no other users are linked, Int if there are.
1403
	 */
1404
	static function get_other_linked_admins() {
1405
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1406
1407
		if ( false === $other_linked_users ) {
1408
			$admins = get_users( array( 'role' => 'administrator' ) );
1409
			if ( count( $admins ) > 1 ) {
1410
				$available = array();
1411
				foreach ( $admins as $admin ) {
1412
					if ( self::is_user_connected( $admin->ID ) ) {
1413
						$available[] = $admin->ID;
1414
					}
1415
				}
1416
1417
				$count_connected_admins = count( $available );
1418
				if ( count( $available ) > 1 ) {
1419
					$other_linked_users = $count_connected_admins;
1420
				} else {
1421
					$other_linked_users = 0;
1422
				}
1423
			} else {
1424
				$other_linked_users = 0;
1425
			}
1426
1427
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1428
		}
1429
1430
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1431
	}
1432
1433
	/**
1434
	 * Return whether we are dealing with a multi network setup or not.
1435
	 * The reason we are type casting this is because we want to avoid the situation where
1436
	 * the result is false since when is_main_network_option return false it cases
1437
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1438
	 * database which could be set to anything as opposed to what this function returns.
1439
	 *
1440
	 * @param  bool $option
1441
	 *
1442
	 * @return boolean
1443
	 */
1444
	public function is_main_network_option( $option ) {
1445
		// return '1' or ''
1446
		return (string) (bool) self::is_multi_network();
1447
	}
1448
1449
	/**
1450
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1451
	 *
1452
	 * @param  string $option
1453
	 * @return boolean
1454
	 */
1455
	public function is_multisite( $option ) {
1456
		return (string) (bool) is_multisite();
1457
	}
1458
1459
	/**
1460
	 * Implemented since there is no core is multi network function
1461
	 * Right now there is no way to tell if we which network is the dominant network on the system
1462
	 *
1463
	 * @since  3.3
1464
	 * @return boolean
1465
	 */
1466 View Code Duplication
	public static function is_multi_network() {
1467
		global  $wpdb;
1468
1469
		// if we don't have a multi site setup no need to do any more
1470
		if ( ! is_multisite() ) {
1471
			return false;
1472
		}
1473
1474
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1475
		if ( $num_sites > 1 ) {
1476
			return true;
1477
		} else {
1478
			return false;
1479
		}
1480
	}
1481
1482
	/**
1483
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1484
	 *
1485
	 * @return null
1486
	 */
1487
	function update_jetpack_main_network_site_option() {
1488
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1489
	}
1490
	/**
1491
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1492
	 */
1493
	function update_jetpack_network_settings() {
1494
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1495
		// Only sync this info for the main network site.
1496
	}
1497
1498
	/**
1499
	 * Get back if the current site is single user site.
1500
	 *
1501
	 * @return bool
1502
	 */
1503 View Code Duplication
	public static function is_single_user_site() {
1504
		global $wpdb;
1505
1506
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1507
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1508
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1509
		}
1510
		return 1 === (int) $some_users;
1511
	}
1512
1513
	/**
1514
	 * Returns true if the site has file write access false otherwise.
1515
	 *
1516
	 * @return string ( '1' | '0' )
1517
	 **/
1518
	public static function file_system_write_access() {
1519
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1520
			require_once ABSPATH . 'wp-admin/includes/file.php';
1521
		}
1522
1523
		require_once ABSPATH . 'wp-admin/includes/template.php';
1524
1525
		$filesystem_method = get_filesystem_method();
1526
		if ( $filesystem_method === 'direct' ) {
1527
			return 1;
1528
		}
1529
1530
		ob_start();
1531
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1532
		ob_end_clean();
1533
		if ( $filesystem_credentials_are_stored ) {
1534
			return 1;
1535
		}
1536
		return 0;
1537
	}
1538
1539
	/**
1540
	 * Finds out if a site is using a version control system.
1541
	 *
1542
	 * @return string ( '1' | '0' )
1543
	 **/
1544
	public static function is_version_controlled() {
1545
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1546
		return (string) (int) Functions::is_version_controlled();
1547
	}
1548
1549
	/**
1550
	 * Determines whether the current theme supports featured images or not.
1551
	 *
1552
	 * @return string ( '1' | '0' )
1553
	 */
1554
	public static function featured_images_enabled() {
1555
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1556
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1557
	}
1558
1559
	/**
1560
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1561
	 *
1562
	 * @deprecated 4.7 use get_avatar_url instead.
1563
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1564
	 * @param int               $size Size of the avatar image
1565
	 * @param string            $default URL to a default image to use if no avatar is available
1566
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1567
	 *
1568
	 * @return array
1569
	 */
1570
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1571
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1572
		return get_avatar_url(
1573
			$id_or_email,
1574
			array(
1575
				'size'          => $size,
1576
				'default'       => $default,
1577
				'force_default' => $force_display,
1578
			)
1579
		);
1580
	}
1581
1582
	/**
1583
	 * jetpack_updates is saved in the following schema:
1584
	 *
1585
	 * array (
1586
	 *      'plugins'                       => (int) Number of plugin updates available.
1587
	 *      'themes'                        => (int) Number of theme updates available.
1588
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1589
	 *      'translations'                  => (int) Number of translation updates available.
1590
	 *      'total'                         => (int) Total of all available updates.
1591
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1592
	 * )
1593
	 *
1594
	 * @return array
1595
	 */
1596
	public static function get_updates() {
1597
		$update_data = wp_get_update_data();
1598
1599
		// Stores the individual update counts as well as the total count.
1600
		if ( isset( $update_data['counts'] ) ) {
1601
			$updates = $update_data['counts'];
1602
		}
1603
1604
		// If we need to update WordPress core, let's find the latest version number.
1605 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1606
			$cur = get_preferred_from_update_core();
1607
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1608
				$updates['wp_update_version'] = $cur->current;
1609
			}
1610
		}
1611
		return isset( $updates ) ? $updates : array();
1612
	}
1613
1614
	public static function get_update_details() {
1615
		$update_details = array(
1616
			'update_core'    => get_site_transient( 'update_core' ),
1617
			'update_plugins' => get_site_transient( 'update_plugins' ),
1618
			'update_themes'  => get_site_transient( 'update_themes' ),
1619
		);
1620
		return $update_details;
1621
	}
1622
1623
	public static function refresh_update_data() {
1624
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1625
1626
	}
1627
1628
	public static function refresh_theme_data() {
1629
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1630
	}
1631
1632
	/**
1633
	 * Is Jetpack active?
1634
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1635
	 *
1636
	 * @return bool
1637
	 */
1638
	public static function is_active() {
1639
		return self::connection()->is_active();
1640
	}
1641
1642
	/**
1643
	 * Make an API call to WordPress.com for plan status
1644
	 *
1645
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1646
	 *
1647
	 * @return bool True if plan is updated, false if no update
1648
	 */
1649
	public static function refresh_active_plan_from_wpcom() {
1650
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1651
		return Jetpack_Plan::refresh_from_wpcom();
1652
	}
1653
1654
	/**
1655
	 * Get the plan that this Jetpack site is currently using
1656
	 *
1657
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1658
	 * @return array Active Jetpack plan details.
1659
	 */
1660
	public static function get_active_plan() {
1661
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1662
		return Jetpack_Plan::get();
1663
	}
1664
1665
	/**
1666
	 * Determine whether the active plan supports a particular feature
1667
	 *
1668
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1669
	 * @return bool True if plan supports feature, false if not.
1670
	 */
1671
	public static function active_plan_supports( $feature ) {
1672
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1673
		return Jetpack_Plan::supports( $feature );
1674
	}
1675
1676
	/**
1677
	 * Deprecated: Is Jetpack in development (offline) mode?
1678
	 *
1679
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1680
	 * and themes still use it, and we do not want to flood them with notices.
1681
	 *
1682
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1683
	 *
1684
	 * @deprecated since 8.0.
1685
	 */
1686
	public static function is_development_mode() {
1687
		return ( new Status() )->is_development_mode();
1688
	}
1689
1690
	/**
1691
	 * Whether the site is currently onboarding or not.
1692
	 * A site is considered as being onboarded if it currently has an onboarding token.
1693
	 *
1694
	 * @since 5.8
1695
	 *
1696
	 * @access public
1697
	 * @static
1698
	 *
1699
	 * @return bool True if the site is currently onboarding, false otherwise
1700
	 */
1701
	public static function is_onboarding() {
1702
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1703
	}
1704
1705
	/**
1706
	 * Determines reason for Jetpack development mode.
1707
	 */
1708
	public static function development_mode_trigger_text() {
1709
		if ( ! ( new Status() )->is_development_mode() ) {
1710
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1711
		}
1712
1713
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1714
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1715
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1716
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1717
		} else {
1718
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1719
		}
1720
1721
		return $notice;
1722
1723
	}
1724
	/**
1725
	 * Get Jetpack development mode notice text and notice class.
1726
	 *
1727
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1728
	 */
1729
	public static function show_development_mode_notice() {
1730 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1731
			$notice = sprintf(
1732
				/* translators: %s is a URL */
1733
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1734
				Redirect::get_url( 'jetpack-support-development-mode' )
1735
			);
1736
1737
			$notice .= ' ' . self::development_mode_trigger_text();
1738
1739
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1740
		}
1741
1742
		// Throw up a notice if using a development version and as for feedback.
1743
		if ( self::is_development_version() ) {
1744
			/* translators: %s is a URL */
1745
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1746
1747
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1748
		}
1749
		// Throw up a notice if using staging mode
1750 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1751
			/* translators: %s is a URL */
1752
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1753
1754
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1755
		}
1756
	}
1757
1758
	/**
1759
	 * Whether Jetpack's version maps to a public release, or a development version.
1760
	 */
1761
	public static function is_development_version() {
1762
		/**
1763
		 * Allows filtering whether this is a development version of Jetpack.
1764
		 *
1765
		 * This filter is especially useful for tests.
1766
		 *
1767
		 * @since 4.3.0
1768
		 *
1769
		 * @param bool $development_version Is this a develoment version of Jetpack?
1770
		 */
1771
		return (bool) apply_filters(
1772
			'jetpack_development_version',
1773
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1774
		);
1775
	}
1776
1777
	/**
1778
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1779
	 */
1780
	public static function is_user_connected( $user_id = false ) {
1781
		return self::connection()->is_user_connected( $user_id );
1782
	}
1783
1784
	/**
1785
	 * Get the wpcom user data of the current|specified connected user.
1786
	 */
1787 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1788
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1789
		if ( ! $user_id ) {
1790
			$user_id = get_current_user_id();
1791
		}
1792
1793
		$transient_key = "jetpack_connected_user_data_$user_id";
1794
1795
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1796
			return $cached_user_data;
1797
		}
1798
1799
		$xml = new Jetpack_IXR_Client(
1800
			array(
1801
				'user_id' => $user_id,
1802
			)
1803
		);
1804
		$xml->query( 'wpcom.getUser' );
1805
		if ( ! $xml->isError() ) {
1806
			$user_data = $xml->getResponse();
1807
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1808
			return $user_data;
1809
		}
1810
1811
		return false;
1812
	}
1813
1814
	/**
1815
	 * Get the wpcom email of the current|specified connected user.
1816
	 */
1817
	public static function get_connected_user_email( $user_id = null ) {
1818
		if ( ! $user_id ) {
1819
			$user_id = get_current_user_id();
1820
		}
1821
1822
		$xml = new Jetpack_IXR_Client(
1823
			array(
1824
				'user_id' => $user_id,
1825
			)
1826
		);
1827
		$xml->query( 'wpcom.getUserEmail' );
1828
		if ( ! $xml->isError() ) {
1829
			return $xml->getResponse();
1830
		}
1831
		return false;
1832
	}
1833
1834
	/**
1835
	 * Get the wpcom email of the master user.
1836
	 */
1837
	public static function get_master_user_email() {
1838
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1839
		if ( $master_user_id ) {
1840
			return self::get_connected_user_email( $master_user_id );
1841
		}
1842
		return '';
1843
	}
1844
1845
	/**
1846
	 * Whether the current user is the connection owner.
1847
	 *
1848
	 * @deprecated since 7.7
1849
	 *
1850
	 * @return bool Whether the current user is the connection owner.
1851
	 */
1852
	public function current_user_is_connection_owner() {
1853
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1854
		return self::connection()->is_connection_owner();
1855
	}
1856
1857
	/**
1858
	 * Gets current user IP address.
1859
	 *
1860
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1861
	 *
1862
	 * @return string                  Current user IP address.
1863
	 */
1864
	public static function current_user_ip( $check_all_headers = false ) {
1865
		if ( $check_all_headers ) {
1866
			foreach ( array(
1867
				'HTTP_CF_CONNECTING_IP',
1868
				'HTTP_CLIENT_IP',
1869
				'HTTP_X_FORWARDED_FOR',
1870
				'HTTP_X_FORWARDED',
1871
				'HTTP_X_CLUSTER_CLIENT_IP',
1872
				'HTTP_FORWARDED_FOR',
1873
				'HTTP_FORWARDED',
1874
				'HTTP_VIA',
1875
			) as $key ) {
1876
				if ( ! empty( $_SERVER[ $key ] ) ) {
1877
					return $_SERVER[ $key ];
1878
				}
1879
			}
1880
		}
1881
1882
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1883
	}
1884
1885
	/**
1886
	 * Synchronize connected user role changes
1887
	 */
1888
	function user_role_change( $user_id ) {
1889
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1890
		Users::user_role_change( $user_id );
1891
	}
1892
1893
	/**
1894
	 * Loads the currently active modules.
1895
	 */
1896
	public static function load_modules() {
1897
		$is_development_mode = ( new Status() )->is_development_mode();
1898
		if (
1899
			! self::is_active()
1900
			&& ! $is_development_mode
1901
			&& ! self::is_onboarding()
1902
			&& (
1903
				! is_multisite()
1904
				|| ! get_site_option( 'jetpack_protect_active' )
1905
			)
1906
		) {
1907
			return;
1908
		}
1909
1910
		$version = Jetpack_Options::get_option( 'version' );
1911 View Code Duplication
		if ( ! $version ) {
1912
			$version = $old_version = JETPACK__VERSION . ':' . time();
1913
			/** This action is documented in class.jetpack.php */
1914
			do_action( 'updating_jetpack_version', $version, false );
1915
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1916
		}
1917
		list( $version ) = explode( ':', $version );
1918
1919
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1920
1921
		$modules_data = array();
1922
1923
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1924
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1925
			$updated_modules = array();
1926
			foreach ( $modules as $module ) {
1927
				$modules_data[ $module ] = self::get_module( $module );
1928
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1929
					continue;
1930
				}
1931
1932
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1933
					continue;
1934
				}
1935
1936
				$updated_modules[] = $module;
1937
			}
1938
1939
			$modules = array_diff( $modules, $updated_modules );
1940
		}
1941
1942
		foreach ( $modules as $index => $module ) {
1943
			// If we're in dev mode, disable modules requiring a connection
1944
			if ( $is_development_mode ) {
1945
				// Prime the pump if we need to
1946
				if ( empty( $modules_data[ $module ] ) ) {
1947
					$modules_data[ $module ] = self::get_module( $module );
1948
				}
1949
				// If the module requires a connection, but we're in local mode, don't include it.
1950
				if ( $modules_data[ $module ]['requires_connection'] ) {
1951
					continue;
1952
				}
1953
			}
1954
1955
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1956
				continue;
1957
			}
1958
1959
			if ( ! include_once self::get_module_path( $module ) ) {
1960
				unset( $modules[ $index ] );
1961
				self::update_active_modules( array_values( $modules ) );
1962
				continue;
1963
			}
1964
1965
			/**
1966
			 * Fires when a specific module is loaded.
1967
			 * The dynamic part of the hook, $module, is the module slug.
1968
			 *
1969
			 * @since 1.1.0
1970
			 */
1971
			do_action( 'jetpack_module_loaded_' . $module );
1972
		}
1973
1974
		/**
1975
		 * Fires when all the modules are loaded.
1976
		 *
1977
		 * @since 1.1.0
1978
		 */
1979
		do_action( 'jetpack_modules_loaded' );
1980
1981
		// 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.
1982
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1983
	}
1984
1985
	/**
1986
	 * Check if Jetpack's REST API compat file should be included
1987
	 *
1988
	 * @action plugins_loaded
1989
	 * @return null
1990
	 */
1991
	public function check_rest_api_compat() {
1992
		/**
1993
		 * Filters the list of REST API compat files to be included.
1994
		 *
1995
		 * @since 2.2.5
1996
		 *
1997
		 * @param array $args Array of REST API compat files to include.
1998
		 */
1999
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2000
2001
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2002
			require_once $_jetpack_rest_api_compat_include;
2003
		}
2004
	}
2005
2006
	/**
2007
	 * Gets all plugins currently active in values, regardless of whether they're
2008
	 * traditionally activated or network activated.
2009
	 *
2010
	 * @todo Store the result in core's object cache maybe?
2011
	 */
2012
	public static function get_active_plugins() {
2013
		$active_plugins = (array) get_option( 'active_plugins', array() );
2014
2015
		if ( is_multisite() ) {
2016
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2017
			// whereas active_plugins stores them in the values.
2018
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2019
			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...
2020
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2021
			}
2022
		}
2023
2024
		sort( $active_plugins );
2025
2026
		return array_unique( $active_plugins );
2027
	}
2028
2029
	/**
2030
	 * Gets and parses additional plugin data to send with the heartbeat data
2031
	 *
2032
	 * @since 3.8.1
2033
	 *
2034
	 * @return array Array of plugin data
2035
	 */
2036
	public static function get_parsed_plugin_data() {
2037
		if ( ! function_exists( 'get_plugins' ) ) {
2038
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2039
		}
2040
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2041
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2042
		$active_plugins = self::get_active_plugins();
2043
2044
		$plugins = array();
2045
		foreach ( $all_plugins as $path => $plugin_data ) {
2046
			$plugins[ $path ] = array(
2047
				'is_active' => in_array( $path, $active_plugins ),
2048
				'file'      => $path,
2049
				'name'      => $plugin_data['Name'],
2050
				'version'   => $plugin_data['Version'],
2051
				'author'    => $plugin_data['Author'],
2052
			);
2053
		}
2054
2055
		return $plugins;
2056
	}
2057
2058
	/**
2059
	 * Gets and parses theme data to send with the heartbeat data
2060
	 *
2061
	 * @since 3.8.1
2062
	 *
2063
	 * @return array Array of theme data
2064
	 */
2065
	public static function get_parsed_theme_data() {
2066
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2067
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2068
2069
		$themes = array();
2070
		foreach ( $all_themes as $slug => $theme_data ) {
2071
			$theme_headers = array();
2072
			foreach ( $header_keys as $header_key ) {
2073
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2074
			}
2075
2076
			$themes[ $slug ] = array(
2077
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2078
				'slug'            => $slug,
2079
				'theme_root'      => $theme_data->get_theme_root_uri(),
2080
				'parent'          => $theme_data->parent(),
2081
				'headers'         => $theme_headers,
2082
			);
2083
		}
2084
2085
		return $themes;
2086
	}
2087
2088
	/**
2089
	 * Checks whether a specific plugin is active.
2090
	 *
2091
	 * We don't want to store these in a static variable, in case
2092
	 * there are switch_to_blog() calls involved.
2093
	 */
2094
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2095
		return in_array( $plugin, self::get_active_plugins() );
2096
	}
2097
2098
	/**
2099
	 * Check if Jetpack's Open Graph tags should be used.
2100
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2101
	 *
2102
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2103
	 * @action plugins_loaded
2104
	 * @return null
2105
	 */
2106
	public function check_open_graph() {
2107
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2108
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2109
		}
2110
2111
		$active_plugins = self::get_active_plugins();
2112
2113
		if ( ! empty( $active_plugins ) ) {
2114
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2115
				if ( in_array( $plugin, $active_plugins ) ) {
2116
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2117
					break;
2118
				}
2119
			}
2120
		}
2121
2122
		/**
2123
		 * Allow the addition of Open Graph Meta Tags to all pages.
2124
		 *
2125
		 * @since 2.0.3
2126
		 *
2127
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2128
		 */
2129
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2130
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2131
		}
2132
	}
2133
2134
	/**
2135
	 * Check if Jetpack's Twitter tags should be used.
2136
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2137
	 *
2138
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2139
	 * @action plugins_loaded
2140
	 * @return null
2141
	 */
2142
	public function check_twitter_tags() {
2143
2144
		$active_plugins = self::get_active_plugins();
2145
2146
		if ( ! empty( $active_plugins ) ) {
2147
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2148
				if ( in_array( $plugin, $active_plugins ) ) {
2149
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2150
					break;
2151
				}
2152
			}
2153
		}
2154
2155
		/**
2156
		 * Allow Twitter Card Meta tags to be disabled.
2157
		 *
2158
		 * @since 2.6.0
2159
		 *
2160
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2161
		 */
2162
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2163
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2164
		}
2165
	}
2166
2167
	/**
2168
	 * Allows plugins to submit security reports.
2169
	 *
2170
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2171
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2172
	 * @param array  $args         See definitions above
2173
	 */
2174
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2175
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2176
	}
2177
2178
	/* Jetpack Options API */
2179
2180
	public static function get_option_names( $type = 'compact' ) {
2181
		return Jetpack_Options::get_option_names( $type );
2182
	}
2183
2184
	/**
2185
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2186
	 *
2187
	 * @param string $name    Option name
2188
	 * @param mixed  $default (optional)
2189
	 */
2190
	public static function get_option( $name, $default = false ) {
2191
		return Jetpack_Options::get_option( $name, $default );
2192
	}
2193
2194
	/**
2195
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2196
	 *
2197
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2198
	 * @param string $name  Option name
2199
	 * @param mixed  $value Option value
2200
	 */
2201
	public static function update_option( $name, $value ) {
2202
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2203
		return Jetpack_Options::update_option( $name, $value );
2204
	}
2205
2206
	/**
2207
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2208
	 *
2209
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2210
	 * @param array $array array( option name => option value, ... )
2211
	 */
2212
	public static function update_options( $array ) {
2213
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2214
		return Jetpack_Options::update_options( $array );
2215
	}
2216
2217
	/**
2218
	 * Deletes the given option.  May be passed multiple option names as an array.
2219
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2220
	 *
2221
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2222
	 * @param string|array $names
2223
	 */
2224
	public static function delete_option( $names ) {
2225
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2226
		return Jetpack_Options::delete_option( $names );
2227
	}
2228
2229
	/**
2230
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2231
	 *
2232
	 * Enters a user token into the user_tokens option
2233
	 *
2234
	 * @param int    $user_id The user id.
2235
	 * @param string $token The user token.
2236
	 * @param bool   $is_master_user Whether the user is the master user.
2237
	 * @return bool
2238
	 */
2239
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2240
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2241
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2242
	}
2243
2244
	/**
2245
	 * Returns an array of all PHP files in the specified absolute path.
2246
	 * Equivalent to glob( "$absolute_path/*.php" ).
2247
	 *
2248
	 * @param string $absolute_path The absolute path of the directory to search.
2249
	 * @return array Array of absolute paths to the PHP files.
2250
	 */
2251
	public static function glob_php( $absolute_path ) {
2252
		if ( function_exists( 'glob' ) ) {
2253
			return glob( "$absolute_path/*.php" );
2254
		}
2255
2256
		$absolute_path = untrailingslashit( $absolute_path );
2257
		$files         = array();
2258
		if ( ! $dir = @opendir( $absolute_path ) ) {
2259
			return $files;
2260
		}
2261
2262
		while ( false !== $file = readdir( $dir ) ) {
2263
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2264
				continue;
2265
			}
2266
2267
			$file = "$absolute_path/$file";
2268
2269
			if ( ! is_file( $file ) ) {
2270
				continue;
2271
			}
2272
2273
			$files[] = $file;
2274
		}
2275
2276
		closedir( $dir );
2277
2278
		return $files;
2279
	}
2280
2281
	public static function activate_new_modules( $redirect = false ) {
2282
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2283
			return;
2284
		}
2285
2286
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2287 View Code Duplication
		if ( ! $jetpack_old_version ) {
2288
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2289
			/** This action is documented in class.jetpack.php */
2290
			do_action( 'updating_jetpack_version', $version, false );
2291
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2292
		}
2293
2294
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2295
2296
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2297
			return;
2298
		}
2299
2300
		$active_modules     = self::get_active_modules();
2301
		$reactivate_modules = array();
2302
		foreach ( $active_modules as $active_module ) {
2303
			$module = self::get_module( $active_module );
2304
			if ( ! isset( $module['changed'] ) ) {
2305
				continue;
2306
			}
2307
2308
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2309
				continue;
2310
			}
2311
2312
			$reactivate_modules[] = $active_module;
2313
			self::deactivate_module( $active_module );
2314
		}
2315
2316
		$new_version = JETPACK__VERSION . ':' . time();
2317
		/** This action is documented in class.jetpack.php */
2318
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2319
		Jetpack_Options::update_options(
2320
			array(
2321
				'version'     => $new_version,
2322
				'old_version' => $jetpack_old_version,
2323
			)
2324
		);
2325
2326
		self::state( 'message', 'modules_activated' );
2327
2328
		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...
2329
2330
		if ( $redirect ) {
2331
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2332
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2333
				$page = $_GET['page'];
2334
			}
2335
2336
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2337
			exit;
2338
		}
2339
	}
2340
2341
	/**
2342
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2343
	 * Make sure to tuck away module "library" files in a sub-directory.
2344
	 */
2345
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2346
		static $modules = null;
2347
2348
		if ( ! isset( $modules ) ) {
2349
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2350
			// Use the cache if we're on the front-end and it's available...
2351
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2352
				$modules = $available_modules_option[ JETPACK__VERSION ];
2353
			} else {
2354
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2355
2356
				$modules = array();
2357
2358
				foreach ( $files as $file ) {
2359
					if ( ! $headers = self::get_module( $file ) ) {
2360
						continue;
2361
					}
2362
2363
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2364
				}
2365
2366
				Jetpack_Options::update_option(
2367
					'available_modules',
2368
					array(
2369
						JETPACK__VERSION => $modules,
2370
					)
2371
				);
2372
			}
2373
		}
2374
2375
		/**
2376
		 * Filters the array of modules available to be activated.
2377
		 *
2378
		 * @since 2.4.0
2379
		 *
2380
		 * @param array $modules Array of available modules.
2381
		 * @param string $min_version Minimum version number required to use modules.
2382
		 * @param string $max_version Maximum version number required to use modules.
2383
		 */
2384
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $min_version.

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...
2385
2386
		if ( ! $min_version && ! $max_version ) {
2387
			return array_keys( $mods );
2388
		}
2389
2390
		$r = array();
2391
		foreach ( $mods as $slug => $introduced ) {
2392
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2393
				continue;
2394
			}
2395
2396
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2397
				continue;
2398
			}
2399
2400
			$r[] = $slug;
2401
		}
2402
2403
		return $r;
2404
	}
2405
2406
	/**
2407
	 * Default modules loaded on activation.
2408
	 */
2409
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2410
		$return = array();
2411
2412
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2413
			$module_data = self::get_module( $module );
2414
2415
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2416
				case 'yes':
2417
					$return[] = $module;
2418
					break;
2419
				case 'public':
2420
					if ( Jetpack_Options::get_option( 'public' ) ) {
2421
						$return[] = $module;
2422
					}
2423
					break;
2424
				case 'no':
2425
				default:
2426
					break;
2427
			}
2428
		}
2429
		/**
2430
		 * Filters the array of default modules.
2431
		 *
2432
		 * @since 2.5.0
2433
		 *
2434
		 * @param array $return Array of default modules.
2435
		 * @param string $min_version Minimum version number required to use modules.
2436
		 * @param string $max_version Maximum version number required to use modules.
2437
		 */
2438
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $min_version.

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...
2439
	}
2440
2441
	/**
2442
	 * Checks activated modules during auto-activation to determine
2443
	 * if any of those modules are being deprecated.  If so, close
2444
	 * them out, and add any replacement modules.
2445
	 *
2446
	 * Runs at priority 99 by default.
2447
	 *
2448
	 * This is run late, so that it can still activate a module if
2449
	 * the new module is a replacement for another that the user
2450
	 * currently has active, even if something at the normal priority
2451
	 * would kibosh everything.
2452
	 *
2453
	 * @since 2.6
2454
	 * @uses jetpack_get_default_modules filter
2455
	 * @param array $modules
2456
	 * @return array
2457
	 */
2458
	function handle_deprecated_modules( $modules ) {
2459
		$deprecated_modules = array(
2460
			'debug'            => null,  // Closed out and moved to the debugger library.
2461
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2462
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2463
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2464
		);
2465
2466
		// Don't activate SSO if they never completed activating WPCC.
2467
		if ( self::is_module_active( 'wpcc' ) ) {
2468
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2469
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2470
				$deprecated_modules['wpcc'] = null;
2471
			}
2472
		}
2473
2474
		foreach ( $deprecated_modules as $module => $replacement ) {
2475
			if ( self::is_module_active( $module ) ) {
2476
				self::deactivate_module( $module );
2477
				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...
2478
					$modules[] = $replacement;
2479
				}
2480
			}
2481
		}
2482
2483
		return array_unique( $modules );
2484
	}
2485
2486
	/**
2487
	 * Checks activated plugins during auto-activation to determine
2488
	 * if any of those plugins are in the list with a corresponding module
2489
	 * that is not compatible with the plugin. The module will not be allowed
2490
	 * to auto-activate.
2491
	 *
2492
	 * @since 2.6
2493
	 * @uses jetpack_get_default_modules filter
2494
	 * @param array $modules
2495
	 * @return array
2496
	 */
2497
	function filter_default_modules( $modules ) {
2498
2499
		$active_plugins = self::get_active_plugins();
2500
2501
		if ( ! empty( $active_plugins ) ) {
2502
2503
			// For each module we'd like to auto-activate...
2504
			foreach ( $modules as $key => $module ) {
2505
				// If there are potential conflicts for it...
2506
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2507
					// For each potential conflict...
2508
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2509
						// If that conflicting plugin is active...
2510
						if ( in_array( $plugin, $active_plugins ) ) {
2511
							// Remove that item from being auto-activated.
2512
							unset( $modules[ $key ] );
2513
						}
2514
					}
2515
				}
2516
			}
2517
		}
2518
2519
		return $modules;
2520
	}
2521
2522
	/**
2523
	 * Extract a module's slug from its full path.
2524
	 */
2525
	public static function get_module_slug( $file ) {
2526
		return str_replace( '.php', '', basename( $file ) );
2527
	}
2528
2529
	/**
2530
	 * Generate a module's path from its slug.
2531
	 */
2532
	public static function get_module_path( $slug ) {
2533
		/**
2534
		 * Filters the path of a modules.
2535
		 *
2536
		 * @since 7.4.0
2537
		 *
2538
		 * @param array $return The absolute path to a module's root php file
2539
		 * @param string $slug The module slug
2540
		 */
2541
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $slug.

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...
2542
	}
2543
2544
	/**
2545
	 * Load module data from module file. Headers differ from WordPress
2546
	 * plugin headers to avoid them being identified as standalone
2547
	 * plugins on the WordPress plugins page.
2548
	 */
2549
	public static function get_module( $module ) {
2550
		$headers = array(
2551
			'name'                      => 'Module Name',
2552
			'description'               => 'Module Description',
2553
			'sort'                      => 'Sort Order',
2554
			'recommendation_order'      => 'Recommendation Order',
2555
			'introduced'                => 'First Introduced',
2556
			'changed'                   => 'Major Changes In',
2557
			'deactivate'                => 'Deactivate',
2558
			'free'                      => 'Free',
2559
			'requires_connection'       => 'Requires Connection',
2560
			'auto_activate'             => 'Auto Activate',
2561
			'module_tags'               => 'Module Tags',
2562
			'feature'                   => 'Feature',
2563
			'additional_search_queries' => 'Additional Search Queries',
2564
			'plan_classes'              => 'Plans',
2565
		);
2566
2567
		$file = self::get_module_path( self::get_module_slug( $module ) );
2568
2569
		$mod = self::get_file_data( $file, $headers );
2570
		if ( empty( $mod['name'] ) ) {
2571
			return false;
2572
		}
2573
2574
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2575
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2576
		$mod['deactivate']           = empty( $mod['deactivate'] );
2577
		$mod['free']                 = empty( $mod['free'] );
2578
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2579
2580
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2581
			$mod['auto_activate'] = 'No';
2582
		} else {
2583
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2584
		}
2585
2586
		if ( $mod['module_tags'] ) {
2587
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2588
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2589
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2590
		} else {
2591
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2592
		}
2593
2594 View Code Duplication
		if ( $mod['plan_classes'] ) {
2595
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2596
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2597
		} else {
2598
			$mod['plan_classes'] = array( 'free' );
2599
		}
2600
2601 View Code Duplication
		if ( $mod['feature'] ) {
2602
			$mod['feature'] = explode( ',', $mod['feature'] );
2603
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2604
		} else {
2605
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2606
		}
2607
2608
		/**
2609
		 * Filters the feature array on a module.
2610
		 *
2611
		 * This filter allows you to control where each module is filtered: Recommended,
2612
		 * and the default "Other" listing.
2613
		 *
2614
		 * @since 3.5.0
2615
		 *
2616
		 * @param array   $mod['feature'] The areas to feature this module:
2617
		 *     'Recommended' shows on the main Jetpack admin screen.
2618
		 *     'Other' should be the default if no other value is in the array.
2619
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2620
		 * @param array   $mod All the currently assembled module data.
2621
		 */
2622
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $module.

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...
2623
2624
		/**
2625
		 * Filter the returned data about a module.
2626
		 *
2627
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2628
		 * so please be careful.
2629
		 *
2630
		 * @since 3.6.0
2631
		 *
2632
		 * @param array   $mod    The details of the requested module.
2633
		 * @param string  $module The slug of the module, e.g. sharedaddy
2634
		 * @param string  $file   The path to the module source file.
2635
		 */
2636
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $module.

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...
2637
	}
2638
2639
	/**
2640
	 * Like core's get_file_data implementation, but caches the result.
2641
	 */
2642
	public static function get_file_data( $file, $headers ) {
2643
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2644
		$file_name = basename( $file );
2645
2646
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2647
2648
		$file_data_option = get_transient( $cache_key );
2649
2650
		if ( ! is_array( $file_data_option ) ) {
2651
			delete_transient( $cache_key );
2652
			$file_data_option = false;
2653
		}
2654
2655
		if ( false === $file_data_option ) {
2656
			$file_data_option = array();
2657
		}
2658
2659
		$key           = md5( $file_name . serialize( $headers ) );
2660
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2661
2662
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2663
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2664
			return $file_data_option[ $key ];
2665
		}
2666
2667
		$data = get_file_data( $file, $headers );
2668
2669
		$file_data_option[ $key ] = $data;
2670
2671
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2672
2673
		return $data;
2674
	}
2675
2676
2677
	/**
2678
	 * Return translated module tag.
2679
	 *
2680
	 * @param string $tag Tag as it appears in each module heading.
2681
	 *
2682
	 * @return mixed
2683
	 */
2684
	public static function translate_module_tag( $tag ) {
2685
		return jetpack_get_module_i18n_tag( $tag );
2686
	}
2687
2688
	/**
2689
	 * Get i18n strings as a JSON-encoded string
2690
	 *
2691
	 * @return string The locale as JSON
2692
	 */
2693
	public static function get_i18n_data_json() {
2694
2695
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2696
		// JSON files with the file they should be included for. This is an md5
2697
		// of '_inc/build/admin.js'.
2698
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2699
2700
		$i18n_json =
2701
				   JETPACK__PLUGIN_DIR
2702
				   . 'languages/json/jetpack-'
2703
				   . get_user_locale()
2704
				   . '-'
2705
				   . $path_md5
2706
				   . '.json';
2707
2708
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2709
			$locale_data = @file_get_contents( $i18n_json );
2710
			if ( $locale_data ) {
2711
				return $locale_data;
2712
			}
2713
		}
2714
2715
		// Return valid empty Jed locale
2716
		return '{ "locale_data": { "messages": { "": {} } } }';
2717
	}
2718
2719
	/**
2720
	 * Add locale data setup to wp-i18n
2721
	 *
2722
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2723
	 *
2724
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2725
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2726
	 *
2727
	 * This method provides a safe way to request the setup multiple times but add the script at
2728
	 * most once.
2729
	 *
2730
	 * @since 6.7.0
2731
	 *
2732
	 * @return void
2733
	 */
2734
	public static function setup_wp_i18n_locale_data() {
2735
		static $script_added = false;
2736
		if ( ! $script_added ) {
2737
			$script_added = true;
2738
			wp_add_inline_script(
2739
				'wp-i18n',
2740
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2741
			);
2742
		}
2743
	}
2744
2745
	/**
2746
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2747
	 *
2748
	 * @since 3.9.2
2749
	 *
2750
	 * @param array $modules
2751
	 *
2752
	 * @return string|void
2753
	 */
2754
	public static function get_translated_modules( $modules ) {
2755
		foreach ( $modules as $index => $module ) {
2756
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2757
			if ( isset( $module['name'] ) ) {
2758
				$modules[ $index ]['name'] = $i18n_module['name'];
2759
			}
2760
			if ( isset( $module['description'] ) ) {
2761
				$modules[ $index ]['description']       = $i18n_module['description'];
2762
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2763
			}
2764
		}
2765
		return $modules;
2766
	}
2767
2768
	/**
2769
	 * Get a list of activated modules as an array of module slugs.
2770
	 */
2771
	public static function get_active_modules() {
2772
		$active = Jetpack_Options::get_option( 'active_modules' );
2773
2774
		if ( ! is_array( $active ) ) {
2775
			$active = array();
2776
		}
2777
2778
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2779
			$active[] = 'vaultpress';
2780
		} else {
2781
			$active = array_diff( $active, array( 'vaultpress' ) );
2782
		}
2783
2784
		// If protect is active on the main site of a multisite, it should be active on all sites.
2785
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2786
			$active[] = 'protect';
2787
		}
2788
2789
		/**
2790
		 * Allow filtering of the active modules.
2791
		 *
2792
		 * Gives theme and plugin developers the power to alter the modules that
2793
		 * are activated on the fly.
2794
		 *
2795
		 * @since 5.8.0
2796
		 *
2797
		 * @param array $active Array of active module slugs.
2798
		 */
2799
		$active = apply_filters( 'jetpack_active_modules', $active );
2800
2801
		return array_unique( $active );
2802
	}
2803
2804
	/**
2805
	 * Check whether or not a Jetpack module is active.
2806
	 *
2807
	 * @param string $module The slug of a Jetpack module.
2808
	 * @return bool
2809
	 *
2810
	 * @static
2811
	 */
2812
	public static function is_module_active( $module ) {
2813
		return in_array( $module, self::get_active_modules() );
2814
	}
2815
2816
	public static function is_module( $module ) {
2817
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2818
	}
2819
2820
	/**
2821
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2822
	 *
2823
	 * @param bool $catch True to start catching, False to stop.
2824
	 *
2825
	 * @static
2826
	 */
2827
	public static function catch_errors( $catch ) {
2828
		static $display_errors, $error_reporting;
2829
2830
		if ( $catch ) {
2831
			$display_errors  = @ini_set( 'display_errors', 1 );
2832
			$error_reporting = @error_reporting( E_ALL );
2833
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2834
		} else {
2835
			@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...
2836
			@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...
2837
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2838
		}
2839
	}
2840
2841
	/**
2842
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2843
	 */
2844
	public static function catch_errors_on_shutdown() {
2845
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2846
	}
2847
2848
	/**
2849
	 * Rewrite any string to make paths easier to read.
2850
	 *
2851
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2852
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2853
	 *
2854
	 * @param $string
2855
	 * @return mixed
2856
	 */
2857
	public static function alias_directories( $string ) {
2858
		// ABSPATH has a trailing slash.
2859
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2860
		// WP_CONTENT_DIR does not have a trailing slash.
2861
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2862
2863
		return $string;
2864
	}
2865
2866
	public static function activate_default_modules(
2867
		$min_version = false,
2868
		$max_version = false,
2869
		$other_modules = array(),
2870
		$redirect = null,
2871
		$send_state_messages = null
2872
	) {
2873
		$jetpack = self::init();
2874
2875
		if ( is_null( $redirect ) ) {
2876
			if (
2877
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2878
			||
2879
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2880
			||
2881
				( defined( 'WP_CLI' ) && WP_CLI )
2882
			||
2883
				( defined( 'DOING_CRON' ) && DOING_CRON )
2884
			||
2885
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2886
			) {
2887
				$redirect = false;
2888
			} elseif ( is_admin() ) {
2889
				$redirect = true;
2890
			} else {
2891
				$redirect = false;
2892
			}
2893
		}
2894
2895
		if ( is_null( $send_state_messages ) ) {
2896
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2897
		}
2898
2899
		$modules = self::get_default_modules( $min_version, $max_version );
2900
		$modules = array_merge( $other_modules, $modules );
2901
2902
		// Look for standalone plugins and disable if active.
2903
2904
		$to_deactivate = array();
2905
		foreach ( $modules as $module ) {
2906
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2907
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2908
			}
2909
		}
2910
2911
		$deactivated = array();
2912
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2913
			list( $probable_file, $probable_title ) = $deactivate_me;
2914
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2915
				$deactivated[] = $module;
2916
			}
2917
		}
2918
2919
		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...
2920
			if ( $send_state_messages ) {
2921
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2922
			}
2923
2924
			if ( $redirect ) {
2925
				$url = add_query_arg(
2926
					array(
2927
						'action'   => 'activate_default_modules',
2928
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2929
					),
2930
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2931
				);
2932
				wp_safe_redirect( $url );
2933
				exit;
2934
			}
2935
		}
2936
2937
		/**
2938
		 * Fires before default modules are activated.
2939
		 *
2940
		 * @since 1.9.0
2941
		 *
2942
		 * @param string $min_version Minimum version number required to use modules.
2943
		 * @param string $max_version Maximum version number required to use modules.
2944
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2945
		 */
2946
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2947
2948
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2949
		if ( $send_state_messages ) {
2950
			self::restate();
2951
			self::catch_errors( true );
2952
		}
2953
2954
		$active = self::get_active_modules();
2955
2956
		foreach ( $modules as $module ) {
2957
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2958
				$active[] = $module;
2959
				self::update_active_modules( $active );
2960
				continue;
2961
			}
2962
2963
			if ( $send_state_messages && in_array( $module, $active ) ) {
2964
				$module_info = self::get_module( $module );
2965 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2966
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2967
					if ( $active_state = self::state( $state ) ) {
2968
						$active_state = explode( ',', $active_state );
2969
					} else {
2970
						$active_state = array();
2971
					}
2972
					$active_state[] = $module;
2973
					self::state( $state, implode( ',', $active_state ) );
2974
				}
2975
				continue;
2976
			}
2977
2978
			$file = self::get_module_path( $module );
2979
			if ( ! file_exists( $file ) ) {
2980
				continue;
2981
			}
2982
2983
			// we'll override this later if the plugin can be included without fatal error
2984
			if ( $redirect ) {
2985
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2986
			}
2987
2988
			if ( $send_state_messages ) {
2989
				self::state( 'error', 'module_activation_failed' );
2990
				self::state( 'module', $module );
2991
			}
2992
2993
			ob_start();
2994
			require_once $file;
2995
2996
			$active[] = $module;
2997
2998 View Code Duplication
			if ( $send_state_messages ) {
2999
3000
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3001
				if ( $active_state = self::state( $state ) ) {
3002
					$active_state = explode( ',', $active_state );
3003
				} else {
3004
					$active_state = array();
3005
				}
3006
				$active_state[] = $module;
3007
				self::state( $state, implode( ',', $active_state ) );
3008
			}
3009
3010
			self::update_active_modules( $active );
3011
3012
			ob_end_clean();
3013
		}
3014
3015
		if ( $send_state_messages ) {
3016
			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...
3017
			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...
3018
		}
3019
3020
		self::catch_errors( false );
3021
		/**
3022
		 * Fires when default modules are activated.
3023
		 *
3024
		 * @since 1.9.0
3025
		 *
3026
		 * @param string $min_version Minimum version number required to use modules.
3027
		 * @param string $max_version Maximum version number required to use modules.
3028
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3029
		 */
3030
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3031
	}
3032
3033
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3034
		/**
3035
		 * Fires before a module is activated.
3036
		 *
3037
		 * @since 2.6.0
3038
		 *
3039
		 * @param string $module Module slug.
3040
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3041
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3042
		 */
3043
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3044
3045
		$jetpack = self::init();
3046
3047
		if ( ! strlen( $module ) ) {
3048
			return false;
3049
		}
3050
3051
		if ( ! self::is_module( $module ) ) {
3052
			return false;
3053
		}
3054
3055
		// If it's already active, then don't do it again
3056
		$active = self::get_active_modules();
3057
		foreach ( $active as $act ) {
3058
			if ( $act == $module ) {
3059
				return true;
3060
			}
3061
		}
3062
3063
		$module_data = self::get_module( $module );
3064
3065
		$is_development_mode = ( new Status() )->is_development_mode();
3066
		if ( ! self::is_active() ) {
3067
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3068
				return false;
3069
			}
3070
3071
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3072
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3073
				return false;
3074
			}
3075
		}
3076
3077
		// Check and see if the old plugin is active
3078
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3079
			// Deactivate the old plugin
3080
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3081
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3082
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3083
				self::state( 'deactivated_plugins', $module );
3084
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3085
				exit;
3086
			}
3087
		}
3088
3089
		// Protect won't work with mis-configured IPs
3090
		if ( 'protect' === $module ) {
3091
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3092
			if ( ! jetpack_protect_get_ip() ) {
3093
				self::state( 'message', 'protect_misconfigured_ip' );
3094
				return false;
3095
			}
3096
		}
3097
3098
		if ( ! Jetpack_Plan::supports( $module ) ) {
3099
			return false;
3100
		}
3101
3102
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3103
		self::state( 'module', $module );
3104
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3105
3106
		self::catch_errors( true );
3107
		ob_start();
3108
		require self::get_module_path( $module );
3109
		/** This action is documented in class.jetpack.php */
3110
		do_action( 'jetpack_activate_module', $module );
3111
		$active[] = $module;
3112
		self::update_active_modules( $active );
3113
3114
		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...
3115
		ob_end_clean();
3116
		self::catch_errors( false );
3117
3118
		if ( $redirect ) {
3119
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3120
		}
3121
		if ( $exit ) {
3122
			exit;
3123
		}
3124
		return true;
3125
	}
3126
3127
	function activate_module_actions( $module ) {
3128
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3129
	}
3130
3131
	public static function deactivate_module( $module ) {
3132
		/**
3133
		 * Fires when a module is deactivated.
3134
		 *
3135
		 * @since 1.9.0
3136
		 *
3137
		 * @param string $module Module slug.
3138
		 */
3139
		do_action( 'jetpack_pre_deactivate_module', $module );
3140
3141
		$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...
3142
3143
		$active = self::get_active_modules();
3144
		$new    = array_filter( array_diff( $active, (array) $module ) );
3145
3146
		return self::update_active_modules( $new );
3147
	}
3148
3149
	public static function enable_module_configurable( $module ) {
3150
		$module = self::get_module_slug( $module );
3151
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3152
	}
3153
3154
	/**
3155
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3156
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3157
	 *
3158
	 * @param string $module Module slug
3159
	 * @return string $url module configuration URL
3160
	 */
3161
	public static function module_configuration_url( $module ) {
3162
		$module      = self::get_module_slug( $module );
3163
		$default_url = self::admin_url() . "#/settings?term=$module";
3164
		/**
3165
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3166
		 *
3167
		 * @since 6.9.0
3168
		 *
3169
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3170
		 */
3171
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3172
3173
		return $url;
3174
	}
3175
3176
	/* Installation */
3177
	public static function bail_on_activation( $message, $deactivate = true ) {
3178
		?>
3179
<!doctype html>
3180
<html>
3181
<head>
3182
<meta charset="<?php bloginfo( 'charset' ); ?>">
3183
<style>
3184
* {
3185
	text-align: center;
3186
	margin: 0;
3187
	padding: 0;
3188
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3189
}
3190
p {
3191
	margin-top: 1em;
3192
	font-size: 18px;
3193
}
3194
</style>
3195
<body>
3196
<p><?php echo esc_html( $message ); ?></p>
3197
</body>
3198
</html>
3199
		<?php
3200
		if ( $deactivate ) {
3201
			$plugins = get_option( 'active_plugins' );
3202
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3203
			$update  = false;
3204
			foreach ( $plugins as $i => $plugin ) {
3205
				if ( $plugin === $jetpack ) {
3206
					$plugins[ $i ] = false;
3207
					$update        = true;
3208
				}
3209
			}
3210
3211
			if ( $update ) {
3212
				update_option( 'active_plugins', array_filter( $plugins ) );
3213
			}
3214
		}
3215
		exit;
3216
	}
3217
3218
	/**
3219
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3220
	 *
3221
	 * @static
3222
	 */
3223
	public static function plugin_activation( $network_wide ) {
3224
		Jetpack_Options::update_option( 'activated', 1 );
3225
3226
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3227
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3228
		}
3229
3230
		if ( $network_wide ) {
3231
			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...
3232
		}
3233
3234
		// For firing one-off events (notices) immediately after activation
3235
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3236
3237
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3238
3239
		Health::on_jetpack_activated();
3240
3241
		self::plugin_initialize();
3242
	}
3243
3244
	public static function get_activation_source( $referer_url ) {
3245
3246
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3247
			return array( 'wp-cli', null );
3248
		}
3249
3250
		$referer = wp_parse_url( $referer_url );
3251
3252
		$source_type  = 'unknown';
3253
		$source_query = null;
3254
3255
		if ( ! is_array( $referer ) ) {
3256
			return array( $source_type, $source_query );
3257
		}
3258
3259
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3260
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3261
3262
		if ( isset( $referer['query'] ) ) {
3263
			parse_str( $referer['query'], $query_parts );
3264
		} else {
3265
			$query_parts = array();
3266
		}
3267
3268
		if ( $plugins_path === $referer['path'] ) {
3269
			$source_type = 'list';
3270
		} elseif ( $plugins_install_path === $referer['path'] ) {
3271
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3272
			switch ( $tab ) {
3273
				case 'popular':
3274
					$source_type = 'popular';
3275
					break;
3276
				case 'recommended':
3277
					$source_type = 'recommended';
3278
					break;
3279
				case 'favorites':
3280
					$source_type = 'favorites';
3281
					break;
3282
				case 'search':
3283
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3284
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3285
					break;
3286
				default:
3287
					$source_type = 'featured';
3288
			}
3289
		}
3290
3291
		return array( $source_type, $source_query );
3292
	}
3293
3294
	/**
3295
	 * Runs before bumping version numbers up to a new version
3296
	 *
3297
	 * @param string $version    Version:timestamp.
3298
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3299
	 */
3300
	public static function do_version_bump( $version, $old_version ) {
3301
		if ( $old_version ) { // For existing Jetpack installations.
3302
3303
			// If a front end page is visited after the update, the 'wp' action will fire.
3304
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3305
3306
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3307
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3308
		}
3309
	}
3310
3311
	/**
3312
	 * Sets the display_update_modal state.
3313
	 */
3314
	public static function set_update_modal_display() {
3315
		self::state( 'display_update_modal', 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...
3316
	}
3317
3318
	/**
3319
	 * Sets the internal version number and activation state.
3320
	 *
3321
	 * @static
3322
	 */
3323
	public static function plugin_initialize() {
3324
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3325
			Jetpack_Options::update_option( 'activated', 2 );
3326
		}
3327
3328 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3329
			$version = $old_version = JETPACK__VERSION . ':' . time();
3330
			/** This action is documented in class.jetpack.php */
3331
			do_action( 'updating_jetpack_version', $version, false );
3332
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3333
		}
3334
3335
		self::load_modules();
3336
3337
		Jetpack_Options::delete_option( 'do_activate' );
3338
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3339
	}
3340
3341
	/**
3342
	 * Removes all connection options
3343
	 *
3344
	 * @static
3345
	 */
3346
	public static function plugin_deactivation() {
3347
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3348
		$tracking = new Tracking();
3349
		$tracking->record_user_event( 'deactivate_plugin', array() );
3350
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3351
			Jetpack_Network::init()->deactivate();
3352
		} else {
3353
			self::disconnect( false );
3354
			// Jetpack_Heartbeat::init()->deactivate();
3355
		}
3356
	}
3357
3358
	/**
3359
	 * Disconnects from the Jetpack servers.
3360
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3361
	 *
3362
	 * @static
3363
	 */
3364
	public static function disconnect( $update_activated_state = true ) {
3365
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3366
		$connection = self::connection();
3367
		$connection->clean_nonces( true );
3368
3369
		// If the site is in an IDC because sync is not allowed,
3370
		// let's make sure to not disconnect the production site.
3371
		if ( ! self::validate_sync_error_idc_option() ) {
3372
			$tracking = new Tracking();
3373
			$tracking->record_user_event( 'disconnect_site', array() );
3374
3375
			$connection->disconnect_site_wpcom();
3376
		}
3377
3378
		$connection->delete_all_connection_tokens();
3379
		Jetpack_IDC::clear_all_idc_options();
3380
3381
		if ( $update_activated_state ) {
3382
			Jetpack_Options::update_option( 'activated', 4 );
3383
		}
3384
3385
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3386
			// Check then record unique disconnection if site has never been disconnected previously
3387
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3388
				$jetpack_unique_connection['disconnected'] = 1;
3389
			} else {
3390
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3391
					// track unique disconnect
3392
					$jetpack = self::init();
3393
3394
					$jetpack->stat( 'connections', 'unique-disconnect' );
3395
					$jetpack->do_stats( 'server_side' );
3396
				}
3397
				// increment number of times disconnected
3398
				$jetpack_unique_connection['disconnected'] += 1;
3399
			}
3400
3401
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3402
		}
3403
3404
		// Delete all the sync related data. Since it could be taking up space.
3405
		Sender::get_instance()->uninstall();
3406
3407
		// Disable the Heartbeat cron
3408
		Jetpack_Heartbeat::init()->deactivate();
3409
	}
3410
3411
	/**
3412
	 * Unlinks the current user from the linked WordPress.com user.
3413
	 *
3414
	 * @deprecated since 7.7
3415
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3416
	 *
3417
	 * @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...
3418
	 * @return Boolean Whether the disconnection of the user was successful.
3419
	 */
3420
	public static function unlink_user( $user_id = null ) {
3421
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3422
		return Connection_Manager::disconnect_user( $user_id );
3423
	}
3424
3425
	/**
3426
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3427
	 */
3428
	public static function try_registration() {
3429
		$terms_of_service = new Terms_Of_Service();
3430
		// The user has agreed to the TOS at some point by now.
3431
		$terms_of_service->agree();
3432
3433
		// Let's get some testing in beta versions and such.
3434
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3435
			// Before attempting to connect, let's make sure that the domains are viable.
3436
			$domains_to_check = array_unique(
3437
				array(
3438
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3439
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3440
				)
3441
			);
3442
			foreach ( $domains_to_check as $domain ) {
3443
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
$domain is of type array<string,string>|false, but the function expects a string.

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...
3444
				if ( is_wp_error( $result ) ) {
3445
					return $result;
3446
				}
3447
			}
3448
		}
3449
3450
		$result = self::register();
3451
3452
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3453
		if ( ! $result || is_wp_error( $result ) ) {
3454
			return $result;
3455
		} else {
3456
			return true;
3457
		}
3458
	}
3459
3460
	/**
3461
	 * Tracking an internal event log. Try not to put too much chaff in here.
3462
	 *
3463
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3464
	 */
3465
	public static function log( $code, $data = null ) {
3466
		// only grab the latest 200 entries
3467
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3468
3469
		// Append our event to the log
3470
		$log_entry = array(
3471
			'time'    => time(),
3472
			'user_id' => get_current_user_id(),
3473
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3474
			'code'    => $code,
3475
		);
3476
		// Don't bother storing it unless we've got some.
3477
		if ( ! is_null( $data ) ) {
3478
			$log_entry['data'] = $data;
3479
		}
3480
		$log[] = $log_entry;
3481
3482
		// Try add_option first, to make sure it's not autoloaded.
3483
		// @todo: Add an add_option method to Jetpack_Options
3484
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3485
			Jetpack_Options::update_option( 'log', $log );
3486
		}
3487
3488
		/**
3489
		 * Fires when Jetpack logs an internal event.
3490
		 *
3491
		 * @since 3.0.0
3492
		 *
3493
		 * @param array $log_entry {
3494
		 *  Array of details about the log entry.
3495
		 *
3496
		 *  @param string time Time of the event.
3497
		 *  @param int user_id ID of the user who trigerred the event.
3498
		 *  @param int blog_id Jetpack Blog ID.
3499
		 *  @param string code Unique name for the event.
3500
		 *  @param string data Data about the event.
3501
		 * }
3502
		 */
3503
		do_action( 'jetpack_log_entry', $log_entry );
3504
	}
3505
3506
	/**
3507
	 * Get the internal event log.
3508
	 *
3509
	 * @param $event (string) - only return the specific log events
3510
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3511
	 *
3512
	 * @return array of log events || WP_Error for invalid params
3513
	 */
3514
	public static function get_log( $event = false, $num = false ) {
3515
		if ( $event && ! is_string( $event ) ) {
3516
			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...
3517
		}
3518
3519
		if ( $num && ! is_numeric( $num ) ) {
3520
			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...
3521
		}
3522
3523
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3524
3525
		// If nothing set - act as it did before, otherwise let's start customizing the output
3526
		if ( ! $num && ! $event ) {
3527
			return $entire_log;
3528
		} else {
3529
			$entire_log = array_reverse( $entire_log );
3530
		}
3531
3532
		$custom_log_output = array();
3533
3534
		if ( $event ) {
3535
			foreach ( $entire_log as $log_event ) {
3536
				if ( $event == $log_event['code'] ) {
3537
					$custom_log_output[] = $log_event;
3538
				}
3539
			}
3540
		} else {
3541
			$custom_log_output = $entire_log;
3542
		}
3543
3544
		if ( $num ) {
3545
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3546
		}
3547
3548
		return $custom_log_output;
3549
	}
3550
3551
	/**
3552
	 * Log modification of important settings.
3553
	 */
3554
	public static function log_settings_change( $option, $old_value, $value ) {
3555
		switch ( $option ) {
3556
			case 'jetpack_sync_non_public_post_stati':
3557
				self::log( $option, $value );
3558
				break;
3559
		}
3560
	}
3561
3562
	/**
3563
	 * Return stat data for WPCOM sync
3564
	 */
3565
	public static function get_stat_data( $encode = true, $extended = true ) {
3566
		$data = Jetpack_Heartbeat::generate_stats_array();
3567
3568
		if ( $extended ) {
3569
			$additional_data = self::get_additional_stat_data();
3570
			$data            = array_merge( $data, $additional_data );
3571
		}
3572
3573
		if ( $encode ) {
3574
			return json_encode( $data );
3575
		}
3576
3577
		return $data;
3578
	}
3579
3580
	/**
3581
	 * Get additional stat data to sync to WPCOM
3582
	 */
3583
	public static function get_additional_stat_data( $prefix = '' ) {
3584
		$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...
3585
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3586
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3587
		$return[ "{$prefix}site-count" ]    = 0;
3588
3589
		if ( function_exists( 'get_blog_count' ) ) {
3590
			$return[ "{$prefix}site-count" ] = get_blog_count();
3591
		}
3592
		return $return;
3593
	}
3594
3595
	private static function get_site_user_count() {
3596
		global $wpdb;
3597
3598
		if ( function_exists( 'wp_is_large_network' ) ) {
3599
			if ( wp_is_large_network( 'users' ) ) {
3600
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3601
			}
3602
		}
3603
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3604
			// It wasn't there, so regenerate the data and save the transient
3605
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3606
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3607
		}
3608
		return $user_count;
3609
	}
3610
3611
	/* Admin Pages */
3612
3613
	function admin_init() {
3614
		// If the plugin is not connected, display a connect message.
3615
		if (
3616
			// the plugin was auto-activated and needs its candy
3617
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3618
		||
3619
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3620
			! Jetpack_Options::get_option( 'activated' )
3621
		) {
3622
			self::plugin_initialize();
3623
		}
3624
3625
		$is_development_mode = ( new Status() )->is_development_mode();
3626
		if ( ! self::is_active() && ! $is_development_mode ) {
3627
			Jetpack_Connection_Banner::init();
3628
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3629
			// Upgrade: 1.1 -> 1.1.1
3630
			// Check and see if host can verify the Jetpack servers' SSL certificate
3631
			$args       = array();
3632
			$connection = self::connection();
3633
			Client::_wp_remote_request(
3634
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3635
				$args,
3636
				true
3637
			);
3638
		}
3639
3640
		Jetpack_Wizard_Banner::init();
3641
3642
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3643
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3644
		}
3645
3646
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3647
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3648
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3649
3650
		if ( self::is_active() || $is_development_mode ) {
3651
			// Artificially throw errors in certain whitelisted cases during plugin activation
3652
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3653
		}
3654
3655
		// Add custom column in wp-admin/users.php to show whether user is linked.
3656
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3657
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3658
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3659
	}
3660
3661
	function admin_body_class( $admin_body_class = '' ) {
3662
		$classes = explode( ' ', trim( $admin_body_class ) );
3663
3664
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3665
3666
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3667
		return " $admin_body_class ";
3668
	}
3669
3670
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3671
		return $admin_body_class . ' jetpack-pagestyles ';
3672
	}
3673
3674
	/**
3675
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3676
	 * This function artificially throws errors for such cases (whitelisted).
3677
	 *
3678
	 * @param string $plugin The activated plugin.
3679
	 */
3680
	function throw_error_on_activate_plugin( $plugin ) {
3681
		$active_modules = self::get_active_modules();
3682
3683
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3684
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3685
			$throw = false;
3686
3687
			// Try and make sure it really was the stats plugin
3688
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3689
				if ( 'stats.php' == basename( $plugin ) ) {
3690
					$throw = true;
3691
				}
3692
			} else {
3693
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3694
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3695
					$throw = true;
3696
				}
3697
			}
3698
3699
			if ( $throw ) {
3700
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3701
			}
3702
		}
3703
	}
3704
3705
	function intercept_plugin_error_scrape_init() {
3706
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3707
	}
3708
3709
	function intercept_plugin_error_scrape( $action, $result ) {
3710
		if ( ! $result ) {
3711
			return;
3712
		}
3713
3714
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3715
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3716
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3717
			}
3718
		}
3719
	}
3720
3721
	/**
3722
	 * Register the remote file upload request handlers, if needed.
3723
	 *
3724
	 * @access public
3725
	 */
3726
	public function add_remote_request_handlers() {
3727
		// Remote file uploads are allowed only via AJAX requests.
3728
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3729
			return;
3730
		}
3731
3732
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3733
		$remote_request_actions = array(
3734
			'jetpack_upload_file',
3735
			'jetpack_update_file',
3736
		);
3737
3738
		// phpcs:ignore WordPress.Security.NonceVerification
3739
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3740
			return;
3741
		}
3742
3743
		// Require Jetpack authentication for the remote file upload AJAX requests.
3744
		if ( ! $this->connection_manager ) {
3745
			$this->connection_manager = new Connection_Manager();
3746
		}
3747
3748
		$this->connection_manager->require_jetpack_authentication();
3749
3750
		// Register the remote file upload AJAX handlers.
3751
		foreach ( $remote_request_actions as $action ) {
3752
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3753
		}
3754
	}
3755
3756
	/**
3757
	 * Handler for Jetpack remote file uploads.
3758
	 *
3759
	 * @access public
3760
	 */
3761
	public function remote_request_handlers() {
3762
		$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...
3763
3764
		switch ( current_filter() ) {
3765
			case 'wp_ajax_nopriv_jetpack_upload_file':
3766
				$response = $this->upload_handler();
3767
				break;
3768
3769
			case 'wp_ajax_nopriv_jetpack_update_file':
3770
				$response = $this->upload_handler( true );
3771
				break;
3772
			default:
3773
				$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...
3774
				break;
3775
		}
3776
3777
		if ( ! $response ) {
3778
			$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...
3779
		}
3780
3781
		if ( is_wp_error( $response ) ) {
3782
			$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...
3783
			$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...
3784
			$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...
3785
3786
			if ( ! is_int( $status_code ) ) {
3787
				$status_code = 400;
3788
			}
3789
3790
			status_header( $status_code );
3791
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3792
		}
3793
3794
		status_header( 200 );
3795
		if ( true === $response ) {
3796
			exit;
3797
		}
3798
3799
		die( json_encode( (object) $response ) );
3800
	}
3801
3802
	/**
3803
	 * Uploads a file gotten from the global $_FILES.
3804
	 * If `$update_media_item` is true and `post_id` is defined
3805
	 * the attachment file of the media item (gotten through of the post_id)
3806
	 * will be updated instead of add a new one.
3807
	 *
3808
	 * @param  boolean $update_media_item - update media attachment
3809
	 * @return array - An array describing the uploadind files process
3810
	 */
3811
	function upload_handler( $update_media_item = false ) {
3812
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3813
			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...
3814
		}
3815
3816
		$user = wp_authenticate( '', '' );
3817
		if ( ! $user || is_wp_error( $user ) ) {
3818
			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...
3819
		}
3820
3821
		wp_set_current_user( $user->ID );
3822
3823
		if ( ! current_user_can( 'upload_files' ) ) {
3824
			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...
3825
		}
3826
3827
		if ( empty( $_FILES ) ) {
3828
			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...
3829
		}
3830
3831
		foreach ( array_keys( $_FILES ) as $files_key ) {
3832
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3833
				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...
3834
			}
3835
		}
3836
3837
		$media_keys = array_keys( $_FILES['media'] );
3838
3839
		$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...
3840
		if ( ! $token || is_wp_error( $token ) ) {
3841
			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...
3842
		}
3843
3844
		$uploaded_files = array();
3845
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3846
		unset( $GLOBALS['post'] );
3847
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3848
			$file = array();
3849
			foreach ( $media_keys as $media_key ) {
3850
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3851
			}
3852
3853
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3854
3855
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3856
			if ( $hmac_provided !== $hmac_file ) {
3857
				$uploaded_files[ $index ] = (object) array(
3858
					'error'             => 'invalid_hmac',
3859
					'error_description' => 'The corresponding HMAC for this file does not match',
3860
				);
3861
				continue;
3862
			}
3863
3864
			$_FILES['.jetpack.upload.'] = $file;
3865
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3866
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3867
				$post_id = 0;
3868
			}
3869
3870
			if ( $update_media_item ) {
3871
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3872
					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...
3873
				}
3874
3875
				$media_array = $_FILES['media'];
3876
3877
				$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...
3878
				$file_array['type']     = $media_array['type'][0];
3879
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3880
				$file_array['error']    = $media_array['error'][0];
3881
				$file_array['size']     = $media_array['size'][0];
3882
3883
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3884
3885
				if ( is_wp_error( $edited_media_item ) ) {
3886
					return $edited_media_item;
3887
				}
3888
3889
				$response = (object) array(
3890
					'id'   => (string) $post_id,
3891
					'file' => (string) $edited_media_item->post_title,
3892
					'url'  => (string) wp_get_attachment_url( $post_id ),
3893
					'type' => (string) $edited_media_item->post_mime_type,
3894
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3895
				);
3896
3897
				return (array) array( $response );
3898
			}
3899
3900
			$attachment_id = media_handle_upload(
3901
				'.jetpack.upload.',
3902
				$post_id,
3903
				array(),
3904
				array(
3905
					'action' => 'jetpack_upload_file',
3906
				)
3907
			);
3908
3909
			if ( ! $attachment_id ) {
3910
				$uploaded_files[ $index ] = (object) array(
3911
					'error'             => 'unknown',
3912
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3913
				);
3914
			} elseif ( is_wp_error( $attachment_id ) ) {
3915
				$uploaded_files[ $index ] = (object) array(
3916
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3917
					'error_description' => $attachment_id->get_error_message(),
3918
				);
3919
			} else {
3920
				$attachment               = get_post( $attachment_id );
3921
				$uploaded_files[ $index ] = (object) array(
3922
					'id'   => (string) $attachment_id,
3923
					'file' => $attachment->post_title,
3924
					'url'  => wp_get_attachment_url( $attachment_id ),
3925
					'type' => $attachment->post_mime_type,
3926
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3927
				);
3928
				// Zip files uploads are not supported unless they are done for installation purposed
3929
				// lets delete them in case something goes wrong in this whole process
3930
				if ( 'application/zip' === $attachment->post_mime_type ) {
3931
					// Schedule a cleanup for 2 hours from now in case of failed install.
3932
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3933
				}
3934
			}
3935
		}
3936
		if ( ! is_null( $global_post ) ) {
3937
			$GLOBALS['post'] = $global_post;
3938
		}
3939
3940
		return $uploaded_files;
3941
	}
3942
3943
	/**
3944
	 * Add help to the Jetpack page
3945
	 *
3946
	 * @since Jetpack (1.2.3)
3947
	 * @return false if not the Jetpack page
3948
	 */
3949
	function admin_help() {
3950
		$current_screen = get_current_screen();
3951
3952
		// Overview
3953
		$current_screen->add_help_tab(
3954
			array(
3955
				'id'      => 'home',
3956
				'title'   => __( 'Home', 'jetpack' ),
3957
				'content' =>
3958
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3959
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3960
					'<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>',
3961
			)
3962
		);
3963
3964
		// Screen Content
3965
		if ( current_user_can( 'manage_options' ) ) {
3966
			$current_screen->add_help_tab(
3967
				array(
3968
					'id'      => 'settings',
3969
					'title'   => __( 'Settings', 'jetpack' ),
3970
					'content' =>
3971
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3972
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3973
						'<ol>' .
3974
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3975
							'<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>' .
3976
						'</ol>' .
3977
						'<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>',
3978
				)
3979
			);
3980
		}
3981
3982
		// Help Sidebar
3983
		$support_url = Redirect::get_url( 'jetpack-support' );
3984
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3985
		$current_screen->set_help_sidebar(
3986
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3987
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3988
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3989
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3990
		);
3991
	}
3992
3993
	function admin_menu_css() {
3994
		wp_enqueue_style( 'jetpack-icons' );
3995
	}
3996
3997
	function admin_menu_order() {
3998
		return true;
3999
	}
4000
4001 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
4002
		$jp_menu_order = array();
4003
4004
		foreach ( $menu_order as $index => $item ) {
4005
			if ( $item != 'jetpack' ) {
4006
				$jp_menu_order[] = $item;
4007
			}
4008
4009
			if ( $index == 0 ) {
4010
				$jp_menu_order[] = 'jetpack';
4011
			}
4012
		}
4013
4014
		return $jp_menu_order;
4015
	}
4016
4017
	function admin_banner_styles() {
4018
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4019
4020 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4021
			wp_register_style(
4022
				'jetpack-dops-style',
4023
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4024
				array(),
4025
				JETPACK__VERSION
4026
			);
4027
		}
4028
4029
		wp_enqueue_style(
4030
			'jetpack',
4031
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4032
			array( 'jetpack-dops-style' ),
4033
			JETPACK__VERSION . '-20121016'
4034
		);
4035
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4036
		wp_style_add_data( 'jetpack', 'suffix', $min );
4037
	}
4038
4039
	function plugin_action_links( $actions ) {
4040
4041
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4042
4043
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4044
			return array_merge(
4045
				$jetpack_home,
4046
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4047
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4048
				$actions
4049
			);
4050
		}
4051
4052
		return array_merge( $jetpack_home, $actions );
4053
	}
4054
4055
	/**
4056
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4057
	 *
4058
	 * @param string $login_url The wp-login URL.
4059
	 * @param string $redirect  URL to redirect users after logging in.
4060
	 * @since Jetpack 8.4
4061
	 * @return string
4062
	 */
4063
	public function login_url( $login_url, $redirect ) {
4064
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4065
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4066
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4067
		}
4068
		return $login_url;
4069
	}
4070
4071
	/**
4072
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4073
	 *
4074
	 * @since Jetpack 8.4
4075
	 */
4076
	public function login_init() {
4077
		// phpcs:ignore WordPress.Security.NonceVerification
4078
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4079
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4080
			wp_safe_redirect(
4081
				add_query_arg(
4082
					array(
4083
						'forceInstall' => 1,
4084
						'url'          => rawurlencode( get_site_url() ),
4085
					),
4086
					// @todo provide way to go to specific calypso env.
4087
					self::get_calypso_host() . 'jetpack/connect'
4088
				)
4089
			);
4090
			exit;
4091
		}
4092
	}
4093
4094
	/*
4095
	 * Registration flow:
4096
	 * 1 - ::admin_page_load() action=register
4097
	 * 2 - ::try_registration()
4098
	 * 3 - ::register()
4099
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4100
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4101
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4102
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4103
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4104
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4105
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4106
	 *       jetpack_id, jetpack_secret, jetpack_public
4107
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4108
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4109
	 * 5 - user logs in with WP.com account
4110
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4111
	 *		- Manager::authorize()
4112
	 *		- Manager::get_token()
4113
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4114
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4115
	 *			- which responds with access_token, token_type, scope
4116
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4117
	 *		- Jetpack::activate_default_modules()
4118
	 *     		- Deactivates deprecated plugins
4119
	 *     		- Activates all default modules
4120
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4121
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4122
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4123
	 *     Done!
4124
	 */
4125
4126
	/**
4127
	 * Handles the page load events for the Jetpack admin page
4128
	 */
4129
	function admin_page_load() {
4130
		$error = false;
4131
4132
		// Make sure we have the right body class to hook stylings for subpages off of.
4133
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4134
4135
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4136
			// Should only be used in intermediate redirects to preserve state across redirects
4137
			self::restate();
4138
		}
4139
4140
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4141
			// @todo: Add validation against a known whitelist
4142
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4143
			// User clicked in the iframe to link their accounts
4144
			if ( ! self::is_user_connected() ) {
4145
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4146
4147
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4148
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4149
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4150
4151
				if ( isset( $_GET['notes_iframe'] ) ) {
4152
					$connect_url .= '&notes_iframe';
4153
				}
4154
				wp_redirect( $connect_url );
4155
				exit;
4156
			} else {
4157
				if ( ! isset( $_GET['calypso_env'] ) ) {
4158
					self::state( 'message', 'already_authorized' );
4159
					wp_safe_redirect( self::admin_url() );
4160
					exit;
4161
				} else {
4162
					$connect_url  = $this->build_connect_url( true, false, $from );
4163
					$connect_url .= '&already_authorized=true';
4164
					wp_redirect( $connect_url );
4165
					exit;
4166
				}
4167
			}
4168
		}
4169
4170
		if ( isset( $_GET['action'] ) ) {
4171
			switch ( $_GET['action'] ) {
4172
				case 'authorize':
4173
					if ( self::is_active() && self::is_user_connected() ) {
4174
						self::state( 'message', 'already_authorized' );
4175
						wp_safe_redirect( self::admin_url() );
4176
						exit;
4177
					}
4178
					self::log( 'authorize' );
4179
					$client_server = new Jetpack_Client_Server();
4180
					$client_server->client_authorize();
4181
					exit;
4182
				case 'register':
4183
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4184
						$error = 'cheatin';
4185
						break;
4186
					}
4187
					check_admin_referer( 'jetpack-register' );
4188
					self::log( 'register' );
4189
					self::maybe_set_version_option();
4190
					$registered = self::try_registration();
4191 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4192
						$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...
4193
						self::state( 'error', $error );
4194
						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...
4195
4196
						/**
4197
						 * Jetpack registration Error.
4198
						 *
4199
						 * @since 7.5.0
4200
						 *
4201
						 * @param string|int $error The error code.
4202
						 * @param \WP_Error $registered The error object.
4203
						 */
4204
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4205
						break;
4206
					}
4207
4208
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4209
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4210
4211
					/**
4212
					 * Jetpack registration Success.
4213
					 *
4214
					 * @since 7.5.0
4215
					 *
4216
					 * @param string $from 'from' GET parameter;
4217
					 */
4218
					do_action( 'jetpack_connection_register_success', $from );
4219
4220
					$url = $this->build_connect_url( true, $redirect, $from );
4221
4222
					if ( ! empty( $_GET['onboarding'] ) ) {
4223
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4224
					}
4225
4226
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4227
						$url = add_query_arg( 'auth_approved', 'true', $url );
4228
					}
4229
4230
					wp_redirect( $url );
4231
					exit;
4232
				case 'activate':
4233
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4234
						$error = 'cheatin';
4235
						break;
4236
					}
4237
4238
					$module = stripslashes( $_GET['module'] );
4239
					check_admin_referer( "jetpack_activate-$module" );
4240
					self::log( 'activate', $module );
4241
					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...
4242
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4243
					}
4244
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4245
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4246
					exit;
4247
				case 'activate_default_modules':
4248
					check_admin_referer( 'activate_default_modules' );
4249
					self::log( 'activate_default_modules' );
4250
					self::restate();
4251
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4252
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4253
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4254
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4255
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4256
					exit;
4257
				case 'disconnect':
4258
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4259
						$error = 'cheatin';
4260
						break;
4261
					}
4262
4263
					check_admin_referer( 'jetpack-disconnect' );
4264
					self::log( 'disconnect' );
4265
					self::disconnect();
4266
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4267
					exit;
4268
				case 'reconnect':
4269
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4270
						$error = 'cheatin';
4271
						break;
4272
					}
4273
4274
					check_admin_referer( 'jetpack-reconnect' );
4275
					self::log( 'reconnect' );
4276
					$this->disconnect();
4277
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4278
					exit;
4279 View Code Duplication
				case 'deactivate':
4280
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4281
						$error = 'cheatin';
4282
						break;
4283
					}
4284
4285
					$modules = stripslashes( $_GET['module'] );
4286
					check_admin_referer( "jetpack_deactivate-$modules" );
4287
					foreach ( explode( ',', $modules ) as $module ) {
4288
						self::log( 'deactivate', $module );
4289
						self::deactivate_module( $module );
4290
						self::state( 'message', 'module_deactivated' );
4291
					}
4292
					self::state( 'module', $modules );
4293
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4294
					exit;
4295
				case 'unlink':
4296
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4297
					check_admin_referer( 'jetpack-unlink' );
4298
					self::log( 'unlink' );
4299
					Connection_Manager::disconnect_user();
4300
					self::state( 'message', 'unlinked' );
4301
					if ( 'sub-unlink' == $redirect ) {
4302
						wp_safe_redirect( admin_url() );
4303
					} else {
4304
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4305
					}
4306
					exit;
4307
				case 'onboard':
4308
					if ( ! current_user_can( 'manage_options' ) ) {
4309
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4310
					} else {
4311
						self::create_onboarding_token();
4312
						$url = $this->build_connect_url( true );
4313
4314
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4315
							$url = add_query_arg( 'onboarding', $token, $url );
4316
						}
4317
4318
						$calypso_env = $this->get_calypso_env();
4319
						if ( ! empty( $calypso_env ) ) {
4320
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4321
						}
4322
4323
						wp_redirect( $url );
4324
						exit;
4325
					}
4326
					exit;
4327
				default:
4328
					/**
4329
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4330
					 *
4331
					 * @since 2.6.0
4332
					 *
4333
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4334
					 */
4335
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4336
			}
4337
		}
4338
4339
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4340
			self::activate_new_modules( true );
4341
		}
4342
4343
		$message_code = self::state( 'message' );
4344
		if ( self::state( 'optin-manage' ) ) {
4345
			$activated_manage = $message_code;
4346
			$message_code     = 'jetpack-manage';
4347
		}
4348
4349
		switch ( $message_code ) {
4350
			case 'jetpack-manage':
4351
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4352
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4353
				$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' ), $sites_url ) . '</strong>';
4354
				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...
4355
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4356
				}
4357
				break;
4358
4359
		}
4360
4361
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4362
4363
		if ( ! empty( $deactivated_plugins ) ) {
4364
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4365
			$deactivated_titles  = array();
4366
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4367
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4368
					continue;
4369
				}
4370
4371
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4372
			}
4373
4374
			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...
4375
				if ( $this->message ) {
4376
					$this->message .= "<br /><br />\n";
4377
				}
4378
4379
				$this->message .= wp_sprintf(
4380
					_n(
4381
						'Jetpack contains the most recent version of the old %l plugin.',
4382
						'Jetpack contains the most recent versions of the old %l plugins.',
4383
						count( $deactivated_titles ),
4384
						'jetpack'
4385
					),
4386
					$deactivated_titles
4387
				);
4388
4389
				$this->message .= "<br />\n";
4390
4391
				$this->message .= _n(
4392
					'The old version has been deactivated and can be removed from your site.',
4393
					'The old versions have been deactivated and can be removed from your site.',
4394
					count( $deactivated_titles ),
4395
					'jetpack'
4396
				);
4397
			}
4398
		}
4399
4400
		$this->privacy_checks = self::state( 'privacy_checks' );
4401
4402
		if ( $this->message || $this->error || $this->privacy_checks ) {
4403
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4404
		}
4405
4406
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4407
	}
4408
4409
	function admin_notices() {
4410
4411
		if ( $this->error ) {
4412
			?>
4413
<div id="message" class="jetpack-message jetpack-err">
4414
	<div class="squeezer">
4415
		<h2>
4416
			<?php
4417
			echo wp_kses(
4418
				$this->error,
4419
				array(
4420
					'a'      => array( 'href' => array() ),
4421
					'small'  => true,
4422
					'code'   => true,
4423
					'strong' => true,
4424
					'br'     => true,
4425
					'b'      => true,
4426
				)
4427
			);
4428
			?>
4429
			</h2>
4430
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4431
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4432
<?php	endif; ?>
4433
	</div>
4434
</div>
4435
			<?php
4436
		}
4437
4438
		if ( $this->message ) {
4439
			?>
4440
<div id="message" class="jetpack-message">
4441
	<div class="squeezer">
4442
		<h2>
4443
			<?php
4444
			echo wp_kses(
4445
				$this->message,
4446
				array(
4447
					'strong' => array(),
4448
					'a'      => array( 'href' => true ),
4449
					'br'     => true,
4450
				)
4451
			);
4452
			?>
4453
			</h2>
4454
	</div>
4455
</div>
4456
			<?php
4457
		}
4458
4459
		if ( $this->privacy_checks ) :
4460
			$module_names = $module_slugs = array();
4461
4462
			$privacy_checks = explode( ',', $this->privacy_checks );
4463
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4464
			foreach ( $privacy_checks as $module_slug ) {
4465
				$module = self::get_module( $module_slug );
4466
				if ( ! $module ) {
4467
					continue;
4468
				}
4469
4470
				$module_slugs[] = $module_slug;
4471
				$module_names[] = "<strong>{$module['name']}</strong>";
4472
			}
4473
4474
			$module_slugs = join( ',', $module_slugs );
4475
			?>
4476
<div id="message" class="jetpack-message jetpack-err">
4477
	<div class="squeezer">
4478
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4479
		<p>
4480
			<?php
4481
			echo wp_kses(
4482
				wptexturize(
4483
					wp_sprintf(
4484
						_nx(
4485
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4486
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4487
							count( $privacy_checks ),
4488
							'%l = list of Jetpack module/feature names',
4489
							'jetpack'
4490
						),
4491
						$module_names
4492
					)
4493
				),
4494
				array( 'strong' => true )
4495
			);
4496
4497
			echo "\n<br />\n";
4498
4499
			echo wp_kses(
4500
				sprintf(
4501
					_nx(
4502
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4503
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4504
						count( $privacy_checks ),
4505
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4506
						'jetpack'
4507
					),
4508
					wp_nonce_url(
4509
						self::admin_url(
4510
							array(
4511
								'page'   => 'jetpack',
4512
								'action' => 'deactivate',
4513
								'module' => urlencode( $module_slugs ),
4514
							)
4515
						),
4516
						"jetpack_deactivate-$module_slugs"
4517
					),
4518
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4519
				),
4520
				array(
4521
					'a' => array(
4522
						'href'  => true,
4523
						'title' => true,
4524
					),
4525
				)
4526
			);
4527
			?>
4528
		</p>
4529
	</div>
4530
</div>
4531
			<?php
4532
endif;
4533
	}
4534
4535
	/**
4536
	 * We can't always respond to a signed XML-RPC request with a
4537
	 * helpful error message. In some circumstances, doing so could
4538
	 * leak information.
4539
	 *
4540
	 * Instead, track that the error occurred via a Jetpack_Option,
4541
	 * and send that data back in the heartbeat.
4542
	 * All this does is increment a number, but it's enough to find
4543
	 * trends.
4544
	 *
4545
	 * @param WP_Error $xmlrpc_error The error produced during
4546
	 *                               signature validation.
4547
	 */
4548
	function track_xmlrpc_error( $xmlrpc_error ) {
4549
		$code = is_wp_error( $xmlrpc_error )
4550
			? $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...
4551
			: 'should-not-happen';
4552
4553
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4554
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4555
			// No need to update the option if we already have
4556
			// this code stored.
4557
			return;
4558
		}
4559
		$xmlrpc_errors[ $code ] = true;
4560
4561
		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...
4562
	}
4563
4564
	/**
4565
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4566
	 */
4567
	function stat( $group, $detail ) {
4568
		if ( ! isset( $this->stats[ $group ] ) ) {
4569
			$this->stats[ $group ] = array();
4570
		}
4571
		$this->stats[ $group ][] = $detail;
4572
	}
4573
4574
	/**
4575
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4576
	 */
4577
	function do_stats( $method = '' ) {
4578
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4579
			foreach ( $this->stats as $group => $stats ) {
4580
				if ( is_array( $stats ) && count( $stats ) ) {
4581
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4582
					if ( 'server_side' === $method ) {
4583
						self::do_server_side_stat( $args );
4584
					} else {
4585
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4586
					}
4587
				}
4588
				unset( $this->stats[ $group ] );
4589
			}
4590
		}
4591
	}
4592
4593
	/**
4594
	 * Runs stats code for a one-off, server-side.
4595
	 *
4596
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4597
	 *
4598
	 * @return bool If it worked.
4599
	 */
4600
	static function do_server_side_stat( $args ) {
4601
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4602
		if ( is_wp_error( $response ) ) {
4603
			return false;
4604
		}
4605
4606
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4607
			return false;
4608
		}
4609
4610
		return true;
4611
	}
4612
4613
	/**
4614
	 * Builds the stats url.
4615
	 *
4616
	 * @param $args array|string The arguments to append to the URL.
4617
	 *
4618
	 * @return string The URL to be pinged.
4619
	 */
4620
	static function build_stats_url( $args ) {
4621
		$defaults = array(
4622
			'v'    => 'wpcom2',
4623
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4624
		);
4625
		$args     = wp_parse_args( $args, $defaults );
0 ignored issues
show
$defaults is of type array<string,string,{"v"...ring","rand":"string"}>, but the function expects a string.

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...
4626
		/**
4627
		 * Filter the URL used as the Stats tracking pixel.
4628
		 *
4629
		 * @since 2.3.2
4630
		 *
4631
		 * @param string $url Base URL used as the Stats tracking pixel.
4632
		 */
4633
		$base_url = apply_filters(
4634
			'jetpack_stats_base_url',
4635
			'https://pixel.wp.com/g.gif'
4636
		);
4637
		$url      = add_query_arg( $args, $base_url );
4638
		return $url;
4639
	}
4640
4641
	/**
4642
	 * Get the role of the current user.
4643
	 *
4644
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4645
	 *
4646
	 * @access public
4647
	 * @static
4648
	 *
4649
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4650
	 */
4651
	public static function translate_current_user_to_role() {
4652
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4653
4654
		$roles = new Roles();
4655
		return $roles->translate_current_user_to_role();
4656
	}
4657
4658
	/**
4659
	 * Get the role of a particular user.
4660
	 *
4661
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4662
	 *
4663
	 * @access public
4664
	 * @static
4665
	 *
4666
	 * @param \WP_User $user User object.
4667
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4668
	 */
4669
	public static function translate_user_to_role( $user ) {
4670
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4671
4672
		$roles = new Roles();
4673
		return $roles->translate_user_to_role( $user );
4674
	}
4675
4676
	/**
4677
	 * Get the minimum capability for a role.
4678
	 *
4679
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4680
	 *
4681
	 * @access public
4682
	 * @static
4683
	 *
4684
	 * @param string $role Role name.
4685
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4686
	 */
4687
	public static function translate_role_to_cap( $role ) {
4688
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4689
4690
		$roles = new Roles();
4691
		return $roles->translate_role_to_cap( $role );
4692
	}
4693
4694
	/**
4695
	 * Sign a user role with the master access token.
4696
	 * If not specified, will default to the current user.
4697
	 *
4698
	 * @deprecated since 7.7
4699
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4700
	 *
4701
	 * @access public
4702
	 * @static
4703
	 *
4704
	 * @param string $role    User role.
4705
	 * @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...
4706
	 * @return string Signed user role.
4707
	 */
4708
	public static function sign_role( $role, $user_id = null ) {
4709
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4710
		return self::connection()->sign_role( $role, $user_id );
4711
	}
4712
4713
	/**
4714
	 * Builds a URL to the Jetpack connection auth page
4715
	 *
4716
	 * @since 3.9.5
4717
	 *
4718
	 * @param bool        $raw If true, URL will not be escaped.
4719
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4720
	 *                              If string, will be a custom redirect.
4721
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4722
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4723
	 *
4724
	 * @return string Connect URL
4725
	 */
4726
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4727
		$site_id    = Jetpack_Options::get_option( 'id' );
4728
		$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...
4729
4730
		if ( $register || ! $blog_token || ! $site_id ) {
4731
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4732
4733
			if ( ! empty( $redirect ) ) {
4734
				$url = add_query_arg(
4735
					'redirect',
4736
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4737
					$url
4738
				);
4739
			}
4740
4741
			if ( is_network_admin() ) {
4742
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4743
			}
4744
4745
			$calypso_env = self::get_calypso_env();
4746
4747
			if ( ! empty( $calypso_env ) ) {
4748
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4749
			}
4750
		} else {
4751
4752
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4753
			// because otherwise this logic can get us in to a loop.
4754
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4755
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4756
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4757
4758
				$response = Client::wpcom_json_api_request_as_blog(
4759
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4760
					'1.1'
4761
				);
4762
4763
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4764
4765
					// Generating a register URL instead to refresh the existing token
4766
					return $this->build_connect_url( $raw, $redirect, $from, true );
4767
				}
4768
			}
4769
4770
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4726 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...
4771
		}
4772
4773
		if ( $from ) {
4774
			$url = add_query_arg( 'from', $from, $url );
4775
		}
4776
4777
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4778
		/**
4779
		 * Filter the URL used when connecting a user to a WordPress.com account.
4780
		 *
4781
		 * @since 8.1.0
4782
		 *
4783
		 * @param string $url Connection URL.
4784
		 * @param bool   $raw If true, URL will not be escaped.
4785
		 */
4786
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $raw.

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...
4787
	}
4788
4789
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4790
4791
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4792
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4793
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4794
4795
		if ( $iframe ) {
4796
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4797
		}
4798
4799
		$c8n = self::connection();
4800
		$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...
4801
4802
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4803
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4804
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4805
4806
		if ( $iframe ) {
4807
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4808
		}
4809
4810
		return $url;
4811
	}
4812
4813
	/**
4814
	 * Filters the connection URL parameter array.
4815
	 *
4816
	 * @param array $args default URL parameters used by the package.
4817
	 * @return array the modified URL arguments array.
4818
	 */
4819
	public static function filter_connect_request_body( $args ) {
4820
		if (
4821
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4822
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4823
		) {
4824
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4825
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4826
				? $gp_locale->slug
4827
				: '';
4828
		}
4829
4830
		$tracking        = new Tracking();
4831
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4832
4833
		$args = array_merge(
4834
			$args,
4835
			array(
4836
				'_ui' => $tracks_identity['_ui'],
4837
				'_ut' => $tracks_identity['_ut'],
4838
			)
4839
		);
4840
4841
		$calypso_env = self::get_calypso_env();
4842
4843
		if ( ! empty( $calypso_env ) ) {
4844
			$args['calypso_env'] = $calypso_env;
4845
		}
4846
4847
		return $args;
4848
	}
4849
4850
	/**
4851
	 * Filters the URL that will process the connection data. It can be different from the URL
4852
	 * that we send the user to after everything is done.
4853
	 *
4854
	 * @param String $processing_url the default redirect URL used by the package.
4855
	 * @return String the modified URL.
4856
	 */
4857
	public static function filter_connect_processing_url( $processing_url ) {
4858
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4859
		return $processing_url;
4860
	}
4861
4862
	/**
4863
	 * Filters the redirection URL that is used for connect requests. The redirect
4864
	 * URL should return the user back to the Jetpack console.
4865
	 *
4866
	 * @param String $redirect the default redirect URL used by the package.
4867
	 * @return String the modified URL.
4868
	 */
4869
	public static function filter_connect_redirect_url( $redirect ) {
4870
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4871
		$redirect           = $redirect
4872
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4873
			: $jetpack_admin_page;
4874
4875
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4876
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4877
		}
4878
4879
		return $redirect;
4880
	}
4881
4882
	/**
4883
	 * This action fires at the beginning of the Manager::authorize method.
4884
	 */
4885
	public static function authorize_starting() {
4886
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4887
		// Checking if site has been active/connected previously before recording unique connection.
4888
		if ( ! $jetpack_unique_connection ) {
4889
			// jetpack_unique_connection option has never been set.
4890
			$jetpack_unique_connection = array(
4891
				'connected'    => 0,
4892
				'disconnected' => 0,
4893
				'version'      => '3.6.1',
4894
			);
4895
4896
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4897
4898
			// Track unique connection.
4899
			$jetpack = self::init();
4900
4901
			$jetpack->stat( 'connections', 'unique-connection' );
4902
			$jetpack->do_stats( 'server_side' );
4903
		}
4904
4905
		// Increment number of times connected.
4906
		$jetpack_unique_connection['connected'] += 1;
4907
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4908
	}
4909
4910
	/**
4911
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4912
	 * linked.
4913
	 */
4914
	public static function authorize_ending_linked() {
4915
		// Don't activate anything since we are just connecting a user.
4916
		self::state( 'message', 'linked' );
4917
	}
4918
4919
	/**
4920
	 * This action fires at the end of the Manager::authorize method when the master user is
4921
	 * authorized.
4922
	 *
4923
	 * @param array $data The request data.
4924
	 */
4925
	public static function authorize_ending_authorized( $data ) {
4926
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4927
		self::invalidate_onboarding_token();
4928
4929
		// If redirect_uri is SSO, ensure SSO module is enabled.
4930
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4931
4932
		/** This filter is documented in class.jetpack-cli.php */
4933
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4934
4935
		$activate_sso = (
4936
			isset( $redirect_options['action'] ) &&
4937
			'jetpack-sso' === $redirect_options['action'] &&
4938
			$jetpack_start_enable_sso
4939
		);
4940
4941
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4942
4943
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4944
	}
4945
4946
	/**
4947
	 * Get our assumed site creation date.
4948
	 * Calculated based on the earlier date of either:
4949
	 * - Earliest admin user registration date.
4950
	 * - Earliest date of post of any post type.
4951
	 *
4952
	 * @since 7.2.0
4953
	 * @deprecated since 7.8.0
4954
	 *
4955
	 * @return string Assumed site creation date and time.
4956
	 */
4957
	public static function get_assumed_site_creation_date() {
4958
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4959
		return self::connection()->get_assumed_site_creation_date();
4960
	}
4961
4962 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4963
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4964
4965
		if ( $activation_source_name ) {
4966
			$args['_as'] = urlencode( $activation_source_name );
4967
		}
4968
4969
		if ( $activation_source_keyword ) {
4970
			$args['_ak'] = urlencode( $activation_source_keyword );
4971
		}
4972
	}
4973
4974
	function build_reconnect_url( $raw = false ) {
4975
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4976
		return $raw ? $url : esc_url( $url );
4977
	}
4978
4979
	public static function admin_url( $args = null ) {
4980
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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...
4981
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4982
		return $url;
4983
	}
4984
4985
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4986
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4987
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4988
	}
4989
4990
	function dismiss_jetpack_notice() {
4991
4992
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4993
			return;
4994
		}
4995
4996
		switch ( $_GET['jetpack-notice'] ) {
4997
			case 'dismiss':
4998
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4999
5000
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5001
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5002
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5003
				}
5004
				break;
5005
		}
5006
	}
5007
5008
	public static function sort_modules( $a, $b ) {
5009
		if ( $a['sort'] == $b['sort'] ) {
5010
			return 0;
5011
		}
5012
5013
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5014
	}
5015
5016
	function ajax_recheck_ssl() {
5017
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5018
		$result = self::permit_ssl( true );
5019
		wp_send_json(
5020
			array(
5021
				'enabled' => $result,
5022
				'message' => get_transient( 'jetpack_https_test_message' ),
5023
			)
5024
		);
5025
	}
5026
5027
	/* Client API */
5028
5029
	/**
5030
	 * Returns the requested Jetpack API URL
5031
	 *
5032
	 * @deprecated since 7.7
5033
	 * @return string
5034
	 */
5035
	public static function api_url( $relative_url ) {
5036
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5037
		$connection = self::connection();
5038
		return $connection->api_url( $relative_url );
5039
	}
5040
5041
	/**
5042
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5043
	 *
5044
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5045
	 */
5046
	public static function fix_url_for_bad_hosts( $url ) {
5047
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5048
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5049
	}
5050
5051
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5052
		// Default to a blog token.
5053
		$token_type = 'blog';
5054
5055
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5056
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5057
			if ( ! empty( $_GET['onboarding'] ) ) {
5058
				$jpo = $_GET;
5059
			} else {
5060
				$jpo = json_decode( $request_data, true );
5061
			}
5062
5063
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5064
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5065
5066
			if (
5067
				isset( $jpo_user )
5068
				&& isset( $jpo_token )
5069
				&& is_email( $jpo_user )
5070
				&& ctype_alnum( $jpo_token )
5071
				&& isset( $_GET['rest_route'] )
5072
				&& self::validate_onboarding_token_action(
5073
					$jpo_token,
5074
					$_GET['rest_route']
5075
				)
5076
			) {
5077
				$jp_user = get_user_by( 'email', $jpo_user );
5078
				if ( is_a( $jp_user, 'WP_User' ) ) {
5079
					wp_set_current_user( $jp_user->ID );
5080
					$user_can = is_multisite()
5081
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5082
						: current_user_can( 'manage_options' );
5083
					if ( $user_can ) {
5084
						$token_type              = 'user';
5085
						$token->external_user_id = $jp_user->ID;
5086
					}
5087
				}
5088
			}
5089
5090
			$token_data['type']    = $token_type;
5091
			$token_data['user_id'] = $token->external_user_id;
5092
		}
5093
5094
		return $token_data;
5095
	}
5096
5097
	/**
5098
	 * Create a random secret for validating onboarding payload
5099
	 *
5100
	 * @return string Secret token
5101
	 */
5102
	public static function create_onboarding_token() {
5103
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5104
			$token = wp_generate_password( 32, false );
5105
			Jetpack_Options::update_option( 'onboarding', $token );
5106
		}
5107
5108
		return $token;
5109
	}
5110
5111
	/**
5112
	 * Remove the onboarding token
5113
	 *
5114
	 * @return bool True on success, false on failure
5115
	 */
5116
	public static function invalidate_onboarding_token() {
5117
		return Jetpack_Options::delete_option( 'onboarding' );
5118
	}
5119
5120
	/**
5121
	 * Validate an onboarding token for a specific action
5122
	 *
5123
	 * @return boolean True if token/action pair is accepted, false if not
5124
	 */
5125
	public static function validate_onboarding_token_action( $token, $action ) {
5126
		// Compare tokens, bail if tokens do not match
5127
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5128
			return false;
5129
		}
5130
5131
		// List of valid actions we can take
5132
		$valid_actions = array(
5133
			'/jetpack/v4/settings',
5134
		);
5135
5136
		// Whitelist the action
5137
		if ( ! in_array( $action, $valid_actions ) ) {
5138
			return false;
5139
		}
5140
5141
		return true;
5142
	}
5143
5144
	/**
5145
	 * Checks to see if the URL is using SSL to connect with Jetpack
5146
	 *
5147
	 * @since 2.3.3
5148
	 * @return boolean
5149
	 */
5150
	public static function permit_ssl( $force_recheck = false ) {
5151
		// Do some fancy tests to see if ssl is being supported
5152
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5153
			$message = '';
5154
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5155
				$ssl = 0;
5156
			} else {
5157
				switch ( JETPACK_CLIENT__HTTPS ) {
5158
					case 'NEVER':
5159
						$ssl     = 0;
5160
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5161
						break;
5162
					case 'ALWAYS':
5163
					case 'AUTO':
5164
					default:
5165
						$ssl = 1;
5166
						break;
5167
				}
5168
5169
				// If it's not 'NEVER', test to see
5170
				if ( $ssl ) {
5171
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5172
						$ssl     = 0;
5173
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5174
					} else {
5175
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5176
						if ( is_wp_error( $response ) ) {
5177
							$ssl     = 0;
5178
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5179
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5180
							$ssl     = 0;
5181
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5182
						}
5183
					}
5184
				}
5185
			}
5186
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5187
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5188
		}
5189
5190
		return (bool) $ssl;
5191
	}
5192
5193
	/*
5194
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5195
	 */
5196
	public function alert_auto_ssl_fail() {
5197
		if ( ! current_user_can( 'manage_options' ) ) {
5198
			return;
5199
		}
5200
5201
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5202
		?>
5203
5204
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5205
			<div class="jp-banner__content">
5206
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5207
				<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>
5208
				<p>
5209
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5210
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5211
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5212
				</p>
5213
				<p>
5214
					<?php
5215
					printf(
5216
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5217
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5218
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5219
					);
5220
					?>
5221
				</p>
5222
			</div>
5223
		</div>
5224
		<style>
5225
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5226
		</style>
5227
		<script type="text/javascript">
5228
			jQuery( document ).ready( function( $ ) {
5229
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5230
					var $this = $( this );
5231
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5232
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5233
					e.preventDefault();
5234
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5235
					$.post( ajaxurl, data )
5236
					  .done( function( response ) {
5237
						  if ( response.enabled ) {
5238
							  $( '#jetpack-ssl-warning' ).hide();
5239
						  } else {
5240
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5241
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5242
						  }
5243
					  }.bind( $this ) );
5244
				} );
5245
			} );
5246
		</script>
5247
5248
		<?php
5249
	}
5250
5251
	/**
5252
	 * Returns the Jetpack XML-RPC API
5253
	 *
5254
	 * @deprecated 8.0 Use Connection_Manager instead.
5255
	 * @return string
5256
	 */
5257
	public static function xmlrpc_api_url() {
5258
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5259
		return self::connection()->xmlrpc_api_url();
5260
	}
5261
5262
	/**
5263
	 * Returns the connection manager object.
5264
	 *
5265
	 * @return Automattic\Jetpack\Connection\Manager
5266
	 */
5267
	public static function connection() {
5268
		$jetpack = static::init();
5269
5270
		// If the connection manager hasn't been instantiated, do that now.
5271
		if ( ! $jetpack->connection_manager ) {
5272
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5273
		}
5274
5275
		return $jetpack->connection_manager;
5276
	}
5277
5278
	/**
5279
	 * Creates two secret tokens and the end of life timestamp for them.
5280
	 *
5281
	 * Note these tokens are unique per call, NOT static per site for connecting.
5282
	 *
5283
	 * @since 2.6
5284
	 * @param String  $action  The action name.
5285
	 * @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...
5286
	 * @param Integer $exp     Expiration time in seconds.
5287
	 * @return array
5288
	 */
5289
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5290
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5291
	}
5292
5293
	public static function get_secrets( $action, $user_id ) {
5294
		$secrets = self::connection()->get_secrets( $action, $user_id );
5295
5296
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5297
			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...
5298
		}
5299
5300
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5301
			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...
5302
		}
5303
5304
		return $secrets;
5305
	}
5306
5307
	/**
5308
	 * @deprecated 7.5 Use Connection_Manager instead.
5309
	 *
5310
	 * @param $action
5311
	 * @param $user_id
5312
	 */
5313
	public static function delete_secrets( $action, $user_id ) {
5314
		return self::connection()->delete_secrets( $action, $user_id );
5315
	}
5316
5317
	/**
5318
	 * Builds the timeout limit for queries talking with the wpcom servers.
5319
	 *
5320
	 * Based on local php max_execution_time in php.ini
5321
	 *
5322
	 * @since 2.6
5323
	 * @return int
5324
	 * @deprecated
5325
	 **/
5326
	public function get_remote_query_timeout_limit() {
5327
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5328
		return self::get_max_execution_time();
5329
	}
5330
5331
	/**
5332
	 * Builds the timeout limit for queries talking with the wpcom servers.
5333
	 *
5334
	 * Based on local php max_execution_time in php.ini
5335
	 *
5336
	 * @since 5.4
5337
	 * @return int
5338
	 **/
5339
	public static function get_max_execution_time() {
5340
		$timeout = (int) ini_get( 'max_execution_time' );
5341
5342
		// Ensure exec time set in php.ini
5343
		if ( ! $timeout ) {
5344
			$timeout = 30;
5345
		}
5346
		return $timeout;
5347
	}
5348
5349
	/**
5350
	 * Sets a minimum request timeout, and returns the current timeout
5351
	 *
5352
	 * @since 5.4
5353
	 **/
5354 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5355
		$timeout = self::get_max_execution_time();
5356
		if ( $timeout < $min_timeout ) {
5357
			$timeout = $min_timeout;
5358
			set_time_limit( $timeout );
5359
		}
5360
		return $timeout;
5361
	}
5362
5363
	/**
5364
	 * Takes the response from the Jetpack register new site endpoint and
5365
	 * verifies it worked properly.
5366
	 *
5367
	 * @since 2.6
5368
	 * @deprecated since 7.7.0
5369
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5370
	 **/
5371
	public function validate_remote_register_response() {
5372
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5373
	}
5374
5375
	/**
5376
	 * @return bool|WP_Error
5377
	 */
5378
	public static function register() {
5379
		$tracking = new Tracking();
5380
		$tracking->record_user_event( 'jpc_register_begin' );
5381
5382
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5383
5384
		$connection   = self::connection();
5385
		$registration = $connection->register();
5386
5387
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5388
5389
		if ( ! $registration || is_wp_error( $registration ) ) {
5390
			return $registration;
5391
		}
5392
5393
		return true;
5394
	}
5395
5396
	/**
5397
	 * Filters the registration request body to include tracking properties.
5398
	 *
5399
	 * @param array $properties
5400
	 * @return array amended properties.
5401
	 */
5402 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5403
		$tracking        = new Tracking();
5404
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5405
5406
		return array_merge(
5407
			$properties,
5408
			array(
5409
				'_ui' => $tracks_identity['_ui'],
5410
				'_ut' => $tracks_identity['_ut'],
5411
			)
5412
		);
5413
	}
5414
5415
	/**
5416
	 * Filters the token request body to include tracking properties.
5417
	 *
5418
	 * @param array $properties
5419
	 * @return array amended properties.
5420
	 */
5421 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5422
		$tracking        = new Tracking();
5423
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5424
5425
		return array_merge(
5426
			$properties,
5427
			array(
5428
				'_ui' => $tracks_identity['_ui'],
5429
				'_ut' => $tracks_identity['_ut'],
5430
			)
5431
		);
5432
	}
5433
5434
	/**
5435
	 * If the db version is showing something other that what we've got now, bump it to current.
5436
	 *
5437
	 * @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...
5438
	 */
5439
	public static function maybe_set_version_option() {
5440
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5441
		if ( JETPACK__VERSION != $version ) {
5442
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5443
5444
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5445
				/** This action is documented in class.jetpack.php */
5446
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5447
			}
5448
5449
			return true;
5450
		}
5451
		return false;
5452
	}
5453
5454
	/* Client Server API */
5455
5456
	/**
5457
	 * Loads the Jetpack XML-RPC client.
5458
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5459
	 *
5460
	 * @deprecated since 7.7.0
5461
	 */
5462
	public static function load_xml_rpc_client() {
5463
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5464
	}
5465
5466
	/**
5467
	 * Resets the saved authentication state in between testing requests.
5468
	 */
5469
	public function reset_saved_auth_state() {
5470
		$this->rest_authentication_status = null;
5471
5472
		if ( ! $this->connection_manager ) {
5473
			$this->connection_manager = new Connection_Manager();
5474
		}
5475
5476
		$this->connection_manager->reset_saved_auth_state();
5477
	}
5478
5479
	/**
5480
	 * Verifies the signature of the current request.
5481
	 *
5482
	 * @deprecated since 7.7.0
5483
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5484
	 *
5485
	 * @return false|array
5486
	 */
5487
	public function verify_xml_rpc_signature() {
5488
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5489
		return self::connection()->verify_xml_rpc_signature();
5490
	}
5491
5492
	/**
5493
	 * Verifies the signature of the current request.
5494
	 *
5495
	 * This function has side effects and should not be used. Instead,
5496
	 * use the memoized version `->verify_xml_rpc_signature()`.
5497
	 *
5498
	 * @deprecated since 7.7.0
5499
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5500
	 * @internal
5501
	 */
5502
	private function internal_verify_xml_rpc_signature() {
5503
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5504
	}
5505
5506
	/**
5507
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5508
	 *
5509
	 * @deprecated since 7.7.0
5510
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5511
	 *
5512
	 * @param \WP_User|mixed $user     User object if authenticated.
5513
	 * @param string         $username Username.
5514
	 * @param string         $password Password string.
5515
	 * @return \WP_User|mixed Authenticated user or error.
5516
	 */
5517 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5518
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5519
5520
		if ( ! $this->connection_manager ) {
5521
			$this->connection_manager = new Connection_Manager();
5522
		}
5523
5524
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5525
	}
5526
5527
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5528
	// Uses the existing XMLRPC request signing implementation.
5529
	function wp_rest_authenticate( $user ) {
5530
		if ( ! empty( $user ) ) {
5531
			// Another authentication method is in effect.
5532
			return $user;
5533
		}
5534
5535
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5536
			// Nothing to do for this authentication method.
5537
			return null;
5538
		}
5539
5540
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5541
			// Nothing to do for this authentication method.
5542
			return null;
5543
		}
5544
5545
		// Ensure that we always have the request body available.  At this
5546
		// point, the WP REST API code to determine the request body has not
5547
		// run yet.  That code may try to read from 'php://input' later, but
5548
		// this can only be done once per request in PHP versions prior to 5.6.
5549
		// So we will go ahead and perform this read now if needed, and save
5550
		// the request body where both the Jetpack signature verification code
5551
		// and the WP REST API code can see it.
5552
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5553
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5554
		}
5555
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5556
5557
		// Only support specific request parameters that have been tested and
5558
		// are known to work with signature verification.  A different method
5559
		// can be passed to the WP REST API via the '?_method=' parameter if
5560
		// needed.
5561
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5562
			$this->rest_authentication_status = new WP_Error(
5563
				'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...
5564
				__( 'This request method is not supported.', 'jetpack' ),
5565
				array( 'status' => 400 )
5566
			);
5567
			return null;
5568
		}
5569
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5570
			$this->rest_authentication_status = new WP_Error(
5571
				'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...
5572
				__( 'This request method does not support body parameters.', 'jetpack' ),
5573
				array( 'status' => 400 )
5574
			);
5575
			return null;
5576
		}
5577
5578
		if ( ! $this->connection_manager ) {
5579
			$this->connection_manager = new Connection_Manager();
5580
		}
5581
5582
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5583
5584
		if (
5585
			$verified &&
5586
			isset( $verified['type'] ) &&
5587
			'user' === $verified['type'] &&
5588
			! empty( $verified['user_id'] )
5589
		) {
5590
			// Authentication successful.
5591
			$this->rest_authentication_status = true;
5592
			return $verified['user_id'];
5593
		}
5594
5595
		// Something else went wrong.  Probably a signature error.
5596
		$this->rest_authentication_status = new WP_Error(
5597
			'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...
5598
			__( 'The request is not signed correctly.', 'jetpack' ),
5599
			array( 'status' => 400 )
5600
		);
5601
		return null;
5602
	}
5603
5604
	/**
5605
	 * Report authentication status to the WP REST API.
5606
	 *
5607
	 * @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...
5608
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5609
	 */
5610
	public function wp_rest_authentication_errors( $value ) {
5611
		if ( $value !== null ) {
5612
			return $value;
5613
		}
5614
		return $this->rest_authentication_status;
5615
	}
5616
5617
	/**
5618
	 * Add our nonce to this request.
5619
	 *
5620
	 * @deprecated since 7.7.0
5621
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5622
	 *
5623
	 * @param int    $timestamp Timestamp of the request.
5624
	 * @param string $nonce     Nonce string.
5625
	 */
5626 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5627
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5628
5629
		if ( ! $this->connection_manager ) {
5630
			$this->connection_manager = new Connection_Manager();
5631
		}
5632
5633
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5634
	}
5635
5636
	/**
5637
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5638
	 * Capture it here so we can verify the signature later.
5639
	 *
5640
	 * @deprecated since 7.7.0
5641
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5642
	 *
5643
	 * @param array $methods XMLRPC methods.
5644
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5645
	 */
5646 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5647
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5648
5649
		if ( ! $this->connection_manager ) {
5650
			$this->connection_manager = new Connection_Manager();
5651
		}
5652
5653
		return $this->connection_manager->xmlrpc_methods( $methods );
5654
	}
5655
5656
	/**
5657
	 * Register additional public XMLRPC methods.
5658
	 *
5659
	 * @deprecated since 7.7.0
5660
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5661
	 *
5662
	 * @param array $methods Public XMLRPC methods.
5663
	 * @return array Public XMLRPC methods, with the getOptions one.
5664
	 */
5665 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5666
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5667
5668
		if ( ! $this->connection_manager ) {
5669
			$this->connection_manager = new Connection_Manager();
5670
		}
5671
5672
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5673
	}
5674
5675
	/**
5676
	 * Handles a getOptions XMLRPC method call.
5677
	 *
5678
	 * @deprecated since 7.7.0
5679
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5680
	 *
5681
	 * @param array $args method call arguments.
5682
	 * @return array an amended XMLRPC server options array.
5683
	 */
5684 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5685
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5686
5687
		if ( ! $this->connection_manager ) {
5688
			$this->connection_manager = new Connection_Manager();
5689
		}
5690
5691
		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...
5692
	}
5693
5694
	/**
5695
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5696
	 *
5697
	 * @deprecated since 7.7.0
5698
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5699
	 *
5700
	 * @param array $options Standard Core options.
5701
	 * @return array Amended options.
5702
	 */
5703 View Code Duplication
	public function xmlrpc_options( $options ) {
5704
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5705
5706
		if ( ! $this->connection_manager ) {
5707
			$this->connection_manager = new Connection_Manager();
5708
		}
5709
5710
		return $this->connection_manager->xmlrpc_options( $options );
5711
	}
5712
5713
	/**
5714
	 * Cleans nonces that were saved when calling ::add_nonce.
5715
	 *
5716
	 * @deprecated since 7.7.0
5717
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5718
	 *
5719
	 * @param bool $all whether to clean even non-expired nonces.
5720
	 */
5721
	public static function clean_nonces( $all = false ) {
5722
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5723
		return self::connection()->clean_nonces( $all );
5724
	}
5725
5726
	/**
5727
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5728
	 * SET: state( $key, $value );
5729
	 * GET: $value = state( $key );
5730
	 *
5731
	 * @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...
5732
	 * @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...
5733
	 * @param bool   $restate private
5734
	 */
5735
	public static function state( $key = null, $value = null, $restate = false ) {
5736
		static $state = array();
5737
		static $path, $domain;
5738
		if ( ! isset( $path ) ) {
5739
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5740
			$admin_url = self::admin_url();
5741
			$bits      = wp_parse_url( $admin_url );
5742
5743
			if ( is_array( $bits ) ) {
5744
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5745
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5746
			} else {
5747
				$path = $domain = null;
5748
			}
5749
		}
5750
5751
		// Extract state from cookies and delete cookies
5752
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5753
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5754
			unset( $_COOKIE['jetpackState'] );
5755
			foreach ( $yum as $k => $v ) {
5756
				if ( strlen( $v ) ) {
5757
					$state[ $k ] = $v;
5758
				}
5759
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5760
			}
5761
		}
5762
5763
		if ( $restate ) {
5764
			foreach ( $state as $k => $v ) {
5765
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5766
			}
5767
			return;
5768
		}
5769
5770
		// Get a state variable.
5771
		if ( isset( $key ) && ! isset( $value ) ) {
5772
			if ( array_key_exists( $key, $state ) ) {
5773
				return $state[ $key ];
5774
			}
5775
			return null;
5776
		}
5777
5778
		// Set a state variable.
5779
		if ( isset( $key ) && isset( $value ) ) {
5780
			if ( is_array( $value ) && isset( $value[0] ) ) {
5781
				$value = $value[0];
5782
			}
5783
			$state[ $key ] = $value;
5784
			if ( ! headers_sent() ) {
5785
				if ( self::should_set_cookie( $key ) ) {
5786
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5787
				}
5788
			}
5789
		}
5790
	}
5791
5792
	public static function restate() {
5793
		self::state( null, null, true );
5794
	}
5795
5796
	/**
5797
	 * Determines whether the jetpackState[$key] value should be added to the
5798
	 * cookie.
5799
	 *
5800
	 * @param string $key The state key.
5801
	 *
5802
	 * @return boolean Whether the value should be added to the cookie.
5803
	 */
5804
	public static function should_set_cookie( $key ) {
5805
		global $current_screen;
5806
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5807
5808
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5809
			return false;
5810
		}
5811
5812
		return true;
5813
	}
5814
5815
	public static function check_privacy( $file ) {
5816
		static $is_site_publicly_accessible = null;
5817
5818
		if ( is_null( $is_site_publicly_accessible ) ) {
5819
			$is_site_publicly_accessible = false;
5820
5821
			$rpc = new Jetpack_IXR_Client();
5822
5823
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5824
			if ( $success ) {
5825
				$response = $rpc->getResponse();
5826
				if ( $response ) {
5827
					$is_site_publicly_accessible = true;
5828
				}
5829
			}
5830
5831
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5832
		}
5833
5834
		if ( $is_site_publicly_accessible ) {
5835
			return;
5836
		}
5837
5838
		$module_slug = self::get_module_slug( $file );
5839
5840
		$privacy_checks = self::state( 'privacy_checks' );
5841
		if ( ! $privacy_checks ) {
5842
			$privacy_checks = $module_slug;
5843
		} else {
5844
			$privacy_checks .= ",$module_slug";
5845
		}
5846
5847
		self::state( 'privacy_checks', $privacy_checks );
5848
	}
5849
5850
	/**
5851
	 * Helper method for multicall XMLRPC.
5852
	 *
5853
	 * @param ...$args Args for the async_call.
5854
	 */
5855
	public static function xmlrpc_async_call( ...$args ) {
5856
		global $blog_id;
5857
		static $clients = array();
5858
5859
		$client_blog_id = is_multisite() ? $blog_id : 0;
5860
5861
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5862
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5863
			if ( function_exists( 'ignore_user_abort' ) ) {
5864
				ignore_user_abort( true );
5865
			}
5866
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5867
		}
5868
5869
		if ( ! empty( $args[0] ) ) {
5870
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5871
		} elseif ( is_multisite() ) {
5872
			foreach ( $clients as $client_blog_id => $client ) {
5873
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5874
					continue;
5875
				}
5876
5877
				$switch_success = switch_to_blog( $client_blog_id, true );
5878
				if ( ! $switch_success ) {
5879
					continue;
5880
				}
5881
5882
				flush();
5883
				$client->query();
5884
5885
				restore_current_blog();
5886
			}
5887
		} else {
5888
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5889
				flush();
5890
				$clients[0]->query();
5891
			}
5892
		}
5893
	}
5894
5895
	public static function staticize_subdomain( $url ) {
5896
5897
		// Extract hostname from URL
5898
		$host = wp_parse_url( $url, PHP_URL_HOST );
0 ignored issues
show
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
5899
5900
		// Explode hostname on '.'
5901
		$exploded_host = explode( '.', $host );
5902
5903
		// Retrieve the name and TLD
5904
		if ( count( $exploded_host ) > 1 ) {
5905
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5906
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5907
			// Rebuild domain excluding subdomains
5908
			$domain = $name . '.' . $tld;
5909
		} else {
5910
			$domain = $host;
5911
		}
5912
		// Array of Automattic domains
5913
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5914
5915
		// Return $url if not an Automattic domain
5916
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5917
			return $url;
5918
		}
5919
5920
		if ( is_ssl() ) {
5921
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5922
		}
5923
5924
		srand( crc32( basename( $url ) ) );
5925
		$static_counter = rand( 0, 2 );
5926
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5927
5928
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5929
	}
5930
5931
	/* JSON API Authorization */
5932
5933
	/**
5934
	 * Handles the login action for Authorizing the JSON API
5935
	 */
5936
	function login_form_json_api_authorization() {
5937
		$this->verify_json_api_authorization_request();
5938
5939
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5940
5941
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5942
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5943
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5944
	}
5945
5946
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5947
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5948
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5949
			return $url;
5950
		}
5951
5952
		$parsed_url = wp_parse_url( $url );
5953
		$url        = strtok( $url, '?' );
5954
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5955
		if ( ! empty( $parsed_url['query'] ) ) {
5956
			$url .= "&{$parsed_url['query']}";
5957
		}
5958
5959
		return $url;
5960
	}
5961
5962
	// Make sure the POSTed request is handled by the same action
5963
	function preserve_action_in_login_form_for_json_api_authorization() {
5964
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5965
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5966
	}
5967
5968
	// If someone logs in to approve API access, store the Access Code in usermeta
5969
	function store_json_api_authorization_token( $user_login, $user ) {
5970
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5971
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5972
		$token = wp_generate_password( 32, false );
5973
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5974
	}
5975
5976
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5977
	function allow_wpcom_public_api_domain( $domains ) {
5978
		$domains[] = 'public-api.wordpress.com';
5979
		return $domains;
5980
	}
5981
5982
	static function is_redirect_encoded( $redirect_url ) {
5983
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5984
	}
5985
5986
	// Add all wordpress.com environments to the safe redirect whitelist
5987
	function allow_wpcom_environments( $domains ) {
5988
		$domains[] = 'wordpress.com';
5989
		$domains[] = 'wpcalypso.wordpress.com';
5990
		$domains[] = 'horizon.wordpress.com';
5991
		$domains[] = 'calypso.localhost';
5992
		return $domains;
5993
	}
5994
5995
	// Add the Access Code details to the public-api.wordpress.com redirect
5996
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5997
		return add_query_arg(
5998
			urlencode_deep(
5999
				array(
6000
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6001
					'jetpack-user-id' => (int) $user->ID,
6002
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6003
				)
6004
			),
6005
			$redirect_to
6006
		);
6007
	}
6008
6009
6010
	/**
6011
	 * Verifies the request by checking the signature
6012
	 *
6013
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6014
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6015
	 *
6016
	 * @param null|array $environment
6017
	 */
6018
	function verify_json_api_authorization_request( $environment = null ) {
6019
		$environment = is_null( $environment )
6020
			? $_REQUEST
6021
			: $environment;
6022
6023
		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...
6024
		$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...
6025
		if ( ! $token || empty( $token->secret ) ) {
6026
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6027
		}
6028
6029
		$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' );
6030
6031
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6032
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6033
			/**
6034
			 * Jetpack authorisation request Error.
6035
			 *
6036
			 * @since 7.5.0
6037
			 */
6038
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6039
			$die_error = sprintf(
6040
				/* translators: %s is a URL */
6041
				__( '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' ),
6042
				Redirect::get_url( 'jetpack-support-double-encoding' )
6043
			);
6044
		}
6045
6046
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6047
6048
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6049
			$signature = $jetpack_signature->sign_request(
6050
				$environment['token'],
6051
				$environment['timestamp'],
6052
				$environment['nonce'],
6053
				'',
6054
				'GET',
6055
				$environment['jetpack_json_api_original_query'],
6056
				null,
6057
				true
6058
			);
6059
		} else {
6060
			$signature = $jetpack_signature->sign_current_request(
6061
				array(
6062
					'body'   => null,
6063
					'method' => 'GET',
6064
				)
6065
			);
6066
		}
6067
6068
		if ( ! $signature ) {
6069
			wp_die( $die_error );
6070
		} elseif ( is_wp_error( $signature ) ) {
6071
			wp_die( $die_error );
6072
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6073
			if ( is_ssl() ) {
6074
				// 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
6075
				$signature = $jetpack_signature->sign_current_request(
6076
					array(
6077
						'scheme' => 'http',
6078
						'body'   => null,
6079
						'method' => 'GET',
6080
					)
6081
				);
6082
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6083
					wp_die( $die_error );
6084
				}
6085
			} else {
6086
				wp_die( $die_error );
6087
			}
6088
		}
6089
6090
		$timestamp = (int) $environment['timestamp'];
6091
		$nonce     = stripslashes( (string) $environment['nonce'] );
6092
6093
		if ( ! $this->connection_manager ) {
6094
			$this->connection_manager = new Connection_Manager();
6095
		}
6096
6097
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6098
			// De-nonce the nonce, at least for 5 minutes.
6099
			// 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)
6100
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6101
			if ( $old_nonce_time < time() - 300 ) {
6102
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6103
			}
6104
		}
6105
6106
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6107
		$data_filters = array(
6108
			'state'        => 'opaque',
6109
			'client_id'    => 'int',
6110
			'client_title' => 'string',
6111
			'client_image' => 'url',
6112
		);
6113
6114
		foreach ( $data_filters as $key => $sanitation ) {
6115
			if ( ! isset( $data->$key ) ) {
6116
				wp_die( $die_error );
6117
			}
6118
6119
			switch ( $sanitation ) {
6120
				case 'int':
6121
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6122
					break;
6123
				case 'opaque':
6124
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6125
					break;
6126
				case 'string':
6127
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6128
					break;
6129
				case 'url':
6130
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6131
					break;
6132
			}
6133
		}
6134
6135
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6136
			wp_die( $die_error );
6137
		}
6138
	}
6139
6140
	function login_message_json_api_authorization( $message ) {
6141
		return '<p class="message">' . sprintf(
6142
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6143
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6144
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6145
	}
6146
6147
	/**
6148
	 * Get $content_width, but with a <s>twist</s> filter.
6149
	 */
6150
	public static function get_content_width() {
6151
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6152
			? $GLOBALS['content_width']
6153
			: false;
6154
		/**
6155
		 * Filter the Content Width value.
6156
		 *
6157
		 * @since 2.2.3
6158
		 *
6159
		 * @param string $content_width Content Width value.
6160
		 */
6161
		return apply_filters( 'jetpack_content_width', $content_width );
6162
	}
6163
6164
	/**
6165
	 * Pings the WordPress.com Mirror Site for the specified options.
6166
	 *
6167
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6168
	 *
6169
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6170
	 */
6171
	public function get_cloud_site_options( $option_names ) {
6172
		$option_names = array_filter( (array) $option_names, 'is_string' );
6173
6174
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6175
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6176
		if ( $xml->isError() ) {
6177
			return array(
6178
				'error_code' => $xml->getErrorCode(),
6179
				'error_msg'  => $xml->getErrorMessage(),
6180
			);
6181
		}
6182
		$cloud_site_options = $xml->getResponse();
6183
6184
		return $cloud_site_options;
6185
	}
6186
6187
	/**
6188
	 * Checks if the site is currently in an identity crisis.
6189
	 *
6190
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6191
	 */
6192
	public static function check_identity_crisis() {
6193
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6194
			return false;
6195
		}
6196
6197
		return Jetpack_Options::get_option( 'sync_error_idc' );
6198
	}
6199
6200
	/**
6201
	 * Checks whether the home and siteurl specifically are whitelisted
6202
	 * Written so that we don't have re-check $key and $value params every time
6203
	 * we want to check if this site is whitelisted, for example in footer.php
6204
	 *
6205
	 * @since  3.8.0
6206
	 * @return bool True = already whitelisted False = not whitelisted
6207
	 */
6208
	public static function is_staging_site() {
6209
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6210
		return ( new Status() )->is_staging_site();
6211
	}
6212
6213
	/**
6214
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6215
	 *
6216
	 * @since 4.4.0
6217
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6218
	 *
6219
	 * @return bool
6220
	 */
6221
	public static function validate_sync_error_idc_option() {
6222
		$is_valid = false;
6223
6224
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6225
		if ( false === $idc_allowed ) {
6226
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6227
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6228
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6229
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6230
				$transient_duration = HOUR_IN_SECONDS;
6231
			} else {
6232
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6233
				$idc_allowed        = '1';
6234
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6235
			}
6236
6237
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6238
		}
6239
6240
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6241
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6242
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6243
			$local_options = self::get_sync_error_idc_option();
6244
			// Ensure all values are set.
6245
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6246
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6247
					$is_valid = true;
6248
				}
6249
			}
6250
		}
6251
6252
		/**
6253
		 * Filters whether the sync_error_idc option is valid.
6254
		 *
6255
		 * @since 4.4.0
6256
		 *
6257
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6258
		 */
6259
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6260
6261
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6262
			// Since the option exists, and did not validate, delete it
6263
			Jetpack_Options::delete_option( 'sync_error_idc' );
6264
		}
6265
6266
		return $is_valid;
6267
	}
6268
6269
	/**
6270
	 * Normalizes a url by doing three things:
6271
	 *  - Strips protocol
6272
	 *  - Strips www
6273
	 *  - Adds a trailing slash
6274
	 *
6275
	 * @since 4.4.0
6276
	 * @param string $url
6277
	 * @return WP_Error|string
6278
	 */
6279
	public static function normalize_url_protocol_agnostic( $url ) {
6280
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6281
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6282
			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...
6283
		}
6284
6285
		// Strip www and protocols
6286
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6287
		return $url;
6288
	}
6289
6290
	/**
6291
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6292
	 *
6293
	 * @since 4.4.0
6294
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6295
	 *
6296
	 * @param array $response
6297
	 * @return array Array of the local urls, wpcom urls, and error code
6298
	 */
6299
	public static function get_sync_error_idc_option( $response = array() ) {
6300
		// Since the local options will hit the database directly, store the values
6301
		// in a transient to allow for autoloading and caching on subsequent views.
6302
		$local_options = get_transient( 'jetpack_idc_local' );
6303
		if ( false === $local_options ) {
6304
			$local_options = array(
6305
				'home'    => Functions::home_url(),
6306
				'siteurl' => Functions::site_url(),
6307
			);
6308
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6309
		}
6310
6311
		$options = array_merge( $local_options, $response );
6312
6313
		$returned_values = array();
6314
		foreach ( $options as $key => $option ) {
6315
			if ( 'error_code' === $key ) {
6316
				$returned_values[ $key ] = $option;
6317
				continue;
6318
			}
6319
6320
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6321
				continue;
6322
			}
6323
6324
			$returned_values[ $key ] = $normalized_url;
6325
		}
6326
6327
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6328
6329
		return $returned_values;
6330
	}
6331
6332
	/**
6333
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6334
	 * If set to true, the site will be put into staging mode.
6335
	 *
6336
	 * @since 4.3.2
6337
	 * @return bool
6338
	 */
6339
	public static function sync_idc_optin() {
6340
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6341
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6342
		} else {
6343
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6344
		}
6345
6346
		/**
6347
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6348
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6349
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6350
		 *
6351
		 * @since 4.3.2
6352
		 *
6353
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6354
		 */
6355
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6356
	}
6357
6358
	/**
6359
	 * Maybe Use a .min.css stylesheet, maybe not.
6360
	 *
6361
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6362
	 */
6363
	public static function maybe_min_asset( $url, $path, $plugin ) {
6364
		// Short out on things trying to find actual paths.
6365
		if ( ! $path || empty( $plugin ) ) {
6366
			return $url;
6367
		}
6368
6369
		$path = ltrim( $path, '/' );
6370
6371
		// Strip out the abspath.
6372
		$base = dirname( plugin_basename( $plugin ) );
6373
6374
		// Short out on non-Jetpack assets.
6375
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6376
			return $url;
6377
		}
6378
6379
		// File name parsing.
6380
		$file              = "{$base}/{$path}";
6381
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6382
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6383
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6384
		$extension         = array_shift( $file_name_parts_r );
6385
6386
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6387
			// Already pointing at the minified version.
6388
			if ( 'min' === $file_name_parts_r[0] ) {
6389
				return $url;
6390
			}
6391
6392
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6393
			if ( file_exists( $min_full_path ) ) {
6394
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6395
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6396
				if ( 'css' === $extension ) {
6397
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6398
					self::$min_assets[ $key ] = $path;
6399
				}
6400
			}
6401
		}
6402
6403
		return $url;
6404
	}
6405
6406
	/**
6407
	 * If the asset is minified, let's flag .min as the suffix.
6408
	 *
6409
	 * Attached to `style_loader_src` filter.
6410
	 *
6411
	 * @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...
6412
	 * @param string $handle The registered handle of the script in question.
6413
	 * @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...
6414
	 */
6415
	public static function set_suffix_on_min( $src, $handle ) {
6416
		if ( false === strpos( $src, '.min.css' ) ) {
6417
			return $src;
6418
		}
6419
6420
		if ( ! empty( self::$min_assets ) ) {
6421
			foreach ( self::$min_assets as $file => $path ) {
6422
				if ( false !== strpos( $src, $file ) ) {
6423
					wp_style_add_data( $handle, 'suffix', '.min' );
6424
					return $src;
6425
				}
6426
			}
6427
		}
6428
6429
		return $src;
6430
	}
6431
6432
	/**
6433
	 * Maybe inlines a stylesheet.
6434
	 *
6435
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6436
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6437
	 *
6438
	 * Attached to `style_loader_tag` filter.
6439
	 *
6440
	 * @param string $tag The tag that would link to the external asset.
6441
	 * @param string $handle The registered handle of the script in question.
6442
	 *
6443
	 * @return string
6444
	 */
6445
	public static function maybe_inline_style( $tag, $handle ) {
6446
		global $wp_styles;
6447
		$item = $wp_styles->registered[ $handle ];
6448
6449
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6450
			return $tag;
6451
		}
6452
6453
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6454
			$href = $matches[1];
6455
			// Strip off query string
6456
			if ( $pos = strpos( $href, '?' ) ) {
6457
				$href = substr( $href, 0, $pos );
6458
			}
6459
			// Strip off fragment
6460
			if ( $pos = strpos( $href, '#' ) ) {
6461
				$href = substr( $href, 0, $pos );
6462
			}
6463
		} else {
6464
			return $tag;
6465
		}
6466
6467
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6468
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6469
			return $tag;
6470
		}
6471
6472
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6473
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6474
			// And this isn't the pass that actually deals with the RTL version...
6475
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6476
				// Short out, as the RTL version will deal with it in a moment.
6477
				return $tag;
6478
			}
6479
		}
6480
6481
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6482
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6483
		if ( $css ) {
6484
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6485
			if ( empty( $item->extra['after'] ) ) {
6486
				wp_add_inline_style( $handle, $css );
6487
			} else {
6488
				array_unshift( $item->extra['after'], $css );
6489
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6490
			}
6491
		}
6492
6493
		return $tag;
6494
	}
6495
6496
	/**
6497
	 * Loads a view file from the views
6498
	 *
6499
	 * Data passed in with the $data parameter will be available in the
6500
	 * template file as $data['value']
6501
	 *
6502
	 * @param string $template - Template file to load
6503
	 * @param array  $data - Any data to pass along to the template
6504
	 * @return boolean - If template file was found
6505
	 **/
6506
	public function load_view( $template, $data = array() ) {
6507
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6508
6509
		if ( file_exists( $views_dir . $template ) ) {
6510
			require_once $views_dir . $template;
6511
			return true;
6512
		}
6513
6514
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6515
		return false;
6516
	}
6517
6518
	/**
6519
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6520
	 */
6521
	public function deprecated_hooks() {
6522
		global $wp_filter;
6523
6524
		/*
6525
		 * Format:
6526
		 * deprecated_filter_name => replacement_name
6527
		 *
6528
		 * If there is no replacement, use null for replacement_name
6529
		 */
6530
		$deprecated_list = array(
6531
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6532
			'wpl_sharing_2014_1'                           => null,
6533
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6534
			'jetpack_identity_crisis_options_to_check'     => null,
6535
			'update_option_jetpack_single_user_site'       => null,
6536
			'audio_player_default_colors'                  => null,
6537
			'add_option_jetpack_featured_images_enabled'   => null,
6538
			'add_option_jetpack_update_details'            => null,
6539
			'add_option_jetpack_updates'                   => null,
6540
			'add_option_jetpack_network_name'              => null,
6541
			'add_option_jetpack_network_allow_new_registrations' => null,
6542
			'add_option_jetpack_network_add_new_users'     => null,
6543
			'add_option_jetpack_network_site_upload_space' => null,
6544
			'add_option_jetpack_network_upload_file_types' => null,
6545
			'add_option_jetpack_network_enable_administration_menus' => null,
6546
			'add_option_jetpack_is_multi_site'             => null,
6547
			'add_option_jetpack_is_main_network'           => null,
6548
			'add_option_jetpack_main_network_site'         => null,
6549
			'jetpack_sync_all_registered_options'          => null,
6550
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6551
			'jetpack_is_post_mailable'                     => null,
6552
			'jetpack_seo_site_host'                        => null,
6553
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6554
			'jetpack_holiday_snow_option_name'             => null,
6555
			'jetpack_holiday_chance_of_snow'               => null,
6556
			'jetpack_holiday_snow_js_url'                  => null,
6557
			'jetpack_is_holiday_snow_season'               => null,
6558
			'jetpack_holiday_snow_option_updated'          => null,
6559
			'jetpack_holiday_snowing'                      => null,
6560
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6561
			'jetpack_cache_plans'                          => null,
6562
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6563
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6564
			'jetpack_enable_site_verification'             => null,
6565
			'can_display_jetpack_manage_notice'            => null,
6566
			// Removed in Jetpack 7.3.0
6567
			'atd_load_scripts'                             => null,
6568
			'atd_http_post_timeout'                        => null,
6569
			'atd_http_post_error'                          => null,
6570
			'atd_service_domain'                           => null,
6571
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6572
			// Removed in Jetpack 7.9.0
6573
			'jetpack_pwa_manifest'                         => null,
6574
			'jetpack_pwa_background_color'                 => null,
6575
			// Removed in Jetpack 8.3.0.
6576
			'jetpack_check_mobile'                         => null,
6577
			'jetpack_mobile_stylesheet'                    => null,
6578
			'jetpack_mobile_template'                      => null,
6579
			'mobile_reject_mobile'                         => null,
6580
			'mobile_force_mobile'                          => null,
6581
			'mobile_app_promo_download'                    => null,
6582
			'mobile_setup'                                 => null,
6583
			'jetpack_mobile_footer_before'                 => null,
6584
			'wp_mobile_theme_footer'                       => null,
6585
			'minileven_credits'                            => null,
6586
			'jetpack_mobile_header_before'                 => null,
6587
			'jetpack_mobile_header_after'                  => null,
6588
			'jetpack_mobile_theme_menu'                    => null,
6589
			'minileven_show_featured_images'               => null,
6590
			'minileven_attachment_size'                    => null,
6591
		);
6592
6593
		// This is a silly loop depth. Better way?
6594
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6595
			if ( has_action( $hook ) ) {
6596
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6597
					foreach ( $values as $hooked ) {
6598
						if ( is_callable( $hooked['function'] ) ) {
6599
							$function_name = $hooked['function'];
6600
						} else {
6601
							$function_name = 'an anonymous function';
6602
						}
6603
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6604
					}
6605
				}
6606
			}
6607
		}
6608
	}
6609
6610
	/**
6611
	 * Converts any url in a stylesheet, to the correct absolute url.
6612
	 *
6613
	 * Considerations:
6614
	 *  - Normal, relative URLs     `feh.png`
6615
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6616
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6617
	 *  - Absolute URLs             `http://domain.com/feh.png`
6618
	 *  - Domain root relative URLs `/feh.png`
6619
	 *
6620
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6621
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6622
	 *
6623
	 * @return mixed|string
6624
	 */
6625
	public static function absolutize_css_urls( $css, $css_file_url ) {
6626
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6627
		$css_dir = dirname( $css_file_url );
6628
		$p       = wp_parse_url( $css_dir );
6629
		$domain  = sprintf(
6630
			'%1$s//%2$s%3$s%4$s',
6631
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6632
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6633
			$p['host'],
6634
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6635
		);
6636
6637
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6638
			$find = $replace = array();
6639
			foreach ( $matches as $match ) {
6640
				$url = trim( $match['path'], "'\" \t" );
6641
6642
				// If this is a data url, we don't want to mess with it.
6643
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6644
					continue;
6645
				}
6646
6647
				// If this is an absolute or protocol-agnostic url,
6648
				// we don't want to mess with it.
6649
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6650
					continue;
6651
				}
6652
6653
				switch ( substr( $url, 0, 1 ) ) {
6654
					case '/':
6655
						$absolute = $domain . $url;
6656
						break;
6657
					default:
6658
						$absolute = $css_dir . '/' . $url;
6659
				}
6660
6661
				$find[]    = $match[0];
6662
				$replace[] = sprintf( 'url("%s")', $absolute );
6663
			}
6664
			$css = str_replace( $find, $replace, $css );
6665
		}
6666
6667
		return $css;
6668
	}
6669
6670
	/**
6671
	 * This methods removes all of the registered css files on the front end
6672
	 * from Jetpack in favor of using a single file. In effect "imploding"
6673
	 * all the files into one file.
6674
	 *
6675
	 * Pros:
6676
	 * - Uses only ONE css asset connection instead of 15
6677
	 * - Saves a minimum of 56k
6678
	 * - Reduces server load
6679
	 * - Reduces time to first painted byte
6680
	 *
6681
	 * Cons:
6682
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6683
	 *      should not cause any issues with themes.
6684
	 * - Plugins/themes dequeuing styles no longer do anything. See
6685
	 *      jetpack_implode_frontend_css filter for a workaround
6686
	 *
6687
	 * For some situations developers may wish to disable css imploding and
6688
	 * instead operate in legacy mode where each file loads seperately and
6689
	 * can be edited individually or dequeued. This can be accomplished with
6690
	 * the following line:
6691
	 *
6692
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6693
	 *
6694
	 * @since 3.2
6695
	 **/
6696
	public function implode_frontend_css( $travis_test = false ) {
6697
		$do_implode = true;
6698
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6699
			$do_implode = false;
6700
		}
6701
6702
		// Do not implode CSS when the page loads via the AMP plugin.
6703
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6704
			$do_implode = false;
6705
		}
6706
6707
		/**
6708
		 * Allow CSS to be concatenated into a single jetpack.css file.
6709
		 *
6710
		 * @since 3.2.0
6711
		 *
6712
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6713
		 */
6714
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6715
6716
		// Do not use the imploded file when default behavior was altered through the filter
6717
		if ( ! $do_implode ) {
6718
			return;
6719
		}
6720
6721
		// We do not want to use the imploded file in dev mode, or if not connected
6722
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6723
			if ( ! $travis_test ) {
6724
				return;
6725
			}
6726
		}
6727
6728
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6729
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6730
			return;
6731
		}
6732
6733
		/*
6734
		 * Now we assume Jetpack is connected and able to serve the single
6735
		 * file.
6736
		 *
6737
		 * In the future there will be a check here to serve the file locally
6738
		 * or potentially from the Jetpack CDN
6739
		 *
6740
		 * For now:
6741
		 * - Enqueue a single imploded css file
6742
		 * - Zero out the style_loader_tag for the bundled ones
6743
		 * - Be happy, drink scotch
6744
		 */
6745
6746
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6747
6748
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6749
6750
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6751
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6752
	}
6753
6754
	function concat_remove_style_loader_tag( $tag, $handle ) {
6755
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6756
			$tag = '';
6757
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6758
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6759
			}
6760
		}
6761
6762
		return $tag;
6763
	}
6764
6765
	/**
6766
	 * @deprecated
6767
	 * @see Automattic\Jetpack\Assets\add_aync_script
6768
	 */
6769
	public function script_add_async( $tag, $handle, $src ) {
6770
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6771
	}
6772
6773
	/*
6774
	 * Check the heartbeat data
6775
	 *
6776
	 * Organizes the heartbeat data by severity.  For example, if the site
6777
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6778
	 *
6779
	 * Data will be added to "caution" array, if it either:
6780
	 *  - Out of date Jetpack version
6781
	 *  - Out of date WP version
6782
	 *  - Out of date PHP version
6783
	 *
6784
	 * $return array $filtered_data
6785
	 */
6786
	public static function jetpack_check_heartbeat_data() {
6787
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6788
6789
		$good    = array();
6790
		$caution = array();
6791
		$bad     = array();
6792
6793
		foreach ( $raw_data as $stat => $value ) {
6794
6795
			// Check jetpack version
6796
			if ( 'version' == $stat ) {
6797
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6798
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6799
					continue;
6800
				}
6801
			}
6802
6803
			// Check WP version
6804
			if ( 'wp-version' == $stat ) {
6805
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6806
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6807
					continue;
6808
				}
6809
			}
6810
6811
			// Check PHP version
6812
			if ( 'php-version' == $stat ) {
6813
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6814
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6815
					continue;
6816
				}
6817
			}
6818
6819
			// Check ID crisis
6820
			if ( 'identitycrisis' == $stat ) {
6821
				if ( 'yes' == $value ) {
6822
					$bad[ $stat ] = $value;
6823
					continue;
6824
				}
6825
			}
6826
6827
			// The rest are good :)
6828
			$good[ $stat ] = $value;
6829
		}
6830
6831
		$filtered_data = array(
6832
			'good'    => $good,
6833
			'caution' => $caution,
6834
			'bad'     => $bad,
6835
		);
6836
6837
		return $filtered_data;
6838
	}
6839
6840
6841
	/*
6842
	 * This method is used to organize all options that can be reset
6843
	 * without disconnecting Jetpack.
6844
	 *
6845
	 * It is used in class.jetpack-cli.php to reset options
6846
	 *
6847
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6848
	 *
6849
	 * @return array of options to delete.
6850
	 */
6851
	public static function get_jetpack_options_for_reset() {
6852
		return Jetpack_Options::get_options_for_reset();
6853
	}
6854
6855
	/*
6856
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6857
	 * so we can bring them directly to their site in calypso.
6858
	 *
6859
	 * @param string | url
6860
	 * @return string | url without the guff
6861
	 */
6862 View Code Duplication
	public static function build_raw_urls( $url ) {
6863
		$strip_http = '/.*?:\/\//i';
6864
		$url        = preg_replace( $strip_http, '', $url );
6865
		$url        = str_replace( '/', '::', $url );
6866
		return $url;
6867
	}
6868
6869
	/**
6870
	 * Stores and prints out domains to prefetch for page speed optimization.
6871
	 *
6872
	 * @param mixed $new_urls
6873
	 */
6874
	public static function dns_prefetch( $new_urls = null ) {
6875
		static $prefetch_urls = array();
6876
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6877
			echo "\r\n";
6878
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6879
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6880
			}
6881
		} elseif ( ! empty( $new_urls ) ) {
6882
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6883
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6884
			}
6885
			foreach ( (array) $new_urls as $this_new_url ) {
6886
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6887
			}
6888
			$prefetch_urls = array_unique( $prefetch_urls );
6889
		}
6890
	}
6891
6892
	public function wp_dashboard_setup() {
6893
		if ( self::is_active() ) {
6894
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6895
		}
6896
6897
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6898
			$jetpack_logo = new Jetpack_Logo();
6899
			$widget_title = sprintf(
6900
				wp_kses(
6901
					/* translators: Placeholder is a Jetpack logo. */
6902
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6903
					array( 'span' => array() )
6904
				),
6905
				$jetpack_logo->get_jp_emblem( true )
6906
			);
6907
6908
			wp_add_dashboard_widget(
6909
				'jetpack_summary_widget',
6910
				$widget_title,
6911
				array( __CLASS__, 'dashboard_widget' )
6912
			);
6913
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6914
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6915
6916
			// If we're inactive and not in development mode, sort our box to the top.
6917
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6918
				global $wp_meta_boxes;
6919
6920
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6921
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6922
6923
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6924
			}
6925
		}
6926
	}
6927
6928
	/**
6929
	 * @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...
6930
	 * @return mixed
6931
	 */
6932
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6933
		if ( ! is_array( $sorted ) ) {
6934
			return $sorted;
6935
		}
6936
6937
		foreach ( $sorted as $box_context => $ids ) {
6938
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6939
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6940
				continue;
6941
			}
6942
6943
			$ids_array = explode( ',', $ids );
6944
			$key       = array_search( 'dashboard_stats', $ids_array );
6945
6946
			if ( false !== $key ) {
6947
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6948
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6949
				$sorted[ $box_context ] = implode( ',', $ids_array );
6950
				// We've found it, stop searching, and just return.
6951
				break;
6952
			}
6953
		}
6954
6955
		return $sorted;
6956
	}
6957
6958
	public static function dashboard_widget() {
6959
		/**
6960
		 * Fires when the dashboard is loaded.
6961
		 *
6962
		 * @since 3.4.0
6963
		 */
6964
		do_action( 'jetpack_dashboard_widget' );
6965
	}
6966
6967
	public static function dashboard_widget_footer() {
6968
		?>
6969
		<footer>
6970
6971
		<div class="protect">
6972
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6973
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6974
				<p class="blocked-count">
6975
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6976
				</p>
6977
				<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>
6978
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6979
				<a href="
6980
				<?php
6981
				echo esc_url(
6982
					wp_nonce_url(
6983
						self::admin_url(
6984
							array(
6985
								'action' => 'activate',
6986
								'module' => 'protect',
6987
							)
6988
						),
6989
						'jetpack_activate-protect'
6990
					)
6991
				);
6992
				?>
6993
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6994
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6995
				</a>
6996
			<?php else : ?>
6997
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6998
			<?php endif; ?>
6999
		</div>
7000
7001
		<div class="akismet">
7002
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7003
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7004
				<p class="blocked-count">
7005
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7006
				</p>
7007
				<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>
7008
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7009
				<a href="
7010
				<?php
7011
				echo esc_url(
7012
					wp_nonce_url(
7013
						add_query_arg(
7014
							array(
7015
								'action' => 'activate',
7016
								'plugin' => 'akismet/akismet.php',
7017
							),
7018
							admin_url( 'plugins.php' )
7019
						),
7020
						'activate-plugin_akismet/akismet.php'
7021
					)
7022
				);
7023
				?>
7024
							" class="button button-jetpack">
7025
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7026
				</a>
7027
			<?php else : ?>
7028
				<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>
7029
			<?php endif; ?>
7030
		</div>
7031
7032
		</footer>
7033
		<?php
7034
	}
7035
7036
	/*
7037
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7038
	 */
7039
	function jetpack_icon_user_connected( $columns ) {
7040
		$columns['user_jetpack'] = '';
7041
		return $columns;
7042
	}
7043
7044
	/*
7045
	 * Show Jetpack icon if the user is linked.
7046
	 */
7047
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7048
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7049
			$jetpack_logo = new Jetpack_Logo();
7050
			$emblem_html  = sprintf(
7051
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7052
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7053
				$jetpack_logo->get_jp_emblem()
7054
			);
7055
			return $emblem_html;
7056
		}
7057
7058
		return $val;
7059
	}
7060
7061
	/*
7062
	 * Style the Jetpack user column
7063
	 */
7064
	function jetpack_user_col_style() {
7065
		global $current_screen;
7066
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7067
			?>
7068
			<style>
7069
				.fixed .column-user_jetpack {
7070
					width: 21px;
7071
				}
7072
				.jp-emblem-user-admin svg {
7073
					width: 20px;
7074
					height: 20px;
7075
				}
7076
				.jp-emblem-user-admin path {
7077
					fill: #00BE28;
7078
				}
7079
			</style>
7080
			<?php
7081
		}
7082
	}
7083
7084
	/**
7085
	 * Checks if Akismet is active and working.
7086
	 *
7087
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7088
	 * that implied usage of methods present since more recent version.
7089
	 * See https://github.com/Automattic/jetpack/pull/9585
7090
	 *
7091
	 * @since  5.1.0
7092
	 *
7093
	 * @return bool True = Akismet available. False = Aksimet not available.
7094
	 */
7095
	public static function is_akismet_active() {
7096
		static $status = null;
7097
7098
		if ( ! is_null( $status ) ) {
7099
			return $status;
7100
		}
7101
7102
		// Check if a modern version of Akismet is active.
7103
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7104
			$status = false;
7105
			return $status;
7106
		}
7107
7108
		// Make sure there is a key known to Akismet at all before verifying key.
7109
		$akismet_key = Akismet::get_api_key();
7110
		if ( ! $akismet_key ) {
7111
			$status = false;
7112
			return $status;
7113
		}
7114
7115
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7116
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7117
7118
		// 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.
7119
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7120
		// We cache the result of the Akismet key verification for ten minutes.
7121
		if ( ! $akismet_key_state || $recheck ) {
7122
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7123
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7124
		}
7125
7126
		$status = 'valid' === $akismet_key_state;
7127
7128
		return $status;
7129
	}
7130
7131
	/**
7132
	 * @deprecated
7133
	 *
7134
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7135
	 */
7136
	public static function is_function_in_backtrace() {
7137
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7138
	}
7139
7140
	/**
7141
	 * Given a minified path, and a non-minified path, will return
7142
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7143
	 *
7144
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7145
	 * root Jetpack directory.
7146
	 *
7147
	 * @since 5.6.0
7148
	 *
7149
	 * @param string $min_path
7150
	 * @param string $non_min_path
7151
	 * @return string The URL to the file
7152
	 */
7153
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7154
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7155
	}
7156
7157
	/**
7158
	 * Checks for whether Jetpack Backup is enabled.
7159
	 * Will return true if the state of Backup is anything except "unavailable".
7160
	 *
7161
	 * @return bool|int|mixed
7162
	 */
7163
	public static function is_rewind_enabled() {
7164
		if ( ! self::is_active() ) {
7165
			return false;
7166
		}
7167
7168
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7169
		if ( false === $rewind_enabled ) {
7170
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7171
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7172
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7173
				&& ! empty( $rewind_data['state'] )
7174
				&& 'active' === $rewind_data['state'] )
7175
				? 1
7176
				: 0;
7177
7178
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7179
		}
7180
		return $rewind_enabled;
7181
	}
7182
7183
	/**
7184
	 * Return Calypso environment value; used for developing Jetpack and pairing
7185
	 * it with different Calypso enrionments, such as localhost.
7186
	 *
7187
	 * @since 7.4.0
7188
	 *
7189
	 * @return string Calypso environment
7190
	 */
7191
	public static function get_calypso_env() {
7192
		if ( isset( $_GET['calypso_env'] ) ) {
7193
			return sanitize_key( $_GET['calypso_env'] );
7194
		}
7195
7196
		if ( getenv( 'CALYPSO_ENV' ) ) {
7197
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7198
		}
7199
7200
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7201
			return sanitize_key( CALYPSO_ENV );
7202
		}
7203
7204
		return '';
7205
	}
7206
7207
	/**
7208
	 * Returns the hostname with protocol for Calypso.
7209
	 * Used for developing Jetpack with Calypso.
7210
	 *
7211
	 * @since 8.4.0
7212
	 *
7213
	 * @return string Calypso host.
7214
	 */
7215
	public static function get_calypso_host() {
7216
		$calypso_env = self::get_calypso_env();
7217
		switch ( $calypso_env ) {
7218
			case 'development':
7219
				return 'http://calypso.localhost:3000/';
7220
			case 'wpcalypso':
7221
				return 'https://wpcalypso.wordpress.com/';
7222
			case 'horizon':
7223
				return 'https://horizon.wordpress.com/';
7224
			default:
7225
				return 'https://wordpress.com/';
7226
		}
7227
	}
7228
7229
	/**
7230
	 * Checks whether or not TOS has been agreed upon.
7231
	 * Will return true if a user has clicked to register, or is already connected.
7232
	 */
7233
	public static function jetpack_tos_agreed() {
7234
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7235
7236
		$terms_of_service = new Terms_Of_Service();
7237
		return $terms_of_service->has_agreed();
7238
7239
	}
7240
7241
	/**
7242
	 * Handles activating default modules as well general cleanup for the new connection.
7243
	 *
7244
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7245
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7246
	 * @param boolean $send_state_messages          Whether to send state messages.
7247
	 * @return void
7248
	 */
7249
	public static function handle_post_authorization_actions(
7250
		$activate_sso = false,
7251
		$redirect_on_activation_error = false,
7252
		$send_state_messages = true
7253
	) {
7254
		$other_modules = $activate_sso
7255
			? array( 'sso' )
7256
			: array();
7257
7258
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7259
			self::delete_active_modules();
7260
7261
			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...
7262
		} else {
7263
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7264
		}
7265
7266
		// Since this is a fresh connection, be sure to clear out IDC options
7267
		Jetpack_IDC::clear_all_idc_options();
7268
7269
		if ( $send_state_messages ) {
7270
			self::state( 'message', 'authorized' );
7271
		}
7272
	}
7273
7274
	/**
7275
	 * Returns a boolean for whether backups UI should be displayed or not.
7276
	 *
7277
	 * @return bool Should backups UI be displayed?
7278
	 */
7279
	public static function show_backups_ui() {
7280
		/**
7281
		 * Whether UI for backups should be displayed.
7282
		 *
7283
		 * @since 6.5.0
7284
		 *
7285
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7286
		 */
7287
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7288
	}
7289
7290
	/*
7291
	 * Deprecated manage functions
7292
	 */
7293
	function prepare_manage_jetpack_notice() {
7294
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7295
	}
7296
	function manage_activate_screen() {
7297
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7298
	}
7299
	function admin_jetpack_manage_notice() {
7300
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7301
	}
7302
	function opt_out_jetpack_manage_url() {
7303
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7304
	}
7305
	function opt_in_jetpack_manage_url() {
7306
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7307
	}
7308
	function opt_in_jetpack_manage_notice() {
7309
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7310
	}
7311
	function can_display_jetpack_manage_notice() {
7312
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7313
	}
7314
7315
	/**
7316
	 * Clean leftoveruser meta.
7317
	 *
7318
	 * Delete Jetpack-related user meta when it is no longer needed.
7319
	 *
7320
	 * @since 7.3.0
7321
	 *
7322
	 * @param int $user_id User ID being updated.
7323
	 */
7324
	public static function user_meta_cleanup( $user_id ) {
7325
		$meta_keys = array(
7326
			// AtD removed from Jetpack 7.3
7327
			'AtD_options',
7328
			'AtD_check_when',
7329
			'AtD_guess_lang',
7330
			'AtD_ignored_phrases',
7331
		);
7332
7333
		foreach ( $meta_keys as $meta_key ) {
7334
			if ( get_user_meta( $user_id, $meta_key ) ) {
7335
				delete_user_meta( $user_id, $meta_key );
7336
			}
7337
		}
7338
	}
7339
7340
	/**
7341
	 * Checks if a Jetpack site is both active and not in development.
7342
	 *
7343
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7344
	 *
7345
	 * @return bool True if Jetpack is active and not in development.
7346
	 */
7347
	public static function is_active_and_not_development_mode() {
7348
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7349
			return false;
7350
		}
7351
		return true;
7352
	}
7353
7354
	/**
7355
	 * Returns the list of products that we have available for purchase.
7356
	 */
7357
	public static function get_products_for_purchase() {
7358
		$products = array();
7359
		if ( ! is_multisite() ) {
7360
			$products[] = array(
7361
				'key'               => 'backup',
7362
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7363
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7364
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7365
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7366
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7367
				'options'           => array(
7368
					array(
7369
						'type'        => 'daily',
7370
						'slug'        => 'jetpack-backup-daily',
7371
						'key'         => 'jetpack_backup_daily',
7372
						'name'        => __( 'Daily Backups', 'jetpack' ),
7373
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7374
					),
7375
					array(
7376
						'type'        => 'realtime',
7377
						'slug'        => 'jetpack-backup-realtime',
7378
						'key'         => 'jetpack_backup_realtime',
7379
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7380
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7381
					),
7382
				),
7383
				'default_option'    => 'realtime',
7384
				'show_promotion'    => true,
7385
				'discount_percent'  => 70,
7386
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7387
			);
7388
7389
			$products[] = array(
7390
				'key'               => 'scan',
7391
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7392
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7393
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7394
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7395
				'show_promotion'    => true,
7396
				'discount_percent'  => 30,
7397
				'options'           => array(
7398
					array(
7399
						'type'      => 'scan',
7400
						'slug'      => 'jetpack-scan',
7401
						'key'       => 'jetpack_scan',
7402
						'name'      => __( 'Daily Scan', 'jetpack' ),
7403
					),
7404
				),
7405
				'default_option'    => 'scan',
7406
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7407
			);
7408
		}
7409
7410
		$products[] = array(
7411
			'key'               => 'search',
7412
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7413
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7414
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7415
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7416
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7417
			'options'           => array(
7418
				array(
7419
					'type'      => 'search',
7420
					'slug'      => 'jetpack-search',
7421
					'key'       => 'jetpack_search',
7422
					'name'      => __( 'Search', 'jetpack' ),
7423
				),
7424
			),
7425
			'tears'             => array(),
7426
			'default_option'    => 'search',
7427
			'show_promotion'    => false,
7428
			'included_in_plans' => array( 'search-plan' ),
7429
		);
7430
7431
		return $products;
7432
	}
7433
}
7434