Completed
Push — update/donations-show-payment-... ( 7233b1...9e3428 )
by
unknown
21:41 queued 13:41
created

class.jetpack.php (83 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\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Health;
15
use Automattic\Jetpack\Sync\Sender;
16
use Automattic\Jetpack\Sync\Users;
17
use Automattic\Jetpack\Terms_Of_Service;
18
use Automattic\Jetpack\Tracking;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
22
23
/*
24
Options:
25
jetpack_options (array)
26
	An array of options.
27
	@see Jetpack_Options::get_option_names()
28
29
jetpack_register (string)
30
	Temporary verification secrets.
31
32
jetpack_activated (int)
33
	1: the plugin was activated normally
34
	2: the plugin was activated on this site because of a network-wide activation
35
	3: the plugin was auto-installed
36
	4: the plugin was manually disconnected (but is still installed)
37
38
jetpack_active_modules (array)
39
	Array of active module slugs.
40
41
jetpack_do_activate (bool)
42
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
43
*/
44
45
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
46
47
class Jetpack {
48
	public $xmlrpc_server = null;
49
50
	private $rest_authentication_status = null;
51
52
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
53
54
	/**
55
	 * @var array The handles of styles that are concatenated into jetpack.css.
56
	 *
57
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
58
	 */
59
	public $concatenated_style_handles = array(
60
		'jetpack-carousel',
61
		'grunion.css',
62
		'the-neverending-homepage',
63
		'jetpack_likes',
64
		'jetpack_related-posts',
65
		'sharedaddy',
66
		'jetpack-slideshow',
67
		'presentations',
68
		'quiz',
69
		'jetpack-subscriptions',
70
		'jetpack-responsive-videos-style',
71
		'jetpack-social-menu',
72
		'tiled-gallery',
73
		'jetpack_display_posts_widget',
74
		'gravatar-profile-widget',
75
		'goodreads-widget',
76
		'jetpack_social_media_icons_widget',
77
		'jetpack-top-posts-widget',
78
		'jetpack_image_widget',
79
		'jetpack-my-community-widget',
80
		'jetpack-authors-widget',
81
		'wordads',
82
		'eu-cookie-law-style',
83
		'flickr-widget-style',
84
		'jetpack-search-widget',
85
		'jetpack-simple-payments-widget-style',
86
		'jetpack-widget-social-icons-styles',
87
		'wpcom_instagram_widget',
88
	);
89
90
	/**
91
	 * Contains all assets that have had their URL rewritten to minified versions.
92
	 *
93
	 * @var array
94
	 */
95
	static $min_assets = array();
96
97
	public $plugins_to_deactivate = array(
98
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
99
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
100
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
101
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
102
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
103
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
104
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
105
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
106
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
107
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
108
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
109
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
110
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
111
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
112
	);
113
114
	/**
115
	 * Map of roles we care about, and their corresponding minimum capabilities.
116
	 *
117
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
118
	 *
119
	 * @access public
120
	 * @static
121
	 *
122
	 * @var array
123
	 */
124
	public static $capability_translations = array(
125
		'administrator' => 'manage_options',
126
		'editor'        => 'edit_others_posts',
127
		'author'        => 'publish_posts',
128
		'contributor'   => 'edit_posts',
129
		'subscriber'    => 'read',
130
	);
131
132
	/**
133
	 * Map of modules that have conflicts with plugins and should not be auto-activated
134
	 * if the plugins are active.  Used by filter_default_modules
135
	 *
136
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
137
	 * change `module-slug` and add this to your plugin:
138
	 *
139
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
140
	 * function my_jetpack_get_default_modules( $modules ) {
141
	 *     return array_diff( $modules, array( 'module-slug' ) );
142
	 * }
143
	 *
144
	 * @var array
145
	 */
146
	private $conflicting_plugins = array(
147
		'comments'           => array(
148
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
149
			'Disqus'                         => 'disqus-comment-system/disqus.php',
150
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
151
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
152
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
153
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
154
		),
155
		'comment-likes'      => array(
156
			'Epoch' => 'epoch/plugincore.php',
157
		),
158
		'contact-form'       => array(
159
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
160
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
161
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
162
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
163
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
164
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
165
		),
166
		'latex'              => array(
167
			'LaTeX for WordPress'     => 'latex/latex.php',
168
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
169
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
170
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
171
			'Enable Latex'            => 'enable-latex/enable-latex.php',
172
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
173
		),
174
		'protect'            => array(
175
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
176
			'Captcha'                           => 'captcha/captcha.php',
177
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
178
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
179
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
180
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
181
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
182
			'Security-protection'               => 'security-protection/security-protection.php',
183
			'Login Security'                    => 'login-security/login-security.php',
184
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
185
			'Wordfence Security'                => 'wordfence/wordfence.php',
186
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
187
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
188
		),
189
		'random-redirect'    => array(
190
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
191
		),
192
		'related-posts'      => array(
193
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
194
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
195
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
196
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
197
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
198
			'outbrain'                    => 'outbrain/outbrain.php',
199
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
200
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
201
		),
202
		'sharedaddy'         => array(
203
			'AddThis'     => 'addthis/addthis_social_widget.php',
204
			'Add To Any'  => 'add-to-any/add-to-any.php',
205
			'ShareThis'   => 'share-this/sharethis.php',
206
			'Shareaholic' => 'shareaholic/shareaholic.php',
207
		),
208
		'seo-tools'          => array(
209
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
210
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
211
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
212
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
213
			'The SEO Framework'              => 'autodescription/autodescription.php',
214
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
215
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
216
		),
217
		'verification-tools' => array(
218
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
219
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
220
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
221
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
222
			'The SEO Framework'              => 'autodescription/autodescription.php',
223
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
224
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
225
		),
226
		'widget-visibility'  => array(
227
			'Widget Logic'    => 'widget-logic/widget_logic.php',
228
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
229
		),
230
		'sitemaps'           => array(
231
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
232
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
233
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
234
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
235
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
236
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
237
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
238
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
239
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
240
			'The SEO Framework'                    => 'autodescription/autodescription.php',
241
			'Sitemap'                              => 'sitemap/sitemap.php',
242
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
243
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
244
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
245
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
246
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
247
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
248
		),
249
		'lazy-images'        => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		// 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
271
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
272
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
273
		// Open Graph Meta Tags by Heateor
274
		'facebook/facebook.php',                                 // Facebook (official plugin)
275
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
276
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
277
		// Facebook Featured Image & OG Meta Tags
278
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
279
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
280
		// Facebook Open Graph Meta Tags for WordPress
281
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
282
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
283
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
284
		// Fedmich's Facebook Open Graph Meta
285
		'network-publisher/networkpub.php',                      // Network Publisher
286
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
287
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
288
		// NextScripts SNAP
289
		'og-tags/og-tags.php',                                   // OG Tags
290
		'opengraph/opengraph.php',                               // Open Graph
291
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
292
		// Open Graph Protocol Framework
293
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
294
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
295
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
296
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
297
		'sharepress/sharepress.php',                             // SharePress
298
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
299
		'social-discussions/social-discussions.php',             // Social Discussions
300
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
301
		'socialize/socialize.php',                               // Socialize
302
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
303
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
304
		// Tweet, Like, Google +1 and Share
305
		'wordbooker/wordbooker.php',                             // Wordbooker
306
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
307
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
308
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
309
		// WP Facebook Like Send & Open Graph Meta
310
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
311
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
312
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
313
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
314
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
315
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
316
		'slim-seo/slim-seo.php',                                 // Slim SEO
317
	);
318
319
	/**
320
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
321
	 */
322
	private $twitter_cards_conflicting_plugins = array(
323
		// 'twitter/twitter.php',                       // The official one handles this on its own.
324
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
325
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
326
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
327
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
328
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
329
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
330
		'twitter-cards/twitter-cards.php',           // Twitter Cards
331
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
332
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
333
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
334
		'seo-by-rank-math/rank-math.php',            // Rank Math.
335
		'slim-seo/slim-seo.php',                     // Slim SEO
336
	);
337
338
	/**
339
	 * Message to display in admin_notice
340
	 *
341
	 * @var string
342
	 */
343
	public $message = '';
344
345
	/**
346
	 * Error to display in admin_notice
347
	 *
348
	 * @var string
349
	 */
350
	public $error = '';
351
352
	/**
353
	 * Modules that need more privacy description.
354
	 *
355
	 * @var string
356
	 */
357
	public $privacy_checks = '';
358
359
	/**
360
	 * Stats to record once the page loads
361
	 *
362
	 * @var array
363
	 */
364
	public $stats = array();
365
366
	/**
367
	 * Jetpack_Sync object
368
	 */
369
	public $sync;
370
371
	/**
372
	 * Verified data for JSON authorization request
373
	 */
374
	public $json_api_authorization_request = array();
375
376
	/**
377
	 * @var Automattic\Jetpack\Connection\Manager
378
	 */
379
	protected $connection_manager;
380
381
	/**
382
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
383
	 */
384
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
385
386
	/**
387
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
388
	 *
389
	 * @var Automattic\Jetpack\A8c_Mc_Stats
390
	 */
391
	public $a8c_mc_stats_instance;
392
393
	/**
394
	 * Constant for login redirect key.
395
	 *
396
	 * @var string
397
	 * @since 8.4.0
398
	 */
399
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
400
401
	/**
402
	 * Holds the singleton instance of this class
403
	 *
404
	 * @since 2.3.3
405
	 * @var Jetpack
406
	 */
407
	static $instance = false;
408
409
	/**
410
	 * Singleton
411
	 *
412
	 * @static
413
	 */
414
	public static function init() {
415
		if ( ! self::$instance ) {
416
			self::$instance = new Jetpack();
417
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
418
		}
419
420
		return self::$instance;
421
	}
422
423
	/**
424
	 * Must never be called statically
425
	 */
426
	function plugin_upgrade() {
427
		if ( self::is_active() ) {
428
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
429
			if ( JETPACK__VERSION != $version ) {
430
				// Prevent multiple upgrades at once - only a single process should trigger
431
				// an upgrade to avoid stampedes
432
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
433
					return;
434
				}
435
436
				// Set a short lock to prevent multiple instances of the upgrade
437
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
438
439
				// check which active modules actually exist and remove others from active_modules list
440
				$unfiltered_modules = self::get_active_modules();
441
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
442
				if ( array_diff( $unfiltered_modules, $modules ) ) {
443
					self::update_active_modules( $modules );
444
				}
445
446
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
447
448
				// Upgrade to 4.3.0
449
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
450
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
451
				}
452
453
				// Make sure Markdown for posts gets turned back on
454
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
455
					update_option( 'wpcom_publish_posts_with_markdown', true );
456
				}
457
458
				/*
459
				 * Minileven deprecation. 8.3.0.
460
				 * Only delete options if not using
461
				 * the replacement standalone Minileven plugin.
462
				 */
463
				if (
464
					! self::is_plugin_active( 'minileven-master/minileven.php' )
465
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
466
				) {
467
					if ( get_option( 'wp_mobile_custom_css' ) ) {
468
						delete_option( 'wp_mobile_custom_css' );
469
					}
470
					if ( get_option( 'wp_mobile_excerpt' ) ) {
471
						delete_option( 'wp_mobile_excerpt' );
472
					}
473
					if ( get_option( 'wp_mobile_featured_images' ) ) {
474
						delete_option( 'wp_mobile_featured_images' );
475
					}
476
					if ( get_option( 'wp_mobile_app_promos' ) ) {
477
						delete_option( 'wp_mobile_app_promos' );
478
					}
479
				}
480
481
				// Upgrade to 8.4.0.
482
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
483
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
484
				}
485
486
				if ( did_action( 'wp_loaded' ) ) {
487
					self::upgrade_on_load();
488
				} else {
489
					add_action(
490
						'wp_loaded',
491
						array( __CLASS__, 'upgrade_on_load' )
492
					);
493
				}
494
			}
495
		}
496
	}
497
498
	/**
499
	 * Runs upgrade routines that need to have modules loaded.
500
	 */
501
	static function upgrade_on_load() {
502
503
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
504
		// This can happen in case Jetpack has been just upgraded and is
505
		// being initialized late during the page load. In this case we wait
506
		// until the next proper admin page load with Jetpack active.
507
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
508
			delete_transient( self::$plugin_upgrade_lock_key );
509
510
			return;
511
		}
512
513
		self::maybe_set_version_option();
514
515
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
516
			Jetpack_Widget_Conditions::migrate_post_type_rules();
517
		}
518
519
		if (
520
			class_exists( 'Jetpack_Sitemap_Manager' )
521
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
522
		) {
523
			do_action( 'jetpack_sitemaps_purge_data' );
524
		}
525
526
		// Delete old stats cache
527
		delete_option( 'jetpack_restapi_stats_cache' );
528
529
		delete_transient( self::$plugin_upgrade_lock_key );
530
	}
531
532
	/**
533
	 * Saves all the currently active modules to options.
534
	 * Also fires Action hooks for each newly activated and deactivated module.
535
	 *
536
	 * @param $modules Array Array of active modules to be saved in options.
537
	 *
538
	 * @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...
539
	 */
540
	static function update_active_modules( $modules ) {
541
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
542
		$active_modules       = self::get_active_modules();
543
		$new_active_modules   = array_diff( $modules, $current_modules );
544
		$new_inactive_modules = array_diff( $active_modules, $modules );
545
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
546
		$reindexed_modules    = array_values( $new_current_modules );
547
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
548
549
		foreach ( $new_active_modules as $module ) {
550
			/**
551
			 * Fires when a specific module is activated.
552
			 *
553
			 * @since 1.9.0
554
			 *
555
			 * @param string $module Module slug.
556
			 * @param boolean $success whether the module was activated. @since 4.2
557
			 */
558
			do_action( 'jetpack_activate_module', $module, $success );
559
			/**
560
			 * Fires when a module is activated.
561
			 * The dynamic part of the filter, $module, is the module slug.
562
			 *
563
			 * @since 1.9.0
564
			 *
565
			 * @param string $module Module slug.
566
			 */
567
			do_action( "jetpack_activate_module_$module", $module );
568
		}
569
570
		foreach ( $new_inactive_modules as $module ) {
571
			/**
572
			 * Fired after a module has been deactivated.
573
			 *
574
			 * @since 4.2.0
575
			 *
576
			 * @param string $module Module slug.
577
			 * @param boolean $success whether the module was deactivated.
578
			 */
579
			do_action( 'jetpack_deactivate_module', $module, $success );
580
			/**
581
			 * Fires when a module is deactivated.
582
			 * The dynamic part of the filter, $module, is the module slug.
583
			 *
584
			 * @since 1.9.0
585
			 *
586
			 * @param string $module Module slug.
587
			 */
588
			do_action( "jetpack_deactivate_module_$module", $module );
589
		}
590
591
		return $success;
592
	}
593
594
	static function delete_active_modules() {
595
		self::update_active_modules( array() );
596
	}
597
598
	/**
599
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
600
	 * available.
601
	 */
602
	public function add_configure_hook() {
603
		global $wp_filter;
604
605
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
606
		if ( false !== $current_priority ) {
607
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
608
		}
609
610
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
611
		sort( $taken_priorities );
612
613
		$first_priority = array_shift( $taken_priorities );
614
615
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
616
			$new_priority = - PHP_INT_MAX;
617
		} else {
618
			$new_priority = $first_priority - 1;
619
		}
620
621
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
622
	}
623
624
	/**
625
	 * Constructor.  Initializes WordPress hooks
626
	 */
627
	private function __construct() {
628
		/*
629
		 * Check for and alert any deprecated hooks
630
		 */
631
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
632
633
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
634
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
635
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
636
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
637
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
638
639
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
640
641
		add_filter(
642
			'jetpack_signature_check_token',
643
			array( __CLASS__, 'verify_onboarding_token' ),
644
			10,
645
			3
646
		);
647
648
		/**
649
		 * Prepare Gutenberg Editor functionality
650
		 */
651
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
652
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
653
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
654
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
655
656
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
657
658
		// Unlink user before deleting the user from WP.com.
659
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
660
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
661
662
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
663
664
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
665
		add_action( 'login_init', array( $this, 'login_init' ) );
666
667
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
668
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
669
670
		add_action( 'admin_init', array( $this, 'admin_init' ) );
671
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
672
673
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
674
675
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
676
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
677
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
678
679
		// returns HTTPS support status
680
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
681
682
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
683
684
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
685
686
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
687
688
		/**
689
		 * These actions run checks to load additional files.
690
		 * They check for external files or plugins, so they need to run as late as possible.
691
		 */
692
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
693
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
694
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
695
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
696
697
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
698
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
699
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
700
701
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
702
703
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
704
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
705
706
		// A filter to control all just in time messages
707
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
708
709
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
710
711
		/*
712
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
713
		 * We should make sure to only do this for front end links.
714
		 */
715
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
716
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
717
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
718
719
			/*
720
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
721
			 * so they point moderation links on emails to Calypso.
722
			 */
723
			jetpack_require_lib( 'functions.wp-notify' );
724
		}
725
726
		add_action(
727
			'plugins_loaded',
728
			function() {
729
				if ( User_Agent_Info::is_mobile_app() ) {
730
					add_filter( 'get_edit_post_link', '__return_empty_string' );
731
				}
732
			}
733
		);
734
735
		// Update the Jetpack plan from API on heartbeats.
736
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
737
738
		/**
739
		 * This is the hack to concatenate all css files into one.
740
		 * For description and reasoning see the implode_frontend_css method.
741
		 *
742
		 * Super late priority so we catch all the registered styles.
743
		 */
744
		if ( ! is_admin() ) {
745
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
746
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
747
		}
748
749
		/**
750
		 * These are sync actions that we need to keep track of for jitms
751
		 */
752
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
753
754
		// Actually push the stats on shutdown.
755
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
756
			add_action( 'shutdown', array( $this, 'push_stats' ) );
757
		}
758
759
		// Actions for Manager::authorize().
760
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
761
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
762
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
763
764
		// Filters for the Manager::get_token() urls and request body.
765
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
766
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
767
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
768
	}
769
770
	/**
771
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
772
	 * Config object.
773
	 */
774
	public function configure() {
775
		$config = new Config();
776
777
		foreach (
778
			array(
779
				'sync',
780
				'tracking',
781
				'tos',
782
			)
783
			as $feature
784
		) {
785
			$config->ensure( $feature );
786
		}
787
788
		$config->ensure(
789
			'connection',
790
			array(
791
				'slug' => 'jetpack',
792
				'name' => 'Jetpack',
793
			)
794
		);
795
796
		if ( is_admin() ) {
797
			$config->ensure( 'jitm' );
798
		}
799
800
		if ( ! $this->connection_manager ) {
801
			$this->connection_manager = new Connection_Manager( 'jetpack' );
802
		}
803
804
		/*
805
		 * Load things that should only be in Network Admin.
806
		 *
807
		 * For now blow away everything else until a more full
808
		 * understanding of what is needed at the network level is
809
		 * available
810
		 */
811
		if ( is_multisite() ) {
812
			$network = Jetpack_Network::init();
813
			$network->set_connection( $this->connection_manager );
814
		}
815
816
		if ( $this->connection_manager->is_active() ) {
817
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
818
819
			Jetpack_Heartbeat::init();
820
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
821
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
822
				Jetpack_Search_Performance_Logger::init();
823
			}
824
		}
825
826
		// Initialize remote file upload request handlers.
827
		$this->add_remote_request_handlers();
828
829
		/*
830
		 * Enable enhanced handling of previewing sites in Calypso
831
		 */
832
		if ( self::is_active() ) {
833
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
834
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
835
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
836
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
837
		}
838
	}
839
840
	/**
841
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
842
	 * initialization code.
843
	 *
844
	 * @action plugins_loaded
845
	 */
846
	public function late_initialization() {
847
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
848
849
		Partner::init();
850
851
		/**
852
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
853
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
854
		 *
855
		 * @since 8.1.0
856
		 *
857
		 * @param Jetpack $jetpack the main plugin class object.
858
		 */
859
		do_action( 'jetpack_loaded', $this );
860
861
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
862
	}
863
864
	/**
865
	 * Sets up the XMLRPC request handlers.
866
	 *
867
	 * @deprecated since 7.7.0
868
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
869
	 *
870
	 * @param array                 $request_params Incoming request parameters.
871
	 * @param Boolean               $is_active      Whether the connection is currently active.
872
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
873
	 * @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...
874
	 */
875 View Code Duplication
	public function setup_xmlrpc_handlers(
876
		$request_params,
877
		$is_active,
878
		$is_signed,
879
		Jetpack_XMLRPC_Server $xmlrpc_server = null
880
	) {
881
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
882
883
		if ( ! $this->connection_manager ) {
884
			$this->connection_manager = new Connection_Manager();
885
		}
886
887
		return $this->connection_manager->setup_xmlrpc_handlers(
888
			$request_params,
889
			$is_active,
890
			$is_signed,
891
			$xmlrpc_server
892
		);
893
	}
894
895
	/**
896
	 * Initialize REST API registration connector.
897
	 *
898
	 * @deprecated since 7.7.0
899
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
900
	 */
901 View Code Duplication
	public function initialize_rest_api_registration_connector() {
902
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
903
904
		if ( ! $this->connection_manager ) {
905
			$this->connection_manager = new Connection_Manager();
906
		}
907
908
		$this->connection_manager->initialize_rest_api_registration_connector();
909
	}
910
911
	/**
912
	 * This is ported over from the manage module, which has been deprecated and baked in here.
913
	 *
914
	 * @param $domains
915
	 */
916
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
917
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
918
	}
919
920
	/**
921
	 * Return $domains, with 'wordpress.com' appended.
922
	 * This is ported over from the manage module, which has been deprecated and baked in here.
923
	 *
924
	 * @param $domains
925
	 * @return array
926
	 */
927
	function allow_wpcom_domain( $domains ) {
928
		if ( empty( $domains ) ) {
929
			$domains = array();
930
		}
931
		$domains[] = 'wordpress.com';
932
		return array_unique( $domains );
933
	}
934
935
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
936
		$post = get_post( $post_id );
937
938
		if ( empty( $post ) ) {
939
			return $default_url;
940
		}
941
942
		$post_type = $post->post_type;
943
944
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
945
		// https://en.support.wordpress.com/custom-post-types/
946
		$allowed_post_types = array(
947
			'post',
948
			'page',
949
			'jetpack-portfolio',
950
			'jetpack-testimonial',
951
		);
952
953
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
954
			return $default_url;
955
		}
956
957
		return Redirect::get_url(
958
			'calypso-edit-' . $post_type,
959
			array(
960
				'path' => $post_id,
961
			)
962
		);
963
	}
964
965
	function point_edit_comment_links_to_calypso( $url ) {
966
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
967
		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...
968
969
		return Redirect::get_url(
970
			'calypso-edit-comment',
971
			array(
972
				'path' => $query_args['amp;c'],
973
			)
974
		);
975
976
	}
977
978
	function jetpack_track_last_sync_callback( $params ) {
979
		/**
980
		 * Filter to turn off jitm caching
981
		 *
982
		 * @since 5.4.0
983
		 *
984
		 * @param bool false Whether to cache just in time messages
985
		 */
986
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
987
			return $params;
988
		}
989
990
		if ( is_array( $params ) && isset( $params[0] ) ) {
991
			$option = $params[0];
992
			if ( 'active_plugins' === $option ) {
993
				// use the cache if we can, but not terribly important if it gets evicted
994
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
995
			}
996
		}
997
998
		return $params;
999
	}
1000
1001
	function jetpack_connection_banner_callback() {
1002
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1003
1004
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1005
		if (
1006
			isset( $_REQUEST['dismissBanner'] ) &&
1007
			! Jetpack_Connection_Banner::force_display()
1008
		) {
1009
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1010
			wp_send_json_success();
1011
		}
1012
1013
		wp_die();
1014
	}
1015
1016
	/**
1017
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1018
	 * Only used in our alternate XML-RPC endpoint, where we want to
1019
	 * ensure that Core and other plugins' methods are not exposed.
1020
	 *
1021
	 * @deprecated since 7.7.0
1022
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1023
	 *
1024
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1025
	 * @return array Filtered $methods
1026
	 */
1027 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1028
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1029
1030
		if ( ! $this->connection_manager ) {
1031
			$this->connection_manager = new Connection_Manager();
1032
		}
1033
1034
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1035
	}
1036
1037
	/**
1038
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1039
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1040
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1041
	 * which is accessible via a different URI. Most of the below is copied directly
1042
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1043
	 *
1044
	 * @deprecated since 7.7.0
1045
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1046
	 */
1047 View Code Duplication
	public function alternate_xmlrpc() {
1048
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1049
1050
		if ( ! $this->connection_manager ) {
1051
			$this->connection_manager = new Connection_Manager();
1052
		}
1053
1054
		$this->connection_manager->alternate_xmlrpc();
1055
	}
1056
1057
	/**
1058
	 * The callback for the JITM ajax requests.
1059
	 *
1060
	 * @deprecated since 7.9.0
1061
	 */
1062
	function jetpack_jitm_ajax_callback() {
1063
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1064
	}
1065
1066
	/**
1067
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1068
	 */
1069
	function push_stats() {
1070
		if ( ! empty( $this->stats ) ) {
1071
			$this->do_stats( 'server_side' );
1072
		}
1073
	}
1074
1075
	/**
1076
	 * Sets the Jetpack custom capabilities.
1077
	 *
1078
	 * @param string[] $caps    Array of the user's capabilities.
1079
	 * @param string   $cap     Capability name.
1080
	 * @param int      $user_id The user ID.
1081
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1082
	 */
1083
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1084
		$is_offline_mode = ( new Status() )->is_offline_mode();
1085
		switch ( $cap ) {
1086
			case 'jetpack_manage_modules':
1087
			case 'jetpack_activate_modules':
1088
			case 'jetpack_deactivate_modules':
1089
				$caps = array( 'manage_options' );
1090
				break;
1091
			case 'jetpack_configure_modules':
1092
				$caps = array( 'manage_options' );
1093
				break;
1094
			case 'jetpack_manage_autoupdates':
1095
				$caps = array(
1096
					'manage_options',
1097
					'update_plugins',
1098
				);
1099
				break;
1100
			case 'jetpack_network_admin_page':
1101
			case 'jetpack_network_settings_page':
1102
				$caps = array( 'manage_network_plugins' );
1103
				break;
1104
			case 'jetpack_network_sites_page':
1105
				$caps = array( 'manage_sites' );
1106
				break;
1107
			case 'jetpack_admin_page':
1108
				if ( $is_offline_mode ) {
1109
					$caps = array( 'manage_options' );
1110
					break;
1111
				} else {
1112
					$caps = array( 'read' );
1113
				}
1114
				break;
1115
		}
1116
		return $caps;
1117
	}
1118
1119
	/**
1120
	 * Require a Jetpack authentication.
1121
	 *
1122
	 * @deprecated since 7.7.0
1123
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1124
	 */
1125 View Code Duplication
	public function require_jetpack_authentication() {
1126
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1127
1128
		if ( ! $this->connection_manager ) {
1129
			$this->connection_manager = new Connection_Manager();
1130
		}
1131
1132
		$this->connection_manager->require_jetpack_authentication();
1133
	}
1134
1135
	/**
1136
	 * Register assets for use in various modules and the Jetpack admin page.
1137
	 *
1138
	 * @uses wp_script_is, wp_register_script, plugins_url
1139
	 * @action wp_loaded
1140
	 * @return null
1141
	 */
1142
	public function register_assets() {
1143 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1144
			wp_register_script(
1145
				'jetpack-gallery-settings',
1146
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1147
				array( 'media-views' ),
1148
				'20121225'
1149
			);
1150
		}
1151
1152
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1153
			wp_register_script(
1154
				'jetpack-twitter-timeline',
1155
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1156
				array( 'jquery' ),
1157
				'4.0.0',
1158
				true
1159
			);
1160
		}
1161
1162
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1163
			wp_register_script(
1164
				'jetpack-facebook-embed',
1165
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1166
				array(),
1167
				null,
1168
				true
1169
			);
1170
1171
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1172
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1173
			if ( ! is_numeric( $fb_app_id ) ) {
1174
				$fb_app_id = '';
1175
			}
1176
			wp_localize_script(
1177
				'jetpack-facebook-embed',
1178
				'jpfbembed',
1179
				array(
1180
					'appid'  => $fb_app_id,
1181
					'locale' => $this->get_locale(),
1182
				)
1183
			);
1184
		}
1185
1186
		/**
1187
		 * As jetpack_register_genericons is by default fired off a hook,
1188
		 * the hook may have already fired by this point.
1189
		 * So, let's just trigger it manually.
1190
		 */
1191
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1192
		jetpack_register_genericons();
1193
1194
		/**
1195
		 * Register the social logos
1196
		 */
1197
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1198
		jetpack_register_social_logos();
1199
1200 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1201
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1202
		}
1203
	}
1204
1205
	/**
1206
	 * Guess locale from language code.
1207
	 *
1208
	 * @param string $lang Language code.
1209
	 * @return string|bool
1210
	 */
1211 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1212
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1213
			return 'en_US';
1214
		}
1215
1216
		if ( ! class_exists( 'GP_Locales' ) ) {
1217
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1218
				return false;
1219
			}
1220
1221
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1222
		}
1223
1224
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1225
			// WP.com: get_locale() returns 'it'
1226
			$locale = GP_Locales::by_slug( $lang );
1227
		} else {
1228
			// Jetpack: get_locale() returns 'it_IT';
1229
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1230
		}
1231
1232
		if ( ! $locale ) {
1233
			return false;
1234
		}
1235
1236
		if ( empty( $locale->facebook_locale ) ) {
1237
			if ( empty( $locale->wp_locale ) ) {
1238
				return false;
1239
			} else {
1240
				// Facebook SDK is smart enough to fall back to en_US if a
1241
				// locale isn't supported. Since supported Facebook locales
1242
				// can fall out of sync, we'll attempt to use the known
1243
				// wp_locale value and rely on said fallback.
1244
				return $locale->wp_locale;
1245
			}
1246
		}
1247
1248
		return $locale->facebook_locale;
1249
	}
1250
1251
	/**
1252
	 * Get the locale.
1253
	 *
1254
	 * @return string|bool
1255
	 */
1256
	function get_locale() {
1257
		$locale = $this->guess_locale_from_lang( get_locale() );
1258
1259
		if ( ! $locale ) {
1260
			$locale = 'en_US';
1261
		}
1262
1263
		return $locale;
1264
	}
1265
1266
	/**
1267
	 * Return the network_site_url so that .com knows what network this site is a part of.
1268
	 *
1269
	 * @param  bool $option
1270
	 * @return string
1271
	 */
1272
	public function jetpack_main_network_site_option( $option ) {
1273
		return network_site_url();
1274
	}
1275
	/**
1276
	 * Network Name.
1277
	 */
1278
	static function network_name( $option = null ) {
1279
		global $current_site;
1280
		return $current_site->site_name;
1281
	}
1282
	/**
1283
	 * Does the network allow new user and site registrations.
1284
	 *
1285
	 * @return string
1286
	 */
1287
	static function network_allow_new_registrations( $option = null ) {
1288
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1289
	}
1290
	/**
1291
	 * Does the network allow admins to add new users.
1292
	 *
1293
	 * @return boolian
1294
	 */
1295
	static function network_add_new_users( $option = null ) {
1296
		return (bool) get_site_option( 'add_new_users' );
1297
	}
1298
	/**
1299
	 * File upload psace left per site in MB.
1300
	 *  -1 means NO LIMIT.
1301
	 *
1302
	 * @return number
1303
	 */
1304
	static function network_site_upload_space( $option = null ) {
1305
		// value in MB
1306
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1307
	}
1308
1309
	/**
1310
	 * Network allowed file types.
1311
	 *
1312
	 * @return string
1313
	 */
1314
	static function network_upload_file_types( $option = null ) {
1315
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1316
	}
1317
1318
	/**
1319
	 * Maximum file upload size set by the network.
1320
	 *
1321
	 * @return number
1322
	 */
1323
	static function network_max_upload_file_size( $option = null ) {
1324
		// value in KB
1325
		return get_site_option( 'fileupload_maxk', 300 );
1326
	}
1327
1328
	/**
1329
	 * Lets us know if a site allows admins to manage the network.
1330
	 *
1331
	 * @return array
1332
	 */
1333
	static function network_enable_administration_menus( $option = null ) {
1334
		return get_site_option( 'menu_items' );
1335
	}
1336
1337
	/**
1338
	 * If a user has been promoted to or demoted from admin, we need to clear the
1339
	 * jetpack_other_linked_admins transient.
1340
	 *
1341
	 * @since 4.3.2
1342
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1343
	 *
1344
	 * @param int    $user_id   The user ID whose role changed.
1345
	 * @param string $role      The new role.
1346
	 * @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...
1347
	 */
1348
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1349
		if ( 'administrator' == $role
1350
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1351
			|| is_null( $old_roles )
1352
		) {
1353
			delete_transient( 'jetpack_other_linked_admins' );
1354
		}
1355
	}
1356
1357
	/**
1358
	 * Checks to see if there are any other users available to become primary
1359
	 * Users must both:
1360
	 * - Be linked to wpcom
1361
	 * - Be an admin
1362
	 *
1363
	 * @return mixed False if no other users are linked, Int if there are.
1364
	 */
1365
	static function get_other_linked_admins() {
1366
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1367
1368
		if ( false === $other_linked_users ) {
1369
			$admins = get_users( array( 'role' => 'administrator' ) );
1370
			if ( count( $admins ) > 1 ) {
1371
				$available = array();
1372
				foreach ( $admins as $admin ) {
1373
					if ( self::is_user_connected( $admin->ID ) ) {
1374
						$available[] = $admin->ID;
1375
					}
1376
				}
1377
1378
				$count_connected_admins = count( $available );
1379
				if ( count( $available ) > 1 ) {
1380
					$other_linked_users = $count_connected_admins;
1381
				} else {
1382
					$other_linked_users = 0;
1383
				}
1384
			} else {
1385
				$other_linked_users = 0;
1386
			}
1387
1388
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1389
		}
1390
1391
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1392
	}
1393
1394
	/**
1395
	 * Return whether we are dealing with a multi network setup or not.
1396
	 * The reason we are type casting this is because we want to avoid the situation where
1397
	 * the result is false since when is_main_network_option return false it cases
1398
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1399
	 * database which could be set to anything as opposed to what this function returns.
1400
	 *
1401
	 * @param  bool $option
1402
	 *
1403
	 * @return boolean
1404
	 */
1405
	public function is_main_network_option( $option ) {
1406
		// return '1' or ''
1407
		return (string) (bool) self::is_multi_network();
1408
	}
1409
1410
	/**
1411
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1412
	 *
1413
	 * @param  string $option
1414
	 * @return boolean
1415
	 */
1416
	public function is_multisite( $option ) {
1417
		return (string) (bool) is_multisite();
1418
	}
1419
1420
	/**
1421
	 * Implemented since there is no core is multi network function
1422
	 * Right now there is no way to tell if we which network is the dominant network on the system
1423
	 *
1424
	 * @since  3.3
1425
	 * @return boolean
1426
	 */
1427 View Code Duplication
	public static function is_multi_network() {
1428
		global  $wpdb;
1429
1430
		// if we don't have a multi site setup no need to do any more
1431
		if ( ! is_multisite() ) {
1432
			return false;
1433
		}
1434
1435
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1436
		if ( $num_sites > 1 ) {
1437
			return true;
1438
		} else {
1439
			return false;
1440
		}
1441
	}
1442
1443
	/**
1444
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1445
	 *
1446
	 * @return null
1447
	 */
1448
	function update_jetpack_main_network_site_option() {
1449
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1450
	}
1451
	/**
1452
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1453
	 */
1454
	function update_jetpack_network_settings() {
1455
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1456
		// Only sync this info for the main network site.
1457
	}
1458
1459
	/**
1460
	 * Get back if the current site is single user site.
1461
	 *
1462
	 * @return bool
1463
	 */
1464 View Code Duplication
	public static function is_single_user_site() {
1465
		global $wpdb;
1466
1467
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1468
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1469
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1470
		}
1471
		return 1 === (int) $some_users;
1472
	}
1473
1474
	/**
1475
	 * Returns true if the site has file write access false otherwise.
1476
	 *
1477
	 * @return string ( '1' | '0' )
1478
	 **/
1479
	public static function file_system_write_access() {
1480
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1481
			require_once ABSPATH . 'wp-admin/includes/file.php';
1482
		}
1483
1484
		require_once ABSPATH . 'wp-admin/includes/template.php';
1485
1486
		$filesystem_method = get_filesystem_method();
1487
		if ( $filesystem_method === 'direct' ) {
1488
			return 1;
1489
		}
1490
1491
		ob_start();
1492
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1493
		ob_end_clean();
1494
		if ( $filesystem_credentials_are_stored ) {
1495
			return 1;
1496
		}
1497
		return 0;
1498
	}
1499
1500
	/**
1501
	 * Finds out if a site is using a version control system.
1502
	 *
1503
	 * @return string ( '1' | '0' )
1504
	 **/
1505
	public static function is_version_controlled() {
1506
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1507
		return (string) (int) Functions::is_version_controlled();
1508
	}
1509
1510
	/**
1511
	 * Determines whether the current theme supports featured images or not.
1512
	 *
1513
	 * @return string ( '1' | '0' )
1514
	 */
1515
	public static function featured_images_enabled() {
1516
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1517
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1518
	}
1519
1520
	/**
1521
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1522
	 *
1523
	 * @deprecated 4.7 use get_avatar_url instead.
1524
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1525
	 * @param int               $size Size of the avatar image
1526
	 * @param string            $default URL to a default image to use if no avatar is available
1527
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1528
	 *
1529
	 * @return array
1530
	 */
1531
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1532
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1533
		return get_avatar_url(
1534
			$id_or_email,
1535
			array(
1536
				'size'          => $size,
1537
				'default'       => $default,
1538
				'force_default' => $force_display,
1539
			)
1540
		);
1541
	}
1542
1543
	/**
1544
	 * jetpack_updates is saved in the following schema:
1545
	 *
1546
	 * array (
1547
	 *      'plugins'                       => (int) Number of plugin updates available.
1548
	 *      'themes'                        => (int) Number of theme updates available.
1549
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1550
	 *      'translations'                  => (int) Number of translation updates available.
1551
	 *      'total'                         => (int) Total of all available updates.
1552
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1553
	 * )
1554
	 *
1555
	 * @return array
1556
	 */
1557
	public static function get_updates() {
1558
		$update_data = wp_get_update_data();
1559
1560
		// Stores the individual update counts as well as the total count.
1561
		if ( isset( $update_data['counts'] ) ) {
1562
			$updates = $update_data['counts'];
1563
		}
1564
1565
		// If we need to update WordPress core, let's find the latest version number.
1566 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1567
			$cur = get_preferred_from_update_core();
1568
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1569
				$updates['wp_update_version'] = $cur->current;
1570
			}
1571
		}
1572
		return isset( $updates ) ? $updates : array();
1573
	}
1574
1575
	public static function get_update_details() {
1576
		$update_details = array(
1577
			'update_core'    => get_site_transient( 'update_core' ),
1578
			'update_plugins' => get_site_transient( 'update_plugins' ),
1579
			'update_themes'  => get_site_transient( 'update_themes' ),
1580
		);
1581
		return $update_details;
1582
	}
1583
1584
	public static function refresh_update_data() {
1585
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1586
1587
	}
1588
1589
	public static function refresh_theme_data() {
1590
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1591
	}
1592
1593
	/**
1594
	 * Is Jetpack active?
1595
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1596
	 *
1597
	 * @return bool
1598
	 */
1599
	public static function is_active() {
1600
		return self::connection()->is_active();
1601
	}
1602
1603
	/**
1604
	 * Make an API call to WordPress.com for plan status
1605
	 *
1606
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1607
	 *
1608
	 * @return bool True if plan is updated, false if no update
1609
	 */
1610
	public static function refresh_active_plan_from_wpcom() {
1611
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1612
		return Jetpack_Plan::refresh_from_wpcom();
1613
	}
1614
1615
	/**
1616
	 * Get the plan that this Jetpack site is currently using
1617
	 *
1618
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1619
	 * @return array Active Jetpack plan details.
1620
	 */
1621
	public static function get_active_plan() {
1622
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1623
		return Jetpack_Plan::get();
1624
	}
1625
1626
	/**
1627
	 * Determine whether the active plan supports a particular feature
1628
	 *
1629
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1630
	 * @return bool True if plan supports feature, false if not.
1631
	 */
1632
	public static function active_plan_supports( $feature ) {
1633
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1634
		return Jetpack_Plan::supports( $feature );
1635
	}
1636
1637
	/**
1638
	 * Deprecated: Is Jetpack in development (offline) mode?
1639
	 *
1640
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1641
	 * and themes still use it, and we do not want to flood them with notices.
1642
	 *
1643
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1644
	 *
1645
	 * @deprecated since 8.0.
1646
	 */
1647
	public static function is_development_mode() {
1648
		return ( new Status() )->is_offline_mode();
1649
	}
1650
1651
	/**
1652
	 * Whether the site is currently onboarding or not.
1653
	 * A site is considered as being onboarded if it currently has an onboarding token.
1654
	 *
1655
	 * @since 5.8
1656
	 *
1657
	 * @access public
1658
	 * @static
1659
	 *
1660
	 * @return bool True if the site is currently onboarding, false otherwise
1661
	 */
1662
	public static function is_onboarding() {
1663
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1664
	}
1665
1666
	/**
1667
	 * Determines reason for Jetpack offline mode.
1668
	 */
1669
	public static function development_mode_trigger_text() {
1670
		$status = new Status();
1671
1672
		if ( ! $status->is_offline_mode() ) {
1673
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1674
		}
1675
1676
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1677
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1678
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1679
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1680
		} elseif ( $status->is_local_site() ) {
1681
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1682
			/** This filter is documented in packages/status/src/class-status.php */
1683
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1684
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1685
		} else {
1686
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1687
		}
1688
1689
		return $notice;
1690
1691
	}
1692
	/**
1693
	 * Get Jetpack offline mode notice text and notice class.
1694
	 *
1695
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1696
	 */
1697
	public static function show_development_mode_notice() {
1698 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1699
			$notice = sprintf(
1700
				/* translators: %s is a URL */
1701
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1702
				Redirect::get_url( 'jetpack-support-development-mode' )
1703
			);
1704
1705
			$notice .= ' ' . self::development_mode_trigger_text();
1706
1707
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1708
		}
1709
1710
		// Throw up a notice if using a development version and as for feedback.
1711
		if ( self::is_development_version() ) {
1712
			/* translators: %s is a URL */
1713
			$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' ) );
1714
1715
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1716
		}
1717
		// Throw up a notice if using staging mode
1718 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1719
			/* translators: %s is a URL */
1720
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1721
1722
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1723
		}
1724
	}
1725
1726
	/**
1727
	 * Whether Jetpack's version maps to a public release, or a development version.
1728
	 */
1729
	public static function is_development_version() {
1730
		/**
1731
		 * Allows filtering whether this is a development version of Jetpack.
1732
		 *
1733
		 * This filter is especially useful for tests.
1734
		 *
1735
		 * @since 4.3.0
1736
		 *
1737
		 * @param bool $development_version Is this a develoment version of Jetpack?
1738
		 */
1739
		return (bool) apply_filters(
1740
			'jetpack_development_version',
1741
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1742
		);
1743
	}
1744
1745
	/**
1746
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1747
	 */
1748
	public static function is_user_connected( $user_id = false ) {
1749
		return self::connection()->is_user_connected( $user_id );
1750
	}
1751
1752
	/**
1753
	 * Get the wpcom user data of the current|specified connected user.
1754
	 */
1755 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1756
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1757
		if ( ! $user_id ) {
1758
			$user_id = get_current_user_id();
1759
		}
1760
1761
		$transient_key = "jetpack_connected_user_data_$user_id";
1762
1763
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1764
			return $cached_user_data;
1765
		}
1766
1767
		$xml = new Jetpack_IXR_Client(
1768
			array(
1769
				'user_id' => $user_id,
1770
			)
1771
		);
1772
		$xml->query( 'wpcom.getUser' );
1773
		if ( ! $xml->isError() ) {
1774
			$user_data = $xml->getResponse();
1775
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1776
			return $user_data;
1777
		}
1778
1779
		return false;
1780
	}
1781
1782
	/**
1783
	 * Get the wpcom email of the current|specified connected user.
1784
	 */
1785
	public static function get_connected_user_email( $user_id = null ) {
1786
		if ( ! $user_id ) {
1787
			$user_id = get_current_user_id();
1788
		}
1789
1790
		$xml = new Jetpack_IXR_Client(
1791
			array(
1792
				'user_id' => $user_id,
1793
			)
1794
		);
1795
		$xml->query( 'wpcom.getUserEmail' );
1796
		if ( ! $xml->isError() ) {
1797
			return $xml->getResponse();
1798
		}
1799
		return false;
1800
	}
1801
1802
	/**
1803
	 * Get the wpcom email of the master user.
1804
	 */
1805
	public static function get_master_user_email() {
1806
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1807
		if ( $master_user_id ) {
1808
			return self::get_connected_user_email( $master_user_id );
1809
		}
1810
		return '';
1811
	}
1812
1813
	/**
1814
	 * Whether the current user is the connection owner.
1815
	 *
1816
	 * @deprecated since 7.7
1817
	 *
1818
	 * @return bool Whether the current user is the connection owner.
1819
	 */
1820
	public function current_user_is_connection_owner() {
1821
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1822
		return self::connection()->is_connection_owner();
1823
	}
1824
1825
	/**
1826
	 * Gets current user IP address.
1827
	 *
1828
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1829
	 *
1830
	 * @return string                  Current user IP address.
1831
	 */
1832
	public static function current_user_ip( $check_all_headers = false ) {
1833
		if ( $check_all_headers ) {
1834
			foreach ( array(
1835
				'HTTP_CF_CONNECTING_IP',
1836
				'HTTP_CLIENT_IP',
1837
				'HTTP_X_FORWARDED_FOR',
1838
				'HTTP_X_FORWARDED',
1839
				'HTTP_X_CLUSTER_CLIENT_IP',
1840
				'HTTP_FORWARDED_FOR',
1841
				'HTTP_FORWARDED',
1842
				'HTTP_VIA',
1843
			) as $key ) {
1844
				if ( ! empty( $_SERVER[ $key ] ) ) {
1845
					return $_SERVER[ $key ];
1846
				}
1847
			}
1848
		}
1849
1850
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1851
	}
1852
1853
	/**
1854
	 * Synchronize connected user role changes
1855
	 */
1856
	function user_role_change( $user_id ) {
1857
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1858
		Users::user_role_change( $user_id );
1859
	}
1860
1861
	/**
1862
	 * Loads the currently active modules.
1863
	 */
1864
	public static function load_modules() {
1865
		$is_offline_mode = ( new Status() )->is_offline_mode();
1866
		if (
1867
			! self::is_active()
1868
			&& ! $is_offline_mode
1869
			&& ! self::is_onboarding()
1870
			&& (
1871
				! is_multisite()
1872
				|| ! get_site_option( 'jetpack_protect_active' )
1873
			)
1874
		) {
1875
			return;
1876
		}
1877
1878
		$version = Jetpack_Options::get_option( 'version' );
1879 View Code Duplication
		if ( ! $version ) {
1880
			$version = $old_version = JETPACK__VERSION . ':' . time();
1881
			/** This action is documented in class.jetpack.php */
1882
			do_action( 'updating_jetpack_version', $version, false );
1883
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1884
		}
1885
		list( $version ) = explode( ':', $version );
1886
1887
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1888
1889
		$modules_data = array();
1890
1891
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1892
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1893
			$updated_modules = array();
1894
			foreach ( $modules as $module ) {
1895
				$modules_data[ $module ] = self::get_module( $module );
1896
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1897
					continue;
1898
				}
1899
1900
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1901
					continue;
1902
				}
1903
1904
				$updated_modules[] = $module;
1905
			}
1906
1907
			$modules = array_diff( $modules, $updated_modules );
1908
		}
1909
1910
		foreach ( $modules as $index => $module ) {
1911
			// If we're in offline mode, disable modules requiring a connection.
1912
			if ( $is_offline_mode ) {
1913
				// Prime the pump if we need to
1914
				if ( empty( $modules_data[ $module ] ) ) {
1915
					$modules_data[ $module ] = self::get_module( $module );
1916
				}
1917
				// If the module requires a connection, but we're in local mode, don't include it.
1918
				if ( $modules_data[ $module ]['requires_connection'] ) {
1919
					continue;
1920
				}
1921
			}
1922
1923
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1924
				continue;
1925
			}
1926
1927
			if ( ! include_once self::get_module_path( $module ) ) {
1928
				unset( $modules[ $index ] );
1929
				self::update_active_modules( array_values( $modules ) );
1930
				continue;
1931
			}
1932
1933
			/**
1934
			 * Fires when a specific module is loaded.
1935
			 * The dynamic part of the hook, $module, is the module slug.
1936
			 *
1937
			 * @since 1.1.0
1938
			 */
1939
			do_action( 'jetpack_module_loaded_' . $module );
1940
		}
1941
1942
		/**
1943
		 * Fires when all the modules are loaded.
1944
		 *
1945
		 * @since 1.1.0
1946
		 */
1947
		do_action( 'jetpack_modules_loaded' );
1948
1949
		// 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.
1950
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1951
	}
1952
1953
	/**
1954
	 * Check if Jetpack's REST API compat file should be included
1955
	 *
1956
	 * @action plugins_loaded
1957
	 * @return null
1958
	 */
1959
	public function check_rest_api_compat() {
1960
		/**
1961
		 * Filters the list of REST API compat files to be included.
1962
		 *
1963
		 * @since 2.2.5
1964
		 *
1965
		 * @param array $args Array of REST API compat files to include.
1966
		 */
1967
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1968
1969
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1970
			require_once $_jetpack_rest_api_compat_include;
1971
		}
1972
	}
1973
1974
	/**
1975
	 * Gets all plugins currently active in values, regardless of whether they're
1976
	 * traditionally activated or network activated.
1977
	 *
1978
	 * @todo Store the result in core's object cache maybe?
1979
	 */
1980
	public static function get_active_plugins() {
1981
		$active_plugins = (array) get_option( 'active_plugins', array() );
1982
1983
		if ( is_multisite() ) {
1984
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1985
			// whereas active_plugins stores them in the values.
1986
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1987
			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...
1988
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1989
			}
1990
		}
1991
1992
		sort( $active_plugins );
1993
1994
		return array_unique( $active_plugins );
1995
	}
1996
1997
	/**
1998
	 * Gets and parses additional plugin data to send with the heartbeat data
1999
	 *
2000
	 * @since 3.8.1
2001
	 *
2002
	 * @return array Array of plugin data
2003
	 */
2004
	public static function get_parsed_plugin_data() {
2005
		if ( ! function_exists( 'get_plugins' ) ) {
2006
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2007
		}
2008
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2009
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2010
		$active_plugins = self::get_active_plugins();
2011
2012
		$plugins = array();
2013
		foreach ( $all_plugins as $path => $plugin_data ) {
2014
			$plugins[ $path ] = array(
2015
				'is_active' => in_array( $path, $active_plugins ),
2016
				'file'      => $path,
2017
				'name'      => $plugin_data['Name'],
2018
				'version'   => $plugin_data['Version'],
2019
				'author'    => $plugin_data['Author'],
2020
			);
2021
		}
2022
2023
		return $plugins;
2024
	}
2025
2026
	/**
2027
	 * Gets and parses theme data to send with the heartbeat data
2028
	 *
2029
	 * @since 3.8.1
2030
	 *
2031
	 * @return array Array of theme data
2032
	 */
2033
	public static function get_parsed_theme_data() {
2034
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2035
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2036
2037
		$themes = array();
2038
		foreach ( $all_themes as $slug => $theme_data ) {
2039
			$theme_headers = array();
2040
			foreach ( $header_keys as $header_key ) {
2041
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2042
			}
2043
2044
			$themes[ $slug ] = array(
2045
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2046
				'slug'            => $slug,
2047
				'theme_root'      => $theme_data->get_theme_root_uri(),
2048
				'parent'          => $theme_data->parent(),
2049
				'headers'         => $theme_headers,
2050
			);
2051
		}
2052
2053
		return $themes;
2054
	}
2055
2056
	/**
2057
	 * Checks whether a specific plugin is active.
2058
	 *
2059
	 * We don't want to store these in a static variable, in case
2060
	 * there are switch_to_blog() calls involved.
2061
	 */
2062
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2063
		return in_array( $plugin, self::get_active_plugins() );
2064
	}
2065
2066
	/**
2067
	 * Check if Jetpack's Open Graph tags should be used.
2068
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2069
	 *
2070
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2071
	 * @action plugins_loaded
2072
	 * @return null
2073
	 */
2074
	public function check_open_graph() {
2075
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2076
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2077
		}
2078
2079
		$active_plugins = self::get_active_plugins();
2080
2081
		if ( ! empty( $active_plugins ) ) {
2082
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2083
				if ( in_array( $plugin, $active_plugins ) ) {
2084
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2085
					break;
2086
				}
2087
			}
2088
		}
2089
2090
		/**
2091
		 * Allow the addition of Open Graph Meta Tags to all pages.
2092
		 *
2093
		 * @since 2.0.3
2094
		 *
2095
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2096
		 */
2097
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2098
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2099
		}
2100
	}
2101
2102
	/**
2103
	 * Check if Jetpack's Twitter tags should be used.
2104
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2105
	 *
2106
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2107
	 * @action plugins_loaded
2108
	 * @return null
2109
	 */
2110
	public function check_twitter_tags() {
2111
2112
		$active_plugins = self::get_active_plugins();
2113
2114
		if ( ! empty( $active_plugins ) ) {
2115
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2116
				if ( in_array( $plugin, $active_plugins ) ) {
2117
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2118
					break;
2119
				}
2120
			}
2121
		}
2122
2123
		/**
2124
		 * Allow Twitter Card Meta tags to be disabled.
2125
		 *
2126
		 * @since 2.6.0
2127
		 *
2128
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2129
		 */
2130
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2131
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2132
		}
2133
	}
2134
2135
	/**
2136
	 * Allows plugins to submit security reports.
2137
	 *
2138
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2139
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2140
	 * @param array  $args         See definitions above
2141
	 */
2142
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2143
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2144
	}
2145
2146
	/* Jetpack Options API */
2147
2148
	public static function get_option_names( $type = 'compact' ) {
2149
		return Jetpack_Options::get_option_names( $type );
2150
	}
2151
2152
	/**
2153
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2154
	 *
2155
	 * @param string $name    Option name
2156
	 * @param mixed  $default (optional)
2157
	 */
2158
	public static function get_option( $name, $default = false ) {
2159
		return Jetpack_Options::get_option( $name, $default );
2160
	}
2161
2162
	/**
2163
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2164
	 *
2165
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2166
	 * @param string $name  Option name
2167
	 * @param mixed  $value Option value
2168
	 */
2169
	public static function update_option( $name, $value ) {
2170
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2171
		return Jetpack_Options::update_option( $name, $value );
2172
	}
2173
2174
	/**
2175
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2176
	 *
2177
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2178
	 * @param array $array array( option name => option value, ... )
2179
	 */
2180
	public static function update_options( $array ) {
2181
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2182
		return Jetpack_Options::update_options( $array );
2183
	}
2184
2185
	/**
2186
	 * Deletes the given option.  May be passed multiple option names as an array.
2187
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2188
	 *
2189
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2190
	 * @param string|array $names
2191
	 */
2192
	public static function delete_option( $names ) {
2193
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2194
		return Jetpack_Options::delete_option( $names );
2195
	}
2196
2197
	/**
2198
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2199
	 *
2200
	 * Enters a user token into the user_tokens option
2201
	 *
2202
	 * @param int    $user_id The user id.
2203
	 * @param string $token The user token.
2204
	 * @param bool   $is_master_user Whether the user is the master user.
2205
	 * @return bool
2206
	 */
2207
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2208
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2209
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2210
	}
2211
2212
	/**
2213
	 * Returns an array of all PHP files in the specified absolute path.
2214
	 * Equivalent to glob( "$absolute_path/*.php" ).
2215
	 *
2216
	 * @param string $absolute_path The absolute path of the directory to search.
2217
	 * @return array Array of absolute paths to the PHP files.
2218
	 */
2219
	public static function glob_php( $absolute_path ) {
2220
		if ( function_exists( 'glob' ) ) {
2221
			return glob( "$absolute_path/*.php" );
2222
		}
2223
2224
		$absolute_path = untrailingslashit( $absolute_path );
2225
		$files         = array();
2226
		if ( ! $dir = @opendir( $absolute_path ) ) {
2227
			return $files;
2228
		}
2229
2230
		while ( false !== $file = readdir( $dir ) ) {
2231
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2232
				continue;
2233
			}
2234
2235
			$file = "$absolute_path/$file";
2236
2237
			if ( ! is_file( $file ) ) {
2238
				continue;
2239
			}
2240
2241
			$files[] = $file;
2242
		}
2243
2244
		closedir( $dir );
2245
2246
		return $files;
2247
	}
2248
2249
	public static function activate_new_modules( $redirect = false ) {
2250
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2251
			return;
2252
		}
2253
2254
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2255 View Code Duplication
		if ( ! $jetpack_old_version ) {
2256
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2257
			/** This action is documented in class.jetpack.php */
2258
			do_action( 'updating_jetpack_version', $version, false );
2259
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2260
		}
2261
2262
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2263
2264
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2265
			return;
2266
		}
2267
2268
		$active_modules     = self::get_active_modules();
2269
		$reactivate_modules = array();
2270
		foreach ( $active_modules as $active_module ) {
2271
			$module = self::get_module( $active_module );
2272
			if ( ! isset( $module['changed'] ) ) {
2273
				continue;
2274
			}
2275
2276
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2277
				continue;
2278
			}
2279
2280
			$reactivate_modules[] = $active_module;
2281
			self::deactivate_module( $active_module );
2282
		}
2283
2284
		$new_version = JETPACK__VERSION . ':' . time();
2285
		/** This action is documented in class.jetpack.php */
2286
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2287
		Jetpack_Options::update_options(
2288
			array(
2289
				'version'     => $new_version,
2290
				'old_version' => $jetpack_old_version,
2291
			)
2292
		);
2293
2294
		self::state( 'message', 'modules_activated' );
2295
2296
		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...
2297
2298
		if ( $redirect ) {
2299
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2300
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2301
				$page = $_GET['page'];
2302
			}
2303
2304
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2305
			exit;
2306
		}
2307
	}
2308
2309
	/**
2310
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2311
	 * Make sure to tuck away module "library" files in a sub-directory.
2312
	 */
2313
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2314
		static $modules = null;
2315
2316
		if ( ! isset( $modules ) ) {
2317
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2318
			// Use the cache if we're on the front-end and it's available...
2319
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2320
				$modules = $available_modules_option[ JETPACK__VERSION ];
2321
			} else {
2322
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2323
2324
				$modules = array();
2325
2326
				foreach ( $files as $file ) {
2327
					if ( ! $headers = self::get_module( $file ) ) {
2328
						continue;
2329
					}
2330
2331
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2332
				}
2333
2334
				Jetpack_Options::update_option(
2335
					'available_modules',
2336
					array(
2337
						JETPACK__VERSION => $modules,
2338
					)
2339
				);
2340
			}
2341
		}
2342
2343
		/**
2344
		 * Filters the array of modules available to be activated.
2345
		 *
2346
		 * @since 2.4.0
2347
		 *
2348
		 * @param array $modules Array of available modules.
2349
		 * @param string $min_version Minimum version number required to use modules.
2350
		 * @param string $max_version Maximum version number required to use modules.
2351
		 */
2352
		$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...
2353
2354
		if ( ! $min_version && ! $max_version ) {
2355
			return array_keys( $mods );
2356
		}
2357
2358
		$r = array();
2359
		foreach ( $mods as $slug => $introduced ) {
2360
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2361
				continue;
2362
			}
2363
2364
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2365
				continue;
2366
			}
2367
2368
			$r[] = $slug;
2369
		}
2370
2371
		return $r;
2372
	}
2373
2374
	/**
2375
	 * Default modules loaded on activation.
2376
	 */
2377
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2378
		$return = array();
2379
2380
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2381
			$module_data = self::get_module( $module );
2382
2383
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2384
				case 'yes':
2385
					$return[] = $module;
2386
					break;
2387
				case 'public':
2388
					if ( Jetpack_Options::get_option( 'public' ) ) {
2389
						$return[] = $module;
2390
					}
2391
					break;
2392
				case 'no':
2393
				default:
2394
					break;
2395
			}
2396
		}
2397
		/**
2398
		 * Filters the array of default modules.
2399
		 *
2400
		 * @since 2.5.0
2401
		 *
2402
		 * @param array $return Array of default modules.
2403
		 * @param string $min_version Minimum version number required to use modules.
2404
		 * @param string $max_version Maximum version number required to use modules.
2405
		 */
2406
		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...
2407
	}
2408
2409
	/**
2410
	 * Checks activated modules during auto-activation to determine
2411
	 * if any of those modules are being deprecated.  If so, close
2412
	 * them out, and add any replacement modules.
2413
	 *
2414
	 * Runs at priority 99 by default.
2415
	 *
2416
	 * This is run late, so that it can still activate a module if
2417
	 * the new module is a replacement for another that the user
2418
	 * currently has active, even if something at the normal priority
2419
	 * would kibosh everything.
2420
	 *
2421
	 * @since 2.6
2422
	 * @uses jetpack_get_default_modules filter
2423
	 * @param array $modules
2424
	 * @return array
2425
	 */
2426
	function handle_deprecated_modules( $modules ) {
2427
		$deprecated_modules = array(
2428
			'debug'            => null,  // Closed out and moved to the debugger library.
2429
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2430
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2431
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2432
		);
2433
2434
		// Don't activate SSO if they never completed activating WPCC.
2435
		if ( self::is_module_active( 'wpcc' ) ) {
2436
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2437
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2438
				$deprecated_modules['wpcc'] = null;
2439
			}
2440
		}
2441
2442
		foreach ( $deprecated_modules as $module => $replacement ) {
2443
			if ( self::is_module_active( $module ) ) {
2444
				self::deactivate_module( $module );
2445
				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...
2446
					$modules[] = $replacement;
2447
				}
2448
			}
2449
		}
2450
2451
		return array_unique( $modules );
2452
	}
2453
2454
	/**
2455
	 * Checks activated plugins during auto-activation to determine
2456
	 * if any of those plugins are in the list with a corresponding module
2457
	 * that is not compatible with the plugin. The module will not be allowed
2458
	 * to auto-activate.
2459
	 *
2460
	 * @since 2.6
2461
	 * @uses jetpack_get_default_modules filter
2462
	 * @param array $modules
2463
	 * @return array
2464
	 */
2465
	function filter_default_modules( $modules ) {
2466
2467
		$active_plugins = self::get_active_plugins();
2468
2469
		if ( ! empty( $active_plugins ) ) {
2470
2471
			// For each module we'd like to auto-activate...
2472
			foreach ( $modules as $key => $module ) {
2473
				// If there are potential conflicts for it...
2474
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2475
					// For each potential conflict...
2476
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2477
						// If that conflicting plugin is active...
2478
						if ( in_array( $plugin, $active_plugins ) ) {
2479
							// Remove that item from being auto-activated.
2480
							unset( $modules[ $key ] );
2481
						}
2482
					}
2483
				}
2484
			}
2485
		}
2486
2487
		return $modules;
2488
	}
2489
2490
	/**
2491
	 * Extract a module's slug from its full path.
2492
	 */
2493
	public static function get_module_slug( $file ) {
2494
		return str_replace( '.php', '', basename( $file ) );
2495
	}
2496
2497
	/**
2498
	 * Generate a module's path from its slug.
2499
	 */
2500
	public static function get_module_path( $slug ) {
2501
		/**
2502
		 * Filters the path of a modules.
2503
		 *
2504
		 * @since 7.4.0
2505
		 *
2506
		 * @param array $return The absolute path to a module's root php file
2507
		 * @param string $slug The module slug
2508
		 */
2509
		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...
2510
	}
2511
2512
	/**
2513
	 * Load module data from module file. Headers differ from WordPress
2514
	 * plugin headers to avoid them being identified as standalone
2515
	 * plugins on the WordPress plugins page.
2516
	 */
2517
	public static function get_module( $module ) {
2518
		$headers = array(
2519
			'name'                      => 'Module Name',
2520
			'description'               => 'Module Description',
2521
			'sort'                      => 'Sort Order',
2522
			'recommendation_order'      => 'Recommendation Order',
2523
			'introduced'                => 'First Introduced',
2524
			'changed'                   => 'Major Changes In',
2525
			'deactivate'                => 'Deactivate',
2526
			'free'                      => 'Free',
2527
			'requires_connection'       => 'Requires Connection',
2528
			'auto_activate'             => 'Auto Activate',
2529
			'module_tags'               => 'Module Tags',
2530
			'feature'                   => 'Feature',
2531
			'additional_search_queries' => 'Additional Search Queries',
2532
			'plan_classes'              => 'Plans',
2533
		);
2534
2535
		$file = self::get_module_path( self::get_module_slug( $module ) );
2536
2537
		$mod = self::get_file_data( $file, $headers );
2538
		if ( empty( $mod['name'] ) ) {
2539
			return false;
2540
		}
2541
2542
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2543
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2544
		$mod['deactivate']           = empty( $mod['deactivate'] );
2545
		$mod['free']                 = empty( $mod['free'] );
2546
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2547
2548
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2549
			$mod['auto_activate'] = 'No';
2550
		} else {
2551
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2552
		}
2553
2554
		if ( $mod['module_tags'] ) {
2555
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2556
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2557
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2558
		} else {
2559
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2560
		}
2561
2562 View Code Duplication
		if ( $mod['plan_classes'] ) {
2563
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2564
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2565
		} else {
2566
			$mod['plan_classes'] = array( 'free' );
2567
		}
2568
2569 View Code Duplication
		if ( $mod['feature'] ) {
2570
			$mod['feature'] = explode( ',', $mod['feature'] );
2571
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2572
		} else {
2573
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2574
		}
2575
2576
		/**
2577
		 * Filters the feature array on a module.
2578
		 *
2579
		 * This filter allows you to control where each module is filtered: Recommended,
2580
		 * and the default "Other" listing.
2581
		 *
2582
		 * @since 3.5.0
2583
		 *
2584
		 * @param array   $mod['feature'] The areas to feature this module:
2585
		 *     'Recommended' shows on the main Jetpack admin screen.
2586
		 *     'Other' should be the default if no other value is in the array.
2587
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2588
		 * @param array   $mod All the currently assembled module data.
2589
		 */
2590
		$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...
2591
2592
		/**
2593
		 * Filter the returned data about a module.
2594
		 *
2595
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2596
		 * so please be careful.
2597
		 *
2598
		 * @since 3.6.0
2599
		 *
2600
		 * @param array   $mod    The details of the requested module.
2601
		 * @param string  $module The slug of the module, e.g. sharedaddy
2602
		 * @param string  $file   The path to the module source file.
2603
		 */
2604
		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...
2605
	}
2606
2607
	/**
2608
	 * Like core's get_file_data implementation, but caches the result.
2609
	 */
2610
	public static function get_file_data( $file, $headers ) {
2611
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2612
		$file_name = basename( $file );
2613
2614
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2615
2616
		$file_data_option = get_transient( $cache_key );
2617
2618
		if ( ! is_array( $file_data_option ) ) {
2619
			delete_transient( $cache_key );
2620
			$file_data_option = false;
2621
		}
2622
2623
		if ( false === $file_data_option ) {
2624
			$file_data_option = array();
2625
		}
2626
2627
		$key           = md5( $file_name . serialize( $headers ) );
2628
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2629
2630
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2631
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2632
			return $file_data_option[ $key ];
2633
		}
2634
2635
		$data = get_file_data( $file, $headers );
2636
2637
		$file_data_option[ $key ] = $data;
2638
2639
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2640
2641
		return $data;
2642
	}
2643
2644
2645
	/**
2646
	 * Return translated module tag.
2647
	 *
2648
	 * @param string $tag Tag as it appears in each module heading.
2649
	 *
2650
	 * @return mixed
2651
	 */
2652
	public static function translate_module_tag( $tag ) {
2653
		return jetpack_get_module_i18n_tag( $tag );
2654
	}
2655
2656
	/**
2657
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2658
	 *
2659
	 * @since 3.9.2
2660
	 *
2661
	 * @param array $modules
2662
	 *
2663
	 * @return string|void
2664
	 */
2665
	public static function get_translated_modules( $modules ) {
2666
		foreach ( $modules as $index => $module ) {
2667
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2668
			if ( isset( $module['name'] ) ) {
2669
				$modules[ $index ]['name'] = $i18n_module['name'];
2670
			}
2671
			if ( isset( $module['description'] ) ) {
2672
				$modules[ $index ]['description']       = $i18n_module['description'];
2673
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2674
			}
2675
		}
2676
		return $modules;
2677
	}
2678
2679
	/**
2680
	 * Get a list of activated modules as an array of module slugs.
2681
	 */
2682
	public static function get_active_modules() {
2683
		$active = Jetpack_Options::get_option( 'active_modules' );
2684
2685
		if ( ! is_array( $active ) ) {
2686
			$active = array();
2687
		}
2688
2689
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2690
			$active[] = 'vaultpress';
2691
		} else {
2692
			$active = array_diff( $active, array( 'vaultpress' ) );
2693
		}
2694
2695
		// If protect is active on the main site of a multisite, it should be active on all sites.
2696
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2697
			$active[] = 'protect';
2698
		}
2699
2700
		/**
2701
		 * Allow filtering of the active modules.
2702
		 *
2703
		 * Gives theme and plugin developers the power to alter the modules that
2704
		 * are activated on the fly.
2705
		 *
2706
		 * @since 5.8.0
2707
		 *
2708
		 * @param array $active Array of active module slugs.
2709
		 */
2710
		$active = apply_filters( 'jetpack_active_modules', $active );
2711
2712
		return array_unique( $active );
2713
	}
2714
2715
	/**
2716
	 * Check whether or not a Jetpack module is active.
2717
	 *
2718
	 * @param string $module The slug of a Jetpack module.
2719
	 * @return bool
2720
	 *
2721
	 * @static
2722
	 */
2723
	public static function is_module_active( $module ) {
2724
		return in_array( $module, self::get_active_modules() );
2725
	}
2726
2727
	public static function is_module( $module ) {
2728
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2729
	}
2730
2731
	/**
2732
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2733
	 *
2734
	 * @param bool $catch True to start catching, False to stop.
2735
	 *
2736
	 * @static
2737
	 */
2738
	public static function catch_errors( $catch ) {
2739
		static $display_errors, $error_reporting;
2740
2741
		if ( $catch ) {
2742
			$display_errors  = @ini_set( 'display_errors', 1 );
2743
			$error_reporting = @error_reporting( E_ALL );
2744
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2745
		} else {
2746
			@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...
2747
			@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...
2748
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2749
		}
2750
	}
2751
2752
	/**
2753
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2754
	 */
2755
	public static function catch_errors_on_shutdown() {
2756
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2757
	}
2758
2759
	/**
2760
	 * Rewrite any string to make paths easier to read.
2761
	 *
2762
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2763
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2764
	 *
2765
	 * @param $string
2766
	 * @return mixed
2767
	 */
2768
	public static function alias_directories( $string ) {
2769
		// ABSPATH has a trailing slash.
2770
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2771
		// WP_CONTENT_DIR does not have a trailing slash.
2772
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2773
2774
		return $string;
2775
	}
2776
2777
	public static function activate_default_modules(
2778
		$min_version = false,
2779
		$max_version = false,
2780
		$other_modules = array(),
2781
		$redirect = null,
2782
		$send_state_messages = null
2783
	) {
2784
		$jetpack = self::init();
2785
2786
		if ( is_null( $redirect ) ) {
2787
			if (
2788
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2789
			||
2790
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2791
			||
2792
				( defined( 'WP_CLI' ) && WP_CLI )
2793
			||
2794
				( defined( 'DOING_CRON' ) && DOING_CRON )
2795
			||
2796
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2797
			) {
2798
				$redirect = false;
2799
			} elseif ( is_admin() ) {
2800
				$redirect = true;
2801
			} else {
2802
				$redirect = false;
2803
			}
2804
		}
2805
2806
		if ( is_null( $send_state_messages ) ) {
2807
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2808
		}
2809
2810
		$modules = self::get_default_modules( $min_version, $max_version );
2811
		$modules = array_merge( $other_modules, $modules );
2812
2813
		// Look for standalone plugins and disable if active.
2814
2815
		$to_deactivate = array();
2816
		foreach ( $modules as $module ) {
2817
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2818
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2819
			}
2820
		}
2821
2822
		$deactivated = array();
2823
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2824
			list( $probable_file, $probable_title ) = $deactivate_me;
2825
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2826
				$deactivated[] = $module;
2827
			}
2828
		}
2829
2830
		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...
2831
			if ( $send_state_messages ) {
2832
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2833
			}
2834
2835
			if ( $redirect ) {
2836
				$url = add_query_arg(
2837
					array(
2838
						'action'   => 'activate_default_modules',
2839
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2840
					),
2841
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2842
				);
2843
				wp_safe_redirect( $url );
2844
				exit;
2845
			}
2846
		}
2847
2848
		/**
2849
		 * Fires before default modules are activated.
2850
		 *
2851
		 * @since 1.9.0
2852
		 *
2853
		 * @param string $min_version Minimum version number required to use modules.
2854
		 * @param string $max_version Maximum version number required to use modules.
2855
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2856
		 */
2857
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2858
2859
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2860
		if ( $send_state_messages ) {
2861
			self::restate();
2862
			self::catch_errors( true );
2863
		}
2864
2865
		$active = self::get_active_modules();
2866
2867
		foreach ( $modules as $module ) {
2868
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2869
				$active[] = $module;
2870
				self::update_active_modules( $active );
2871
				continue;
2872
			}
2873
2874
			if ( $send_state_messages && in_array( $module, $active ) ) {
2875
				$module_info = self::get_module( $module );
2876 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2877
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2878
					if ( $active_state = self::state( $state ) ) {
2879
						$active_state = explode( ',', $active_state );
2880
					} else {
2881
						$active_state = array();
2882
					}
2883
					$active_state[] = $module;
2884
					self::state( $state, implode( ',', $active_state ) );
2885
				}
2886
				continue;
2887
			}
2888
2889
			$file = self::get_module_path( $module );
2890
			if ( ! file_exists( $file ) ) {
2891
				continue;
2892
			}
2893
2894
			// we'll override this later if the plugin can be included without fatal error
2895
			if ( $redirect ) {
2896
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2897
			}
2898
2899
			if ( $send_state_messages ) {
2900
				self::state( 'error', 'module_activation_failed' );
2901
				self::state( 'module', $module );
2902
			}
2903
2904
			ob_start();
2905
			require_once $file;
2906
2907
			$active[] = $module;
2908
2909 View Code Duplication
			if ( $send_state_messages ) {
2910
2911
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2912
				if ( $active_state = self::state( $state ) ) {
2913
					$active_state = explode( ',', $active_state );
2914
				} else {
2915
					$active_state = array();
2916
				}
2917
				$active_state[] = $module;
2918
				self::state( $state, implode( ',', $active_state ) );
2919
			}
2920
2921
			self::update_active_modules( $active );
2922
2923
			ob_end_clean();
2924
		}
2925
2926
		if ( $send_state_messages ) {
2927
			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...
2928
			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...
2929
		}
2930
2931
		self::catch_errors( false );
2932
		/**
2933
		 * Fires when default modules are activated.
2934
		 *
2935
		 * @since 1.9.0
2936
		 *
2937
		 * @param string $min_version Minimum version number required to use modules.
2938
		 * @param string $max_version Maximum version number required to use modules.
2939
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2940
		 */
2941
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2942
	}
2943
2944
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2945
		/**
2946
		 * Fires before a module is activated.
2947
		 *
2948
		 * @since 2.6.0
2949
		 *
2950
		 * @param string $module Module slug.
2951
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2952
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2953
		 */
2954
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2955
2956
		$jetpack = self::init();
2957
2958
		if ( ! strlen( $module ) ) {
2959
			return false;
2960
		}
2961
2962
		if ( ! self::is_module( $module ) ) {
2963
			return false;
2964
		}
2965
2966
		// If it's already active, then don't do it again
2967
		$active = self::get_active_modules();
2968
		foreach ( $active as $act ) {
2969
			if ( $act == $module ) {
2970
				return true;
2971
			}
2972
		}
2973
2974
		$module_data = self::get_module( $module );
2975
2976
		$is_offline_mode = ( new Status() )->is_offline_mode();
2977
		if ( ! self::is_active() ) {
2978
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
2979
				return false;
2980
			}
2981
2982
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
2983
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
2984
				return false;
2985
			}
2986
		}
2987
2988
		// Check and see if the old plugin is active
2989
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2990
			// Deactivate the old plugin
2991
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2992
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2993
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2994
				self::state( 'deactivated_plugins', $module );
2995
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2996
				exit;
2997
			}
2998
		}
2999
3000
		// Protect won't work with mis-configured IPs
3001
		if ( 'protect' === $module ) {
3002
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3003
			if ( ! jetpack_protect_get_ip() ) {
3004
				self::state( 'message', 'protect_misconfigured_ip' );
3005
				return false;
3006
			}
3007
		}
3008
3009
		if ( ! Jetpack_Plan::supports( $module ) ) {
3010
			return false;
3011
		}
3012
3013
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3014
		self::state( 'module', $module );
3015
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3016
3017
		self::catch_errors( true );
3018
		ob_start();
3019
		require self::get_module_path( $module );
3020
		/** This action is documented in class.jetpack.php */
3021
		do_action( 'jetpack_activate_module', $module );
3022
		$active[] = $module;
3023
		self::update_active_modules( $active );
3024
3025
		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...
3026
		ob_end_clean();
3027
		self::catch_errors( false );
3028
3029
		if ( $redirect ) {
3030
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3031
		}
3032
		if ( $exit ) {
3033
			exit;
3034
		}
3035
		return true;
3036
	}
3037
3038
	function activate_module_actions( $module ) {
3039
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3040
	}
3041
3042
	public static function deactivate_module( $module ) {
3043
		/**
3044
		 * Fires when a module is deactivated.
3045
		 *
3046
		 * @since 1.9.0
3047
		 *
3048
		 * @param string $module Module slug.
3049
		 */
3050
		do_action( 'jetpack_pre_deactivate_module', $module );
3051
3052
		$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...
3053
3054
		$active = self::get_active_modules();
3055
		$new    = array_filter( array_diff( $active, (array) $module ) );
3056
3057
		return self::update_active_modules( $new );
3058
	}
3059
3060
	public static function enable_module_configurable( $module ) {
3061
		$module = self::get_module_slug( $module );
3062
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3063
	}
3064
3065
	/**
3066
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3067
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3068
	 *
3069
	 * @param string $module Module slug
3070
	 * @return string $url module configuration URL
3071
	 */
3072
	public static function module_configuration_url( $module ) {
3073
		$module      = self::get_module_slug( $module );
3074
		$default_url = self::admin_url() . "#/settings?term=$module";
3075
		/**
3076
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3077
		 *
3078
		 * @since 6.9.0
3079
		 *
3080
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3081
		 */
3082
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3083
3084
		return $url;
3085
	}
3086
3087
	/* Installation */
3088
	public static function bail_on_activation( $message, $deactivate = true ) {
3089
		?>
3090
<!doctype html>
3091
<html>
3092
<head>
3093
<meta charset="<?php bloginfo( 'charset' ); ?>">
3094
<style>
3095
* {
3096
	text-align: center;
3097
	margin: 0;
3098
	padding: 0;
3099
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3100
}
3101
p {
3102
	margin-top: 1em;
3103
	font-size: 18px;
3104
}
3105
</style>
3106
<body>
3107
<p><?php echo esc_html( $message ); ?></p>
3108
</body>
3109
</html>
3110
		<?php
3111
		if ( $deactivate ) {
3112
			$plugins = get_option( 'active_plugins' );
3113
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3114
			$update  = false;
3115
			foreach ( $plugins as $i => $plugin ) {
3116
				if ( $plugin === $jetpack ) {
3117
					$plugins[ $i ] = false;
3118
					$update        = true;
3119
				}
3120
			}
3121
3122
			if ( $update ) {
3123
				update_option( 'active_plugins', array_filter( $plugins ) );
3124
			}
3125
		}
3126
		exit;
3127
	}
3128
3129
	/**
3130
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3131
	 *
3132
	 * @static
3133
	 */
3134
	public static function plugin_activation( $network_wide ) {
3135
		Jetpack_Options::update_option( 'activated', 1 );
3136
3137
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3138
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3139
		}
3140
3141
		if ( $network_wide ) {
3142
			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...
3143
		}
3144
3145
		// For firing one-off events (notices) immediately after activation
3146
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3147
3148
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3149
3150
		Health::on_jetpack_activated();
3151
3152
		self::plugin_initialize();
3153
	}
3154
3155
	public static function get_activation_source( $referer_url ) {
3156
3157
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3158
			return array( 'wp-cli', null );
3159
		}
3160
3161
		$referer = wp_parse_url( $referer_url );
3162
3163
		$source_type  = 'unknown';
3164
		$source_query = null;
3165
3166
		if ( ! is_array( $referer ) ) {
3167
			return array( $source_type, $source_query );
3168
		}
3169
3170
		$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...
3171
		$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...
3172
3173
		if ( isset( $referer['query'] ) ) {
3174
			parse_str( $referer['query'], $query_parts );
3175
		} else {
3176
			$query_parts = array();
3177
		}
3178
3179
		if ( $plugins_path === $referer['path'] ) {
3180
			$source_type = 'list';
3181
		} elseif ( $plugins_install_path === $referer['path'] ) {
3182
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3183
			switch ( $tab ) {
3184
				case 'popular':
3185
					$source_type = 'popular';
3186
					break;
3187
				case 'recommended':
3188
					$source_type = 'recommended';
3189
					break;
3190
				case 'favorites':
3191
					$source_type = 'favorites';
3192
					break;
3193
				case 'search':
3194
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3195
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3196
					break;
3197
				default:
3198
					$source_type = 'featured';
3199
			}
3200
		}
3201
3202
		return array( $source_type, $source_query );
3203
	}
3204
3205
	/**
3206
	 * Runs before bumping version numbers up to a new version
3207
	 *
3208
	 * @param string $version    Version:timestamp.
3209
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3210
	 */
3211
	public static function do_version_bump( $version, $old_version ) {
3212
		if ( $old_version ) { // For existing Jetpack installations.
3213
3214
			// If a front end page is visited after the update, the 'wp' action will fire.
3215
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3216
3217
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3218
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3219
		}
3220
	}
3221
3222
	/**
3223
	 * Sets the display_update_modal state.
3224
	 */
3225
	public static function set_update_modal_display() {
3226
		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...
3227
	}
3228
3229
	/**
3230
	 * Sets the internal version number and activation state.
3231
	 *
3232
	 * @static
3233
	 */
3234
	public static function plugin_initialize() {
3235
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3236
			Jetpack_Options::update_option( 'activated', 2 );
3237
		}
3238
3239 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3240
			$version = $old_version = JETPACK__VERSION . ':' . time();
3241
			/** This action is documented in class.jetpack.php */
3242
			do_action( 'updating_jetpack_version', $version, false );
3243
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3244
		}
3245
3246
		self::load_modules();
3247
3248
		Jetpack_Options::delete_option( 'do_activate' );
3249
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3250
	}
3251
3252
	/**
3253
	 * Removes all connection options
3254
	 *
3255
	 * @static
3256
	 */
3257
	public static function plugin_deactivation() {
3258
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3259
		$tracking = new Tracking();
3260
		$tracking->record_user_event( 'deactivate_plugin', array() );
3261
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3262
			Jetpack_Network::init()->deactivate();
3263
		} else {
3264
			self::disconnect( false );
3265
			// Jetpack_Heartbeat::init()->deactivate();
3266
		}
3267
	}
3268
3269
	/**
3270
	 * Disconnects from the Jetpack servers.
3271
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3272
	 *
3273
	 * @static
3274
	 */
3275
	public static function disconnect( $update_activated_state = true ) {
3276
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3277
		$connection = self::connection();
3278
		$connection->clean_nonces( true );
3279
3280
		// If the site is in an IDC because sync is not allowed,
3281
		// let's make sure to not disconnect the production site.
3282
		if ( ! self::validate_sync_error_idc_option() ) {
3283
			$tracking = new Tracking();
3284
			$tracking->record_user_event( 'disconnect_site', array() );
3285
3286
			$connection->disconnect_site_wpcom( true );
3287
		}
3288
3289
		$connection->delete_all_connection_tokens( true );
3290
		Jetpack_IDC::clear_all_idc_options();
3291
3292
		if ( $update_activated_state ) {
3293
			Jetpack_Options::update_option( 'activated', 4 );
3294
		}
3295
3296
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3297
			// Check then record unique disconnection if site has never been disconnected previously
3298
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3299
				$jetpack_unique_connection['disconnected'] = 1;
3300
			} else {
3301
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3302
					// track unique disconnect
3303
					$jetpack = self::init();
3304
3305
					$jetpack->stat( 'connections', 'unique-disconnect' );
3306
					$jetpack->do_stats( 'server_side' );
3307
				}
3308
				// increment number of times disconnected
3309
				$jetpack_unique_connection['disconnected'] += 1;
3310
			}
3311
3312
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3313
		}
3314
3315
		// Delete all the sync related data. Since it could be taking up space.
3316
		Sender::get_instance()->uninstall();
3317
3318
		// Disable the Heartbeat cron
3319
		Jetpack_Heartbeat::init()->deactivate();
3320
	}
3321
3322
	/**
3323
	 * Unlinks the current user from the linked WordPress.com user.
3324
	 *
3325
	 * @deprecated since 7.7
3326
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3327
	 *
3328
	 * @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...
3329
	 * @return Boolean Whether the disconnection of the user was successful.
3330
	 */
3331
	public static function unlink_user( $user_id = null ) {
3332
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3333
		return Connection_Manager::disconnect_user( $user_id );
3334
	}
3335
3336
	/**
3337
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3338
	 */
3339
	public static function try_registration() {
3340
		$terms_of_service = new Terms_Of_Service();
3341
		// The user has agreed to the TOS at some point by now.
3342
		$terms_of_service->agree();
3343
3344
		// Let's get some testing in beta versions and such.
3345
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3346
			// Before attempting to connect, let's make sure that the domains are viable.
3347
			$domains_to_check = array_unique(
3348
				array(
3349
					'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...
3350
					'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...
3351
				)
3352
			);
3353
			foreach ( $domains_to_check as $domain ) {
3354
				$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...
3355
				if ( is_wp_error( $result ) ) {
3356
					return $result;
3357
				}
3358
			}
3359
		}
3360
3361
		$result = self::register();
3362
3363
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3364
		if ( ! $result || is_wp_error( $result ) ) {
3365
			return $result;
3366
		} else {
3367
			return true;
3368
		}
3369
	}
3370
3371
	/**
3372
	 * Tracking an internal event log. Try not to put too much chaff in here.
3373
	 *
3374
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3375
	 */
3376
	public static function log( $code, $data = null ) {
3377
		// only grab the latest 200 entries
3378
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3379
3380
		// Append our event to the log
3381
		$log_entry = array(
3382
			'time'    => time(),
3383
			'user_id' => get_current_user_id(),
3384
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3385
			'code'    => $code,
3386
		);
3387
		// Don't bother storing it unless we've got some.
3388
		if ( ! is_null( $data ) ) {
3389
			$log_entry['data'] = $data;
3390
		}
3391
		$log[] = $log_entry;
3392
3393
		// Try add_option first, to make sure it's not autoloaded.
3394
		// @todo: Add an add_option method to Jetpack_Options
3395
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3396
			Jetpack_Options::update_option( 'log', $log );
3397
		}
3398
3399
		/**
3400
		 * Fires when Jetpack logs an internal event.
3401
		 *
3402
		 * @since 3.0.0
3403
		 *
3404
		 * @param array $log_entry {
3405
		 *  Array of details about the log entry.
3406
		 *
3407
		 *  @param string time Time of the event.
3408
		 *  @param int user_id ID of the user who trigerred the event.
3409
		 *  @param int blog_id Jetpack Blog ID.
3410
		 *  @param string code Unique name for the event.
3411
		 *  @param string data Data about the event.
3412
		 * }
3413
		 */
3414
		do_action( 'jetpack_log_entry', $log_entry );
3415
	}
3416
3417
	/**
3418
	 * Get the internal event log.
3419
	 *
3420
	 * @param $event (string) - only return the specific log events
3421
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3422
	 *
3423
	 * @return array of log events || WP_Error for invalid params
3424
	 */
3425
	public static function get_log( $event = false, $num = false ) {
3426
		if ( $event && ! is_string( $event ) ) {
3427
			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...
3428
		}
3429
3430
		if ( $num && ! is_numeric( $num ) ) {
3431
			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...
3432
		}
3433
3434
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3435
3436
		// If nothing set - act as it did before, otherwise let's start customizing the output
3437
		if ( ! $num && ! $event ) {
3438
			return $entire_log;
3439
		} else {
3440
			$entire_log = array_reverse( $entire_log );
3441
		}
3442
3443
		$custom_log_output = array();
3444
3445
		if ( $event ) {
3446
			foreach ( $entire_log as $log_event ) {
3447
				if ( $event == $log_event['code'] ) {
3448
					$custom_log_output[] = $log_event;
3449
				}
3450
			}
3451
		} else {
3452
			$custom_log_output = $entire_log;
3453
		}
3454
3455
		if ( $num ) {
3456
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3457
		}
3458
3459
		return $custom_log_output;
3460
	}
3461
3462
	/**
3463
	 * Log modification of important settings.
3464
	 */
3465
	public static function log_settings_change( $option, $old_value, $value ) {
3466
		switch ( $option ) {
3467
			case 'jetpack_sync_non_public_post_stati':
3468
				self::log( $option, $value );
3469
				break;
3470
		}
3471
	}
3472
3473
	/**
3474
	 * Return stat data for WPCOM sync
3475
	 */
3476
	public static function get_stat_data( $encode = true, $extended = true ) {
3477
		$data = Jetpack_Heartbeat::generate_stats_array();
3478
3479
		if ( $extended ) {
3480
			$additional_data = self::get_additional_stat_data();
3481
			$data            = array_merge( $data, $additional_data );
3482
		}
3483
3484
		if ( $encode ) {
3485
			return json_encode( $data );
3486
		}
3487
3488
		return $data;
3489
	}
3490
3491
	/**
3492
	 * Get additional stat data to sync to WPCOM
3493
	 */
3494
	public static function get_additional_stat_data( $prefix = '' ) {
3495
		$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...
3496
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3497
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3498
		$return[ "{$prefix}site-count" ]    = 0;
3499
3500
		if ( function_exists( 'get_blog_count' ) ) {
3501
			$return[ "{$prefix}site-count" ] = get_blog_count();
3502
		}
3503
		return $return;
3504
	}
3505
3506
	private static function get_site_user_count() {
3507
		global $wpdb;
3508
3509
		if ( function_exists( 'wp_is_large_network' ) ) {
3510
			if ( wp_is_large_network( 'users' ) ) {
3511
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3512
			}
3513
		}
3514
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3515
			// It wasn't there, so regenerate the data and save the transient
3516
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3517
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3518
		}
3519
		return $user_count;
3520
	}
3521
3522
	/* Admin Pages */
3523
3524
	function admin_init() {
3525
		// If the plugin is not connected, display a connect message.
3526
		if (
3527
			// the plugin was auto-activated and needs its candy
3528
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3529
		||
3530
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3531
			! Jetpack_Options::get_option( 'activated' )
3532
		) {
3533
			self::plugin_initialize();
3534
		}
3535
3536
		$is_offline_mode = ( new Status() )->is_offline_mode();
3537
		if ( ! self::is_active() && ! $is_offline_mode ) {
3538
			Jetpack_Connection_Banner::init();
3539
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3540
			// Upgrade: 1.1 -> 1.1.1
3541
			// Check and see if host can verify the Jetpack servers' SSL certificate
3542
			$args       = array();
3543
			$connection = self::connection();
3544
			Client::_wp_remote_request(
3545
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3546
				$args,
3547
				true
3548
			);
3549
		}
3550
3551
		Jetpack_Wizard_Banner::init();
3552
3553
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3554
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3555
		}
3556
3557
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3558
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3559
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3560
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3561
3562
		if ( self::is_active() || $is_offline_mode ) {
3563
			// Artificially throw errors in certain specific cases during plugin activation.
3564
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3565
		}
3566
3567
		// Add custom column in wp-admin/users.php to show whether user is linked.
3568
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3569
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3570
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3571
	}
3572
3573
	function admin_body_class( $admin_body_class = '' ) {
3574
		$classes = explode( ' ', trim( $admin_body_class ) );
3575
3576
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3577
3578
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3579
		return " $admin_body_class ";
3580
	}
3581
3582
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3583
		return $admin_body_class . ' jetpack-pagestyles ';
3584
	}
3585
3586
	/**
3587
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3588
	 * This function artificially throws errors for such cases (per a specific list).
3589
	 *
3590
	 * @param string $plugin The activated plugin.
3591
	 */
3592
	function throw_error_on_activate_plugin( $plugin ) {
3593
		$active_modules = self::get_active_modules();
3594
3595
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3596
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3597
			$throw = false;
3598
3599
			// Try and make sure it really was the stats plugin
3600
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3601
				if ( 'stats.php' == basename( $plugin ) ) {
3602
					$throw = true;
3603
				}
3604
			} else {
3605
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3606
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3607
					$throw = true;
3608
				}
3609
			}
3610
3611
			if ( $throw ) {
3612
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3613
			}
3614
		}
3615
	}
3616
3617
	function intercept_plugin_error_scrape_init() {
3618
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3619
	}
3620
3621
	function intercept_plugin_error_scrape( $action, $result ) {
3622
		if ( ! $result ) {
3623
			return;
3624
		}
3625
3626
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3627
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3628
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3629
			}
3630
		}
3631
	}
3632
3633
	/**
3634
	 * Register the remote file upload request handlers, if needed.
3635
	 *
3636
	 * @access public
3637
	 */
3638
	public function add_remote_request_handlers() {
3639
		// Remote file uploads are allowed only via AJAX requests.
3640
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3641
			return;
3642
		}
3643
3644
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3645
		$remote_request_actions = array(
3646
			'jetpack_upload_file',
3647
			'jetpack_update_file',
3648
		);
3649
3650
		// phpcs:ignore WordPress.Security.NonceVerification
3651
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3652
			return;
3653
		}
3654
3655
		// Require Jetpack authentication for the remote file upload AJAX requests.
3656
		if ( ! $this->connection_manager ) {
3657
			$this->connection_manager = new Connection_Manager();
3658
		}
3659
3660
		$this->connection_manager->require_jetpack_authentication();
3661
3662
		// Register the remote file upload AJAX handlers.
3663
		foreach ( $remote_request_actions as $action ) {
3664
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3665
		}
3666
	}
3667
3668
	/**
3669
	 * Handler for Jetpack remote file uploads.
3670
	 *
3671
	 * @access public
3672
	 */
3673
	public function remote_request_handlers() {
3674
		$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...
3675
3676
		switch ( current_filter() ) {
3677
			case 'wp_ajax_nopriv_jetpack_upload_file':
3678
				$response = $this->upload_handler();
3679
				break;
3680
3681
			case 'wp_ajax_nopriv_jetpack_update_file':
3682
				$response = $this->upload_handler( true );
3683
				break;
3684
			default:
3685
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
The call to WP_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...
3686
				break;
3687
		}
3688
3689
		if ( ! $response ) {
3690
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
The call to WP_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...
3691
		}
3692
3693
		if ( is_wp_error( $response ) ) {
3694
			$status_code       = $response->get_error_data();
0 ignored issues
show
The method get_error_data() 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...
3695
			$error             = $response->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...
3696
			$error_description = $response->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...
3697
3698
			if ( ! is_int( $status_code ) ) {
3699
				$status_code = 400;
3700
			}
3701
3702
			status_header( $status_code );
3703
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3704
		}
3705
3706
		status_header( 200 );
3707
		if ( true === $response ) {
3708
			exit;
3709
		}
3710
3711
		die( json_encode( (object) $response ) );
3712
	}
3713
3714
	/**
3715
	 * Uploads a file gotten from the global $_FILES.
3716
	 * If `$update_media_item` is true and `post_id` is defined
3717
	 * the attachment file of the media item (gotten through of the post_id)
3718
	 * will be updated instead of add a new one.
3719
	 *
3720
	 * @param  boolean $update_media_item - update media attachment
3721
	 * @return array - An array describing the uploadind files process
3722
	 */
3723
	function upload_handler( $update_media_item = false ) {
3724
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3725
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
The call to WP_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...
3726
		}
3727
3728
		$user = wp_authenticate( '', '' );
3729
		if ( ! $user || is_wp_error( $user ) ) {
3730
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
The call to WP_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...
3731
		}
3732
3733
		wp_set_current_user( $user->ID );
3734
3735
		if ( ! current_user_can( 'upload_files' ) ) {
3736
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
The call to WP_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...
3737
		}
3738
3739
		if ( empty( $_FILES ) ) {
3740
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
The call to WP_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...
3741
		}
3742
3743
		foreach ( array_keys( $_FILES ) as $files_key ) {
3744
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3745
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
The call to WP_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...
3746
			}
3747
		}
3748
3749
		$media_keys = array_keys( $_FILES['media'] );
3750
3751
		$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...
3752
		if ( ! $token || is_wp_error( $token ) ) {
3753
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
The call to WP_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...
3754
		}
3755
3756
		$uploaded_files = array();
3757
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3758
		unset( $GLOBALS['post'] );
3759
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3760
			$file = array();
3761
			foreach ( $media_keys as $media_key ) {
3762
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3763
			}
3764
3765
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3766
3767
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3768
			if ( $hmac_provided !== $hmac_file ) {
3769
				$uploaded_files[ $index ] = (object) array(
3770
					'error'             => 'invalid_hmac',
3771
					'error_description' => 'The corresponding HMAC for this file does not match',
3772
				);
3773
				continue;
3774
			}
3775
3776
			$_FILES['.jetpack.upload.'] = $file;
3777
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3778
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3779
				$post_id = 0;
3780
			}
3781
3782
			if ( $update_media_item ) {
3783
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3784
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
The call to WP_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...
3785
				}
3786
3787
				$media_array = $_FILES['media'];
3788
3789
				$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...
3790
				$file_array['type']     = $media_array['type'][0];
3791
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3792
				$file_array['error']    = $media_array['error'][0];
3793
				$file_array['size']     = $media_array['size'][0];
3794
3795
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3796
3797
				if ( is_wp_error( $edited_media_item ) ) {
3798
					return $edited_media_item;
3799
				}
3800
3801
				$response = (object) array(
3802
					'id'   => (string) $post_id,
3803
					'file' => (string) $edited_media_item->post_title,
3804
					'url'  => (string) wp_get_attachment_url( $post_id ),
3805
					'type' => (string) $edited_media_item->post_mime_type,
3806
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3807
				);
3808
3809
				return (array) array( $response );
3810
			}
3811
3812
			$attachment_id = media_handle_upload(
3813
				'.jetpack.upload.',
3814
				$post_id,
3815
				array(),
3816
				array(
3817
					'action' => 'jetpack_upload_file',
3818
				)
3819
			);
3820
3821
			if ( ! $attachment_id ) {
3822
				$uploaded_files[ $index ] = (object) array(
3823
					'error'             => 'unknown',
3824
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3825
				);
3826
			} elseif ( is_wp_error( $attachment_id ) ) {
3827
				$uploaded_files[ $index ] = (object) array(
3828
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3829
					'error_description' => $attachment_id->get_error_message(),
3830
				);
3831
			} else {
3832
				$attachment               = get_post( $attachment_id );
3833
				$uploaded_files[ $index ] = (object) array(
3834
					'id'   => (string) $attachment_id,
3835
					'file' => $attachment->post_title,
3836
					'url'  => wp_get_attachment_url( $attachment_id ),
3837
					'type' => $attachment->post_mime_type,
3838
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3839
				);
3840
				// Zip files uploads are not supported unless they are done for installation purposed
3841
				// lets delete them in case something goes wrong in this whole process
3842
				if ( 'application/zip' === $attachment->post_mime_type ) {
3843
					// Schedule a cleanup for 2 hours from now in case of failed install.
3844
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3845
				}
3846
			}
3847
		}
3848
		if ( ! is_null( $global_post ) ) {
3849
			$GLOBALS['post'] = $global_post;
3850
		}
3851
3852
		return $uploaded_files;
3853
	}
3854
3855
	/**
3856
	 * Add help to the Jetpack page
3857
	 *
3858
	 * @since Jetpack (1.2.3)
3859
	 * @return false if not the Jetpack page
3860
	 */
3861
	function admin_help() {
3862
		$current_screen = get_current_screen();
3863
3864
		// Overview
3865
		$current_screen->add_help_tab(
3866
			array(
3867
				'id'      => 'home',
3868
				'title'   => __( 'Home', 'jetpack' ),
3869
				'content' =>
3870
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3871
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3872
					'<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>',
3873
			)
3874
		);
3875
3876
		// Screen Content
3877
		if ( current_user_can( 'manage_options' ) ) {
3878
			$current_screen->add_help_tab(
3879
				array(
3880
					'id'      => 'settings',
3881
					'title'   => __( 'Settings', 'jetpack' ),
3882
					'content' =>
3883
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3884
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3885
						'<ol>' .
3886
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3887
							'<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>' .
3888
						'</ol>' .
3889
						'<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>',
3890
				)
3891
			);
3892
		}
3893
3894
		// Help Sidebar
3895
		$support_url = Redirect::get_url( 'jetpack-support' );
3896
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3897
		$current_screen->set_help_sidebar(
3898
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3899
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3900
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3901
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3902
		);
3903
	}
3904
3905
	function admin_menu_css() {
3906
		wp_enqueue_style( 'jetpack-icons' );
3907
	}
3908
3909
	function admin_menu_order() {
3910
		return true;
3911
	}
3912
3913 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3914
		$jp_menu_order = array();
3915
3916
		foreach ( $menu_order as $index => $item ) {
3917
			if ( $item != 'jetpack' ) {
3918
				$jp_menu_order[] = $item;
3919
			}
3920
3921
			if ( $index == 0 ) {
3922
				$jp_menu_order[] = 'jetpack';
3923
			}
3924
		}
3925
3926
		return $jp_menu_order;
3927
	}
3928
3929
	function admin_banner_styles() {
3930
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3931
3932 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3933
			wp_register_style(
3934
				'jetpack-dops-style',
3935
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3936
				array(),
3937
				JETPACK__VERSION
3938
			);
3939
		}
3940
3941
		wp_enqueue_style(
3942
			'jetpack',
3943
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3944
			array( 'jetpack-dops-style' ),
3945
			JETPACK__VERSION . '-20121016'
3946
		);
3947
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3948
		wp_style_add_data( 'jetpack', 'suffix', $min );
3949
	}
3950
3951
	function plugin_action_links( $actions ) {
3952
3953
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3954
3955
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3956
			return array_merge(
3957
				$jetpack_home,
3958
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3959
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3960
				$actions
3961
			);
3962
		}
3963
3964
		return array_merge( $jetpack_home, $actions );
3965
	}
3966
3967
	/**
3968
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3969
	 *
3970
	 * @param string $hook The current admin page.
3971
	 *
3972
	 * @return void
3973
	 */
3974
	public function deactivate_dialog( $hook ) {
3975
		if (
3976
			'plugins.php' === $hook
3977
			&& self::is_active()
3978
		) {
3979
3980
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
3981
3982
			if ( count( $active_plugins_using_connection ) > 1 ) {
3983
3984
				add_thickbox();
3985
3986
				wp_register_script(
3987
					'jp-tracks',
3988
					'//stats.wp.com/w.js',
3989
					array(),
3990
					gmdate( 'YW' ),
3991
					true
3992
				);
3993
3994
				wp_register_script(
3995
					'jp-tracks-functions',
3996
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
3997
					array( 'jp-tracks' ),
3998
					JETPACK__VERSION,
3999
					false
4000
				);
4001
4002
				wp_enqueue_script(
4003
					'jetpack-deactivate-dialog-js',
4004
					Assets::get_file_url_for_environment(
4005
						'_inc/build/jetpack-deactivate-dialog.min.js',
4006
						'_inc/jetpack-deactivate-dialog.js'
4007
					),
4008
					array( 'jquery', 'jp-tracks-functions' ),
4009
					JETPACK__VERSION,
4010
					true
4011
				);
4012
4013
				wp_localize_script(
4014
					'jetpack-deactivate-dialog-js',
4015
					'deactivate_dialog',
4016
					array(
4017
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4018
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4019
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4020
					)
4021
				);
4022
4023
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4024
4025
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4026
			}
4027
		}
4028
	}
4029
4030
	/**
4031
	 * Outputs the content of the deactivation modal
4032
	 *
4033
	 * @return void
4034
	 */
4035
	public function deactivate_dialog_content() {
4036
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4037
		unset( $active_plugins_using_connection['jetpack'] );
4038
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4036 can also be of type object<WP_Error>; however, Jetpack::load_view() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4039
	}
4040
4041
	/**
4042
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4043
	 *
4044
	 * @param string $login_url The wp-login URL.
4045
	 * @param string $redirect  URL to redirect users after logging in.
4046
	 * @since Jetpack 8.4
4047
	 * @return string
4048
	 */
4049
	public function login_url( $login_url, $redirect ) {
4050
		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...
4051
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4052
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4053
		}
4054
		return $login_url;
4055
	}
4056
4057
	/**
4058
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4059
	 *
4060
	 * @since Jetpack 8.4
4061
	 */
4062
	public function login_init() {
4063
		// phpcs:ignore WordPress.Security.NonceVerification
4064
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4065
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4066
			wp_safe_redirect(
4067
				add_query_arg(
4068
					array(
4069
						'forceInstall' => 1,
4070
						'url'          => rawurlencode( get_site_url() ),
4071
					),
4072
					// @todo provide way to go to specific calypso env.
4073
					self::get_calypso_host() . 'jetpack/connect'
4074
				)
4075
			);
4076
			exit;
4077
		}
4078
	}
4079
4080
	/*
4081
	 * Registration flow:
4082
	 * 1 - ::admin_page_load() action=register
4083
	 * 2 - ::try_registration()
4084
	 * 3 - ::register()
4085
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4086
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4087
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4088
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4089
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4090
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4091
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4092
	 *       jetpack_id, jetpack_secret, jetpack_public
4093
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4094
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4095
	 * 5 - user logs in with WP.com account
4096
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4097
	 *		- Manager::authorize()
4098
	 *		- Manager::get_token()
4099
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4100
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4101
	 *			- which responds with access_token, token_type, scope
4102
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4103
	 *		- Jetpack::activate_default_modules()
4104
	 *     		- Deactivates deprecated plugins
4105
	 *     		- Activates all default modules
4106
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4107
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4108
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4109
	 *     Done!
4110
	 */
4111
4112
	/**
4113
	 * Handles the page load events for the Jetpack admin page
4114
	 */
4115
	function admin_page_load() {
4116
		$error = false;
4117
4118
		// Make sure we have the right body class to hook stylings for subpages off of.
4119
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4120
4121
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4122
			// Should only be used in intermediate redirects to preserve state across redirects
4123
			self::restate();
4124
		}
4125
4126
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4127
			// @todo: Add validation against a known allowed list.
4128
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4129
			// User clicked in the iframe to link their accounts
4130
			if ( ! self::is_user_connected() ) {
4131
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4132
4133
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4134
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4135
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4136
4137
				if ( isset( $_GET['notes_iframe'] ) ) {
4138
					$connect_url .= '&notes_iframe';
4139
				}
4140
				wp_redirect( $connect_url );
4141
				exit;
4142
			} else {
4143
				if ( ! isset( $_GET['calypso_env'] ) ) {
4144
					self::state( 'message', 'already_authorized' );
4145
					wp_safe_redirect( self::admin_url() );
4146
					exit;
4147
				} else {
4148
					$connect_url  = $this->build_connect_url( true, false, $from );
4149
					$connect_url .= '&already_authorized=true';
4150
					wp_redirect( $connect_url );
4151
					exit;
4152
				}
4153
			}
4154
		}
4155
4156
		if ( isset( $_GET['action'] ) ) {
4157
			switch ( $_GET['action'] ) {
4158
				case 'authorize':
4159
					if ( self::is_active() && self::is_user_connected() ) {
4160
						self::state( 'message', 'already_authorized' );
4161
						wp_safe_redirect( self::admin_url() );
4162
						exit;
4163
					}
4164
					self::log( 'authorize' );
4165
					$client_server = new Jetpack_Client_Server();
4166
					$client_server->client_authorize();
4167
					exit;
4168
				case 'register':
4169
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4170
						$error = 'cheatin';
4171
						break;
4172
					}
4173
					check_admin_referer( 'jetpack-register' );
4174
					self::log( 'register' );
4175
					self::maybe_set_version_option();
4176
					$registered = self::try_registration();
4177 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4178
						$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...
4179
						self::state( 'error', $error );
4180
						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...
4181
4182
						/**
4183
						 * Jetpack registration Error.
4184
						 *
4185
						 * @since 7.5.0
4186
						 *
4187
						 * @param string|int $error The error code.
4188
						 * @param \WP_Error $registered The error object.
4189
						 */
4190
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4191
						break;
4192
					}
4193
4194
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4195
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4196
4197
					/**
4198
					 * Jetpack registration Success.
4199
					 *
4200
					 * @since 7.5.0
4201
					 *
4202
					 * @param string $from 'from' GET parameter;
4203
					 */
4204
					do_action( 'jetpack_connection_register_success', $from );
4205
4206
					$url = $this->build_connect_url( true, $redirect, $from );
4207
4208
					if ( ! empty( $_GET['onboarding'] ) ) {
4209
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4210
					}
4211
4212
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4213
						$url = add_query_arg( 'auth_approved', 'true', $url );
4214
					}
4215
4216
					wp_redirect( $url );
4217
					exit;
4218
				case 'activate':
4219
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4220
						$error = 'cheatin';
4221
						break;
4222
					}
4223
4224
					$module = stripslashes( $_GET['module'] );
4225
					check_admin_referer( "jetpack_activate-$module" );
4226
					self::log( 'activate', $module );
4227
					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...
4228
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4229
					}
4230
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4231
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4232
					exit;
4233
				case 'activate_default_modules':
4234
					check_admin_referer( 'activate_default_modules' );
4235
					self::log( 'activate_default_modules' );
4236
					self::restate();
4237
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4238
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4239
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4240
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4241
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4242
					exit;
4243
				case 'disconnect':
4244
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4245
						$error = 'cheatin';
4246
						break;
4247
					}
4248
4249
					check_admin_referer( 'jetpack-disconnect' );
4250
					self::log( 'disconnect' );
4251
					self::disconnect();
4252
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4253
					exit;
4254
				case 'reconnect':
4255
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4256
						$error = 'cheatin';
4257
						break;
4258
					}
4259
4260
					check_admin_referer( 'jetpack-reconnect' );
4261
					self::log( 'reconnect' );
4262
					$this->disconnect();
4263
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4264
					exit;
4265 View Code Duplication
				case 'deactivate':
4266
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4267
						$error = 'cheatin';
4268
						break;
4269
					}
4270
4271
					$modules = stripslashes( $_GET['module'] );
4272
					check_admin_referer( "jetpack_deactivate-$modules" );
4273
					foreach ( explode( ',', $modules ) as $module ) {
4274
						self::log( 'deactivate', $module );
4275
						self::deactivate_module( $module );
4276
						self::state( 'message', 'module_deactivated' );
4277
					}
4278
					self::state( 'module', $modules );
4279
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4280
					exit;
4281
				case 'unlink':
4282
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4283
					check_admin_referer( 'jetpack-unlink' );
4284
					self::log( 'unlink' );
4285
					Connection_Manager::disconnect_user();
4286
					self::state( 'message', 'unlinked' );
4287
					if ( 'sub-unlink' == $redirect ) {
4288
						wp_safe_redirect( admin_url() );
4289
					} else {
4290
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4291
					}
4292
					exit;
4293
				case 'onboard':
4294
					if ( ! current_user_can( 'manage_options' ) ) {
4295
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4296
					} else {
4297
						self::create_onboarding_token();
4298
						$url = $this->build_connect_url( true );
4299
4300
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4301
							$url = add_query_arg( 'onboarding', $token, $url );
4302
						}
4303
4304
						$calypso_env = $this->get_calypso_env();
4305
						if ( ! empty( $calypso_env ) ) {
4306
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4307
						}
4308
4309
						wp_redirect( $url );
4310
						exit;
4311
					}
4312
					exit;
4313
				default:
4314
					/**
4315
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4316
					 *
4317
					 * @since 2.6.0
4318
					 *
4319
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4320
					 */
4321
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4322
			}
4323
		}
4324
4325
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4326
			self::activate_new_modules( true );
4327
		}
4328
4329
		$message_code = self::state( 'message' );
4330
		if ( self::state( 'optin-manage' ) ) {
4331
			$activated_manage = $message_code;
4332
			$message_code     = 'jetpack-manage';
4333
		}
4334
4335
		switch ( $message_code ) {
4336
			case 'jetpack-manage':
4337
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4338
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4339
				$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>';
4340
				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...
4341
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4342
				}
4343
				break;
4344
4345
		}
4346
4347
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4348
4349
		if ( ! empty( $deactivated_plugins ) ) {
4350
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4351
			$deactivated_titles  = array();
4352
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4353
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4354
					continue;
4355
				}
4356
4357
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4358
			}
4359
4360
			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...
4361
				if ( $this->message ) {
4362
					$this->message .= "<br /><br />\n";
4363
				}
4364
4365
				$this->message .= wp_sprintf(
4366
					_n(
4367
						'Jetpack contains the most recent version of the old %l plugin.',
4368
						'Jetpack contains the most recent versions of the old %l plugins.',
4369
						count( $deactivated_titles ),
4370
						'jetpack'
4371
					),
4372
					$deactivated_titles
4373
				);
4374
4375
				$this->message .= "<br />\n";
4376
4377
				$this->message .= _n(
4378
					'The old version has been deactivated and can be removed from your site.',
4379
					'The old versions have been deactivated and can be removed from your site.',
4380
					count( $deactivated_titles ),
4381
					'jetpack'
4382
				);
4383
			}
4384
		}
4385
4386
		$this->privacy_checks = self::state( 'privacy_checks' );
4387
4388
		if ( $this->message || $this->error || $this->privacy_checks ) {
4389
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4390
		}
4391
4392
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4393
	}
4394
4395
	function admin_notices() {
4396
4397
		if ( $this->error ) {
4398
			?>
4399
<div id="message" class="jetpack-message jetpack-err">
4400
	<div class="squeezer">
4401
		<h2>
4402
			<?php
4403
			echo wp_kses(
4404
				$this->error,
4405
				array(
4406
					'a'      => array( 'href' => array() ),
4407
					'small'  => true,
4408
					'code'   => true,
4409
					'strong' => true,
4410
					'br'     => true,
4411
					'b'      => true,
4412
				)
4413
			);
4414
			?>
4415
			</h2>
4416
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4417
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4418
<?php	endif; ?>
4419
	</div>
4420
</div>
4421
			<?php
4422
		}
4423
4424
		if ( $this->message ) {
4425
			?>
4426
<div id="message" class="jetpack-message">
4427
	<div class="squeezer">
4428
		<h2>
4429
			<?php
4430
			echo wp_kses(
4431
				$this->message,
4432
				array(
4433
					'strong' => array(),
4434
					'a'      => array( 'href' => true ),
4435
					'br'     => true,
4436
				)
4437
			);
4438
			?>
4439
			</h2>
4440
	</div>
4441
</div>
4442
			<?php
4443
		}
4444
4445
		if ( $this->privacy_checks ) :
4446
			$module_names = $module_slugs = array();
4447
4448
			$privacy_checks = explode( ',', $this->privacy_checks );
4449
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4450
			foreach ( $privacy_checks as $module_slug ) {
4451
				$module = self::get_module( $module_slug );
4452
				if ( ! $module ) {
4453
					continue;
4454
				}
4455
4456
				$module_slugs[] = $module_slug;
4457
				$module_names[] = "<strong>{$module['name']}</strong>";
4458
			}
4459
4460
			$module_slugs = join( ',', $module_slugs );
4461
			?>
4462
<div id="message" class="jetpack-message jetpack-err">
4463
	<div class="squeezer">
4464
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4465
		<p>
4466
			<?php
4467
			echo wp_kses(
4468
				wptexturize(
4469
					wp_sprintf(
4470
						_nx(
4471
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4472
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4473
							count( $privacy_checks ),
4474
							'%l = list of Jetpack module/feature names',
4475
							'jetpack'
4476
						),
4477
						$module_names
4478
					)
4479
				),
4480
				array( 'strong' => true )
4481
			);
4482
4483
			echo "\n<br />\n";
4484
4485
			echo wp_kses(
4486
				sprintf(
4487
					_nx(
4488
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4489
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4490
						count( $privacy_checks ),
4491
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4492
						'jetpack'
4493
					),
4494
					wp_nonce_url(
4495
						self::admin_url(
4496
							array(
4497
								'page'   => 'jetpack',
4498
								'action' => 'deactivate',
4499
								'module' => urlencode( $module_slugs ),
4500
							)
4501
						),
4502
						"jetpack_deactivate-$module_slugs"
4503
					),
4504
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4505
				),
4506
				array(
4507
					'a' => array(
4508
						'href'  => true,
4509
						'title' => true,
4510
					),
4511
				)
4512
			);
4513
			?>
4514
		</p>
4515
	</div>
4516
</div>
4517
			<?php
4518
endif;
4519
	}
4520
4521
	/**
4522
	 * We can't always respond to a signed XML-RPC request with a
4523
	 * helpful error message. In some circumstances, doing so could
4524
	 * leak information.
4525
	 *
4526
	 * Instead, track that the error occurred via a Jetpack_Option,
4527
	 * and send that data back in the heartbeat.
4528
	 * All this does is increment a number, but it's enough to find
4529
	 * trends.
4530
	 *
4531
	 * @param WP_Error $xmlrpc_error The error produced during
4532
	 *                               signature validation.
4533
	 */
4534
	function track_xmlrpc_error( $xmlrpc_error ) {
4535
		$code = is_wp_error( $xmlrpc_error )
4536
			? $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...
4537
			: 'should-not-happen';
4538
4539
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4540
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4541
			// No need to update the option if we already have
4542
			// this code stored.
4543
			return;
4544
		}
4545
		$xmlrpc_errors[ $code ] = true;
4546
4547
		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...
4548
	}
4549
4550
	/**
4551
	 * Initialize the jetpack stats instance only when needed
4552
	 *
4553
	 * @return void
4554
	 */
4555
	private function initialize_stats() {
4556
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4557
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4558
		}
4559
	}
4560
4561
	/**
4562
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4563
	 */
4564
	function stat( $group, $detail ) {
4565
		$this->initialize_stats();
4566
		$this->a8c_mc_stats_instance->add( $group, $detail );
4567
4568
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4569
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4570
	}
4571
4572
	/**
4573
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4574
	 */
4575
	function do_stats( $method = '' ) {
4576
		$this->initialize_stats();
4577
		if ( 'server_side' === $method ) {
4578
			$this->a8c_mc_stats_instance->do_server_side_stats();
4579
		} else {
4580
			$this->a8c_mc_stats_instance->do_stats();
4581
		}
4582
4583
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4584
		$this->stats = array();
4585
	}
4586
4587
	/**
4588
	 * Runs stats code for a one-off, server-side.
4589
	 *
4590
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4591
	 *
4592
	 * @return bool If it worked.
4593
	 */
4594
	static function do_server_side_stat( $args ) {
4595
		$url                   = self::build_stats_url( $args );
4596
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4597
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4598
	}
4599
4600
	/**
4601
	 * Builds the stats url.
4602
	 *
4603
	 * @param $args array|string The arguments to append to the URL.
4604
	 *
4605
	 * @return string The URL to be pinged.
4606
	 */
4607
	static function build_stats_url( $args ) {
4608
4609
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4610
		return $a8c_mc_stats_instance->build_stats_url( $args );
4611
4612
	}
4613
4614
	/**
4615
	 * Get the role of the current user.
4616
	 *
4617
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4618
	 *
4619
	 * @access public
4620
	 * @static
4621
	 *
4622
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4623
	 */
4624
	public static function translate_current_user_to_role() {
4625
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4626
4627
		$roles = new Roles();
4628
		return $roles->translate_current_user_to_role();
4629
	}
4630
4631
	/**
4632
	 * Get the role of a particular user.
4633
	 *
4634
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4635
	 *
4636
	 * @access public
4637
	 * @static
4638
	 *
4639
	 * @param \WP_User $user User object.
4640
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4641
	 */
4642
	public static function translate_user_to_role( $user ) {
4643
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4644
4645
		$roles = new Roles();
4646
		return $roles->translate_user_to_role( $user );
4647
	}
4648
4649
	/**
4650
	 * Get the minimum capability for a role.
4651
	 *
4652
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4653
	 *
4654
	 * @access public
4655
	 * @static
4656
	 *
4657
	 * @param string $role Role name.
4658
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4659
	 */
4660
	public static function translate_role_to_cap( $role ) {
4661
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4662
4663
		$roles = new Roles();
4664
		return $roles->translate_role_to_cap( $role );
4665
	}
4666
4667
	/**
4668
	 * Sign a user role with the master access token.
4669
	 * If not specified, will default to the current user.
4670
	 *
4671
	 * @deprecated since 7.7
4672
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4673
	 *
4674
	 * @access public
4675
	 * @static
4676
	 *
4677
	 * @param string $role    User role.
4678
	 * @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...
4679
	 * @return string Signed user role.
4680
	 */
4681
	public static function sign_role( $role, $user_id = null ) {
4682
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4683
		return self::connection()->sign_role( $role, $user_id );
4684
	}
4685
4686
	/**
4687
	 * Builds a URL to the Jetpack connection auth page
4688
	 *
4689
	 * @since 3.9.5
4690
	 *
4691
	 * @param bool        $raw If true, URL will not be escaped.
4692
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4693
	 *                              If string, will be a custom redirect.
4694
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4695
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4696
	 *
4697
	 * @return string Connect URL
4698
	 */
4699
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4700
		$site_id    = Jetpack_Options::get_option( 'id' );
4701
		$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...
4702
4703
		if ( $register || ! $blog_token || ! $site_id ) {
4704
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4705
4706
			if ( ! empty( $redirect ) ) {
4707
				$url = add_query_arg(
4708
					'redirect',
4709
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4710
					$url
4711
				);
4712
			}
4713
4714
			if ( is_network_admin() ) {
4715
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4716
			}
4717
4718
			$calypso_env = self::get_calypso_env();
4719
4720
			if ( ! empty( $calypso_env ) ) {
4721
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4722
			}
4723
		} else {
4724
4725
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4726
			// because otherwise this logic can get us in to a loop.
4727
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4728
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4729
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4730
4731
				$response = Client::wpcom_json_api_request_as_blog(
4732
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4733
					'1.1'
4734
				);
4735
4736
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4737
4738
					// Generating a register URL instead to refresh the existing token
4739
					return $this->build_connect_url( $raw, $redirect, $from, true );
4740
				}
4741
			}
4742
4743
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4699 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...
4744
		}
4745
4746
		if ( $from ) {
4747
			$url = add_query_arg( 'from', $from, $url );
4748
		}
4749
4750
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4751
		/**
4752
		 * Filter the URL used when connecting a user to a WordPress.com account.
4753
		 *
4754
		 * @since 8.1.0
4755
		 *
4756
		 * @param string $url Connection URL.
4757
		 * @param bool   $raw If true, URL will not be escaped.
4758
		 */
4759
		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...
4760
	}
4761
4762
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4763
4764
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4765
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4766
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4767
4768
		if ( $iframe ) {
4769
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4770
		}
4771
4772
		$c8n = self::connection();
4773
		$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...
4774
4775
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4776
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4777
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4778
4779
		if ( $iframe ) {
4780
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4781
		}
4782
4783
		return $url;
4784
	}
4785
4786
	/**
4787
	 * Filters the connection URL parameter array.
4788
	 *
4789
	 * @param array $args default URL parameters used by the package.
4790
	 * @return array the modified URL arguments array.
4791
	 */
4792
	public static function filter_connect_request_body( $args ) {
4793
		if (
4794
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4795
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4796
		) {
4797
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4798
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4799
				? $gp_locale->slug
4800
				: '';
4801
		}
4802
4803
		$tracking        = new Tracking();
4804
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4805
4806
		$args = array_merge(
4807
			$args,
4808
			array(
4809
				'_ui' => $tracks_identity['_ui'],
4810
				'_ut' => $tracks_identity['_ut'],
4811
			)
4812
		);
4813
4814
		$calypso_env = self::get_calypso_env();
4815
4816
		if ( ! empty( $calypso_env ) ) {
4817
			$args['calypso_env'] = $calypso_env;
4818
		}
4819
4820
		return $args;
4821
	}
4822
4823
	/**
4824
	 * Filters the URL that will process the connection data. It can be different from the URL
4825
	 * that we send the user to after everything is done.
4826
	 *
4827
	 * @param String $processing_url the default redirect URL used by the package.
4828
	 * @return String the modified URL.
4829
	 */
4830
	public static function filter_connect_processing_url( $processing_url ) {
4831
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4832
		return $processing_url;
4833
	}
4834
4835
	/**
4836
	 * Filters the redirection URL that is used for connect requests. The redirect
4837
	 * URL should return the user back to the Jetpack console.
4838
	 *
4839
	 * @param String $redirect the default redirect URL used by the package.
4840
	 * @return String the modified URL.
4841
	 */
4842
	public static function filter_connect_redirect_url( $redirect ) {
4843
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4844
		$redirect           = $redirect
4845
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4846
			: $jetpack_admin_page;
4847
4848
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4849
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4850
		}
4851
4852
		return $redirect;
4853
	}
4854
4855
	/**
4856
	 * This action fires at the beginning of the Manager::authorize method.
4857
	 */
4858
	public static function authorize_starting() {
4859
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4860
		// Checking if site has been active/connected previously before recording unique connection.
4861
		if ( ! $jetpack_unique_connection ) {
4862
			// jetpack_unique_connection option has never been set.
4863
			$jetpack_unique_connection = array(
4864
				'connected'    => 0,
4865
				'disconnected' => 0,
4866
				'version'      => '3.6.1',
4867
			);
4868
4869
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4870
4871
			// Track unique connection.
4872
			$jetpack = self::init();
4873
4874
			$jetpack->stat( 'connections', 'unique-connection' );
4875
			$jetpack->do_stats( 'server_side' );
4876
		}
4877
4878
		// Increment number of times connected.
4879
		$jetpack_unique_connection['connected'] += 1;
4880
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4881
	}
4882
4883
	/**
4884
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4885
	 * linked.
4886
	 */
4887
	public static function authorize_ending_linked() {
4888
		// Don't activate anything since we are just connecting a user.
4889
		self::state( 'message', 'linked' );
4890
	}
4891
4892
	/**
4893
	 * This action fires at the end of the Manager::authorize method when the master user is
4894
	 * authorized.
4895
	 *
4896
	 * @param array $data The request data.
4897
	 */
4898
	public static function authorize_ending_authorized( $data ) {
4899
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4900
		self::invalidate_onboarding_token();
4901
4902
		// If redirect_uri is SSO, ensure SSO module is enabled.
4903
		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...
4904
4905
		/** This filter is documented in class.jetpack-cli.php */
4906
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4907
4908
		$activate_sso = (
4909
			isset( $redirect_options['action'] ) &&
4910
			'jetpack-sso' === $redirect_options['action'] &&
4911
			$jetpack_start_enable_sso
4912
		);
4913
4914
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4915
4916
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4917
	}
4918
4919
	/**
4920
	 * Get our assumed site creation date.
4921
	 * Calculated based on the earlier date of either:
4922
	 * - Earliest admin user registration date.
4923
	 * - Earliest date of post of any post type.
4924
	 *
4925
	 * @since 7.2.0
4926
	 * @deprecated since 7.8.0
4927
	 *
4928
	 * @return string Assumed site creation date and time.
4929
	 */
4930
	public static function get_assumed_site_creation_date() {
4931
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4932
		return self::connection()->get_assumed_site_creation_date();
4933
	}
4934
4935 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4936
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4937
4938
		if ( $activation_source_name ) {
4939
			$args['_as'] = urlencode( $activation_source_name );
4940
		}
4941
4942
		if ( $activation_source_keyword ) {
4943
			$args['_ak'] = urlencode( $activation_source_keyword );
4944
		}
4945
	}
4946
4947
	function build_reconnect_url( $raw = false ) {
4948
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4949
		return $raw ? $url : esc_url( $url );
4950
	}
4951
4952
	public static function admin_url( $args = null ) {
4953
		$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...
4954
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4955
		return $url;
4956
	}
4957
4958
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4959
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4960
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4961
	}
4962
4963
	function dismiss_jetpack_notice() {
4964
4965
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4966
			return;
4967
		}
4968
4969
		switch ( $_GET['jetpack-notice'] ) {
4970
			case 'dismiss':
4971
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4972
4973
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4974
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4975
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4976
				}
4977
				break;
4978
		}
4979
	}
4980
4981
	public static function sort_modules( $a, $b ) {
4982
		if ( $a['sort'] == $b['sort'] ) {
4983
			return 0;
4984
		}
4985
4986
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4987
	}
4988
4989
	function ajax_recheck_ssl() {
4990
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4991
		$result = self::permit_ssl( true );
4992
		wp_send_json(
4993
			array(
4994
				'enabled' => $result,
4995
				'message' => get_transient( 'jetpack_https_test_message' ),
4996
			)
4997
		);
4998
	}
4999
5000
	/* Client API */
5001
5002
	/**
5003
	 * Returns the requested Jetpack API URL
5004
	 *
5005
	 * @deprecated since 7.7
5006
	 * @return string
5007
	 */
5008
	public static function api_url( $relative_url ) {
5009
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5010
		$connection = self::connection();
5011
		return $connection->api_url( $relative_url );
5012
	}
5013
5014
	/**
5015
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5016
	 *
5017
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5018
	 */
5019
	public static function fix_url_for_bad_hosts( $url ) {
5020
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5021
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5022
	}
5023
5024
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5025
		// Default to a blog token.
5026
		$token_type = 'blog';
5027
5028
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5029
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5030
			if ( ! empty( $_GET['onboarding'] ) ) {
5031
				$jpo = $_GET;
5032
			} else {
5033
				$jpo = json_decode( $request_data, true );
5034
			}
5035
5036
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5037
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5038
5039
			if (
5040
				isset( $jpo_user )
5041
				&& isset( $jpo_token )
5042
				&& is_email( $jpo_user )
5043
				&& ctype_alnum( $jpo_token )
5044
				&& isset( $_GET['rest_route'] )
5045
				&& self::validate_onboarding_token_action(
5046
					$jpo_token,
5047
					$_GET['rest_route']
5048
				)
5049
			) {
5050
				$jp_user = get_user_by( 'email', $jpo_user );
5051
				if ( is_a( $jp_user, 'WP_User' ) ) {
5052
					wp_set_current_user( $jp_user->ID );
5053
					$user_can = is_multisite()
5054
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5055
						: current_user_can( 'manage_options' );
5056
					if ( $user_can ) {
5057
						$token_type              = 'user';
5058
						$token->external_user_id = $jp_user->ID;
5059
					}
5060
				}
5061
			}
5062
5063
			$token_data['type']    = $token_type;
5064
			$token_data['user_id'] = $token->external_user_id;
5065
		}
5066
5067
		return $token_data;
5068
	}
5069
5070
	/**
5071
	 * Create a random secret for validating onboarding payload
5072
	 *
5073
	 * @return string Secret token
5074
	 */
5075
	public static function create_onboarding_token() {
5076
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5077
			$token = wp_generate_password( 32, false );
5078
			Jetpack_Options::update_option( 'onboarding', $token );
5079
		}
5080
5081
		return $token;
5082
	}
5083
5084
	/**
5085
	 * Remove the onboarding token
5086
	 *
5087
	 * @return bool True on success, false on failure
5088
	 */
5089
	public static function invalidate_onboarding_token() {
5090
		return Jetpack_Options::delete_option( 'onboarding' );
5091
	}
5092
5093
	/**
5094
	 * Validate an onboarding token for a specific action
5095
	 *
5096
	 * @return boolean True if token/action pair is accepted, false if not
5097
	 */
5098
	public static function validate_onboarding_token_action( $token, $action ) {
5099
		// Compare tokens, bail if tokens do not match
5100
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5101
			return false;
5102
		}
5103
5104
		// List of valid actions we can take
5105
		$valid_actions = array(
5106
			'/jetpack/v4/settings',
5107
		);
5108
5109
		// Only allow valid actions.
5110
		if ( ! in_array( $action, $valid_actions ) ) {
5111
			return false;
5112
		}
5113
5114
		return true;
5115
	}
5116
5117
	/**
5118
	 * Checks to see if the URL is using SSL to connect with Jetpack
5119
	 *
5120
	 * @since 2.3.3
5121
	 * @return boolean
5122
	 */
5123
	public static function permit_ssl( $force_recheck = false ) {
5124
		// Do some fancy tests to see if ssl is being supported
5125
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5126
			$message = '';
5127
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5128
				$ssl = 0;
5129
			} else {
5130
				switch ( JETPACK_CLIENT__HTTPS ) {
5131
					case 'NEVER':
5132
						$ssl     = 0;
5133
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5134
						break;
5135
					case 'ALWAYS':
5136
					case 'AUTO':
5137
					default:
5138
						$ssl = 1;
5139
						break;
5140
				}
5141
5142
				// If it's not 'NEVER', test to see
5143
				if ( $ssl ) {
5144
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5145
						$ssl     = 0;
5146
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5147
					} else {
5148
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5149
						if ( is_wp_error( $response ) ) {
5150
							$ssl     = 0;
5151
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5152
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5153
							$ssl     = 0;
5154
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5155
						}
5156
					}
5157
				}
5158
			}
5159
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5160
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5161
		}
5162
5163
		return (bool) $ssl;
5164
	}
5165
5166
	/*
5167
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5168
	 */
5169
	public function alert_auto_ssl_fail() {
5170
		if ( ! current_user_can( 'manage_options' ) ) {
5171
			return;
5172
		}
5173
5174
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5175
		?>
5176
5177
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5178
			<div class="jp-banner__content">
5179
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5180
				<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>
5181
				<p>
5182
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5183
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5184
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5185
				</p>
5186
				<p>
5187
					<?php
5188
					printf(
5189
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5190
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5191
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5192
					);
5193
					?>
5194
				</p>
5195
			</div>
5196
		</div>
5197
		<style>
5198
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5199
		</style>
5200
		<script type="text/javascript">
5201
			jQuery( document ).ready( function( $ ) {
5202
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5203
					var $this = $( this );
5204
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5205
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5206
					e.preventDefault();
5207
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5208
					$.post( ajaxurl, data )
5209
					  .done( function( response ) {
5210
						  if ( response.enabled ) {
5211
							  $( '#jetpack-ssl-warning' ).hide();
5212
						  } else {
5213
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5214
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5215
						  }
5216
					  }.bind( $this ) );
5217
				} );
5218
			} );
5219
		</script>
5220
5221
		<?php
5222
	}
5223
5224
	/**
5225
	 * Returns the Jetpack XML-RPC API
5226
	 *
5227
	 * @deprecated 8.0 Use Connection_Manager instead.
5228
	 * @return string
5229
	 */
5230
	public static function xmlrpc_api_url() {
5231
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5232
		return self::connection()->xmlrpc_api_url();
5233
	}
5234
5235
	/**
5236
	 * Returns the connection manager object.
5237
	 *
5238
	 * @return Automattic\Jetpack\Connection\Manager
5239
	 */
5240
	public static function connection() {
5241
		$jetpack = static::init();
5242
5243
		// If the connection manager hasn't been instantiated, do that now.
5244
		if ( ! $jetpack->connection_manager ) {
5245
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5246
		}
5247
5248
		return $jetpack->connection_manager;
5249
	}
5250
5251
	/**
5252
	 * Creates two secret tokens and the end of life timestamp for them.
5253
	 *
5254
	 * Note these tokens are unique per call, NOT static per site for connecting.
5255
	 *
5256
	 * @since 2.6
5257
	 * @param String  $action  The action name.
5258
	 * @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...
5259
	 * @param Integer $exp     Expiration time in seconds.
5260
	 * @return array
5261
	 */
5262
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5263
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5264
	}
5265
5266
	public static function get_secrets( $action, $user_id ) {
5267
		$secrets = self::connection()->get_secrets( $action, $user_id );
5268
5269
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5270
			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...
5271
		}
5272
5273
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5274
			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...
5275
		}
5276
5277
		return $secrets;
5278
	}
5279
5280
	/**
5281
	 * @deprecated 7.5 Use Connection_Manager instead.
5282
	 *
5283
	 * @param $action
5284
	 * @param $user_id
5285
	 */
5286
	public static function delete_secrets( $action, $user_id ) {
5287
		return self::connection()->delete_secrets( $action, $user_id );
5288
	}
5289
5290
	/**
5291
	 * Builds the timeout limit for queries talking with the wpcom servers.
5292
	 *
5293
	 * Based on local php max_execution_time in php.ini
5294
	 *
5295
	 * @since 2.6
5296
	 * @return int
5297
	 * @deprecated
5298
	 **/
5299
	public function get_remote_query_timeout_limit() {
5300
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5301
		return self::get_max_execution_time();
5302
	}
5303
5304
	/**
5305
	 * Builds the timeout limit for queries talking with the wpcom servers.
5306
	 *
5307
	 * Based on local php max_execution_time in php.ini
5308
	 *
5309
	 * @since 5.4
5310
	 * @return int
5311
	 **/
5312
	public static function get_max_execution_time() {
5313
		$timeout = (int) ini_get( 'max_execution_time' );
5314
5315
		// Ensure exec time set in php.ini
5316
		if ( ! $timeout ) {
5317
			$timeout = 30;
5318
		}
5319
		return $timeout;
5320
	}
5321
5322
	/**
5323
	 * Sets a minimum request timeout, and returns the current timeout
5324
	 *
5325
	 * @since 5.4
5326
	 **/
5327 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5328
		$timeout = self::get_max_execution_time();
5329
		if ( $timeout < $min_timeout ) {
5330
			$timeout = $min_timeout;
5331
			set_time_limit( $timeout );
5332
		}
5333
		return $timeout;
5334
	}
5335
5336
	/**
5337
	 * Takes the response from the Jetpack register new site endpoint and
5338
	 * verifies it worked properly.
5339
	 *
5340
	 * @since 2.6
5341
	 * @deprecated since 7.7.0
5342
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5343
	 **/
5344
	public function validate_remote_register_response() {
5345
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5346
	}
5347
5348
	/**
5349
	 * @return bool|WP_Error
5350
	 */
5351
	public static function register() {
5352
		$tracking = new Tracking();
5353
		$tracking->record_user_event( 'jpc_register_begin' );
5354
5355
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5356
5357
		$connection   = self::connection();
5358
		$registration = $connection->register();
5359
5360
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5361
5362
		if ( ! $registration || is_wp_error( $registration ) ) {
5363
			return $registration;
5364
		}
5365
5366
		return true;
5367
	}
5368
5369
	/**
5370
	 * Filters the registration request body to include tracking properties.
5371
	 *
5372
	 * @param array $properties
5373
	 * @return array amended properties.
5374
	 */
5375 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5376
		$tracking        = new Tracking();
5377
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5378
5379
		return array_merge(
5380
			$properties,
5381
			array(
5382
				'_ui' => $tracks_identity['_ui'],
5383
				'_ut' => $tracks_identity['_ut'],
5384
			)
5385
		);
5386
	}
5387
5388
	/**
5389
	 * Filters the token request body to include tracking properties.
5390
	 *
5391
	 * @param array $properties
5392
	 * @return array amended properties.
5393
	 */
5394 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5395
		$tracking        = new Tracking();
5396
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5397
5398
		return array_merge(
5399
			$properties,
5400
			array(
5401
				'_ui' => $tracks_identity['_ui'],
5402
				'_ut' => $tracks_identity['_ut'],
5403
			)
5404
		);
5405
	}
5406
5407
	/**
5408
	 * If the db version is showing something other that what we've got now, bump it to current.
5409
	 *
5410
	 * @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...
5411
	 */
5412
	public static function maybe_set_version_option() {
5413
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5414
		if ( JETPACK__VERSION != $version ) {
5415
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5416
5417
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5418
				/** This action is documented in class.jetpack.php */
5419
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5420
			}
5421
5422
			return true;
5423
		}
5424
		return false;
5425
	}
5426
5427
	/* Client Server API */
5428
5429
	/**
5430
	 * Loads the Jetpack XML-RPC client.
5431
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5432
	 *
5433
	 * @deprecated since 7.7.0
5434
	 */
5435
	public static function load_xml_rpc_client() {
5436
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5437
	}
5438
5439
	/**
5440
	 * Resets the saved authentication state in between testing requests.
5441
	 */
5442
	public function reset_saved_auth_state() {
5443
		$this->rest_authentication_status = null;
5444
5445
		if ( ! $this->connection_manager ) {
5446
			$this->connection_manager = new Connection_Manager();
5447
		}
5448
5449
		$this->connection_manager->reset_saved_auth_state();
5450
	}
5451
5452
	/**
5453
	 * Verifies the signature of the current request.
5454
	 *
5455
	 * @deprecated since 7.7.0
5456
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5457
	 *
5458
	 * @return false|array
5459
	 */
5460
	public function verify_xml_rpc_signature() {
5461
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5462
		return self::connection()->verify_xml_rpc_signature();
5463
	}
5464
5465
	/**
5466
	 * Verifies the signature of the current request.
5467
	 *
5468
	 * This function has side effects and should not be used. Instead,
5469
	 * use the memoized version `->verify_xml_rpc_signature()`.
5470
	 *
5471
	 * @deprecated since 7.7.0
5472
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5473
	 * @internal
5474
	 */
5475
	private function internal_verify_xml_rpc_signature() {
5476
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5477
	}
5478
5479
	/**
5480
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5481
	 *
5482
	 * @deprecated since 7.7.0
5483
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5484
	 *
5485
	 * @param \WP_User|mixed $user     User object if authenticated.
5486
	 * @param string         $username Username.
5487
	 * @param string         $password Password string.
5488
	 * @return \WP_User|mixed Authenticated user or error.
5489
	 */
5490 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5491
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5492
5493
		if ( ! $this->connection_manager ) {
5494
			$this->connection_manager = new Connection_Manager();
5495
		}
5496
5497
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5498
	}
5499
5500
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5501
	// Uses the existing XMLRPC request signing implementation.
5502
	function wp_rest_authenticate( $user ) {
5503
		if ( ! empty( $user ) ) {
5504
			// Another authentication method is in effect.
5505
			return $user;
5506
		}
5507
5508
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5509
			// Nothing to do for this authentication method.
5510
			return null;
5511
		}
5512
5513
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5514
			// Nothing to do for this authentication method.
5515
			return null;
5516
		}
5517
5518
		// Ensure that we always have the request body available.  At this
5519
		// point, the WP REST API code to determine the request body has not
5520
		// run yet.  That code may try to read from 'php://input' later, but
5521
		// this can only be done once per request in PHP versions prior to 5.6.
5522
		// So we will go ahead and perform this read now if needed, and save
5523
		// the request body where both the Jetpack signature verification code
5524
		// and the WP REST API code can see it.
5525
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5526
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5527
		}
5528
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5529
5530
		// Only support specific request parameters that have been tested and
5531
		// are known to work with signature verification.  A different method
5532
		// can be passed to the WP REST API via the '?_method=' parameter if
5533
		// needed.
5534
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5535
			$this->rest_authentication_status = new WP_Error(
5536
				'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...
5537
				__( 'This request method is not supported.', 'jetpack' ),
5538
				array( 'status' => 400 )
5539
			);
5540
			return null;
5541
		}
5542
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5543
			$this->rest_authentication_status = new WP_Error(
5544
				'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...
5545
				__( 'This request method does not support body parameters.', 'jetpack' ),
5546
				array( 'status' => 400 )
5547
			);
5548
			return null;
5549
		}
5550
5551
		if ( ! $this->connection_manager ) {
5552
			$this->connection_manager = new Connection_Manager();
5553
		}
5554
5555
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5556
5557
		if (
5558
			$verified &&
5559
			isset( $verified['type'] ) &&
5560
			'user' === $verified['type'] &&
5561
			! empty( $verified['user_id'] )
5562
		) {
5563
			// Authentication successful.
5564
			$this->rest_authentication_status = true;
5565
			return $verified['user_id'];
5566
		}
5567
5568
		// Something else went wrong.  Probably a signature error.
5569
		$this->rest_authentication_status = new WP_Error(
5570
			'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...
5571
			__( 'The request is not signed correctly.', 'jetpack' ),
5572
			array( 'status' => 400 )
5573
		);
5574
		return null;
5575
	}
5576
5577
	/**
5578
	 * Report authentication status to the WP REST API.
5579
	 *
5580
	 * @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...
5581
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5582
	 */
5583
	public function wp_rest_authentication_errors( $value ) {
5584
		if ( $value !== null ) {
5585
			return $value;
5586
		}
5587
		return $this->rest_authentication_status;
5588
	}
5589
5590
	/**
5591
	 * Add our nonce to this request.
5592
	 *
5593
	 * @deprecated since 7.7.0
5594
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5595
	 *
5596
	 * @param int    $timestamp Timestamp of the request.
5597
	 * @param string $nonce     Nonce string.
5598
	 */
5599 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5600
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5601
5602
		if ( ! $this->connection_manager ) {
5603
			$this->connection_manager = new Connection_Manager();
5604
		}
5605
5606
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5607
	}
5608
5609
	/**
5610
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5611
	 * Capture it here so we can verify the signature later.
5612
	 *
5613
	 * @deprecated since 7.7.0
5614
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5615
	 *
5616
	 * @param array $methods XMLRPC methods.
5617
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5618
	 */
5619 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5620
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5621
5622
		if ( ! $this->connection_manager ) {
5623
			$this->connection_manager = new Connection_Manager();
5624
		}
5625
5626
		return $this->connection_manager->xmlrpc_methods( $methods );
5627
	}
5628
5629
	/**
5630
	 * Register additional public XMLRPC methods.
5631
	 *
5632
	 * @deprecated since 7.7.0
5633
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5634
	 *
5635
	 * @param array $methods Public XMLRPC methods.
5636
	 * @return array Public XMLRPC methods, with the getOptions one.
5637
	 */
5638 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5639
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5640
5641
		if ( ! $this->connection_manager ) {
5642
			$this->connection_manager = new Connection_Manager();
5643
		}
5644
5645
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5646
	}
5647
5648
	/**
5649
	 * Handles a getOptions XMLRPC method call.
5650
	 *
5651
	 * @deprecated since 7.7.0
5652
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5653
	 *
5654
	 * @param array $args method call arguments.
5655
	 * @return array an amended XMLRPC server options array.
5656
	 */
5657 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5658
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5659
5660
		if ( ! $this->connection_manager ) {
5661
			$this->connection_manager = new Connection_Manager();
5662
		}
5663
5664
		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...
5665
	}
5666
5667
	/**
5668
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5669
	 *
5670
	 * @deprecated since 7.7.0
5671
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5672
	 *
5673
	 * @param array $options Standard Core options.
5674
	 * @return array Amended options.
5675
	 */
5676 View Code Duplication
	public function xmlrpc_options( $options ) {
5677
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5678
5679
		if ( ! $this->connection_manager ) {
5680
			$this->connection_manager = new Connection_Manager();
5681
		}
5682
5683
		return $this->connection_manager->xmlrpc_options( $options );
5684
	}
5685
5686
	/**
5687
	 * Cleans nonces that were saved when calling ::add_nonce.
5688
	 *
5689
	 * @deprecated since 7.7.0
5690
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5691
	 *
5692
	 * @param bool $all whether to clean even non-expired nonces.
5693
	 */
5694
	public static function clean_nonces( $all = false ) {
5695
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5696
		return self::connection()->clean_nonces( $all );
5697
	}
5698
5699
	/**
5700
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5701
	 * SET: state( $key, $value );
5702
	 * GET: $value = state( $key );
5703
	 *
5704
	 * @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...
5705
	 * @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...
5706
	 * @param bool   $restate private
5707
	 */
5708
	public static function state( $key = null, $value = null, $restate = false ) {
5709
		static $state = array();
5710
		static $path, $domain;
5711
		if ( ! isset( $path ) ) {
5712
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5713
			$admin_url = self::admin_url();
5714
			$bits      = wp_parse_url( $admin_url );
5715
5716
			if ( is_array( $bits ) ) {
5717
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5718
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5719
			} else {
5720
				$path = $domain = null;
5721
			}
5722
		}
5723
5724
		// Extract state from cookies and delete cookies
5725
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5726
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5727
			unset( $_COOKIE['jetpackState'] );
5728
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

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