Completed
Push — add/local-site-check ( 19e0e4...a3b1d7 )
by Jeremy
91:40 queued 83:45
created

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

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4604
		/**
4605
		 * Filter the URL used as the Stats tracking pixel.
4606
		 *
4607
		 * @since 2.3.2
4608
		 *
4609
		 * @param string $url Base URL used as the Stats tracking pixel.
4610
		 */
4611
		$base_url = apply_filters(
4612
			'jetpack_stats_base_url',
4613
			'https://pixel.wp.com/g.gif'
4614
		);
4615
		$url      = add_query_arg( $args, $base_url );
4616
		return $url;
4617
	}
4618
4619
	/**
4620
	 * Get the role of the current user.
4621
	 *
4622
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4623
	 *
4624
	 * @access public
4625
	 * @static
4626
	 *
4627
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4628
	 */
4629
	public static function translate_current_user_to_role() {
4630
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4631
4632
		$roles = new Roles();
4633
		return $roles->translate_current_user_to_role();
4634
	}
4635
4636
	/**
4637
	 * Get the role of a particular user.
4638
	 *
4639
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4640
	 *
4641
	 * @access public
4642
	 * @static
4643
	 *
4644
	 * @param \WP_User $user User object.
4645
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4646
	 */
4647
	public static function translate_user_to_role( $user ) {
4648
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4649
4650
		$roles = new Roles();
4651
		return $roles->translate_user_to_role( $user );
4652
	}
4653
4654
	/**
4655
	 * Get the minimum capability for a role.
4656
	 *
4657
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4658
	 *
4659
	 * @access public
4660
	 * @static
4661
	 *
4662
	 * @param string $role Role name.
4663
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4664
	 */
4665
	public static function translate_role_to_cap( $role ) {
4666
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4667
4668
		$roles = new Roles();
4669
		return $roles->translate_role_to_cap( $role );
4670
	}
4671
4672
	/**
4673
	 * Sign a user role with the master access token.
4674
	 * If not specified, will default to the current user.
4675
	 *
4676
	 * @deprecated since 7.7
4677
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4678
	 *
4679
	 * @access public
4680
	 * @static
4681
	 *
4682
	 * @param string $role    User role.
4683
	 * @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...
4684
	 * @return string Signed user role.
4685
	 */
4686
	public static function sign_role( $role, $user_id = null ) {
4687
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4688
		return self::connection()->sign_role( $role, $user_id );
4689
	}
4690
4691
	/**
4692
	 * Builds a URL to the Jetpack connection auth page
4693
	 *
4694
	 * @since 3.9.5
4695
	 *
4696
	 * @param bool        $raw If true, URL will not be escaped.
4697
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4698
	 *                              If string, will be a custom redirect.
4699
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4700
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4701
	 *
4702
	 * @return string Connect URL
4703
	 */
4704
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4705
		$site_id    = Jetpack_Options::get_option( 'id' );
4706
		$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...
4707
4708
		if ( $register || ! $blog_token || ! $site_id ) {
4709
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4710
4711
			if ( ! empty( $redirect ) ) {
4712
				$url = add_query_arg(
4713
					'redirect',
4714
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4715
					$url
4716
				);
4717
			}
4718
4719
			if ( is_network_admin() ) {
4720
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4721
			}
4722
4723
			$calypso_env = self::get_calypso_env();
4724
4725
			if ( ! empty( $calypso_env ) ) {
4726
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4727
			}
4728
		} else {
4729
4730
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4731
			// because otherwise this logic can get us in to a loop.
4732
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4733
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4734
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4735
4736
				$response = Client::wpcom_json_api_request_as_blog(
4737
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4738
					'1.1'
4739
				);
4740
4741
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4742
4743
					// Generating a register URL instead to refresh the existing token
4744
					return $this->build_connect_url( $raw, $redirect, $from, true );
4745
				}
4746
			}
4747
4748
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4704 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...
4749
		}
4750
4751
		if ( $from ) {
4752
			$url = add_query_arg( 'from', $from, $url );
4753
		}
4754
4755
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4756
		/**
4757
		 * Filter the URL used when connecting a user to a WordPress.com account.
4758
		 *
4759
		 * @since 8.1.0
4760
		 *
4761
		 * @param string $url Connection URL.
4762
		 * @param bool   $raw If true, URL will not be escaped.
4763
		 */
4764
		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...
4765
	}
4766
4767
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4768
4769
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4770
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4771
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4772
4773
		if ( $iframe ) {
4774
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4775
		}
4776
4777
		$c8n = self::connection();
4778
		$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...
4779
4780
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4781
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4782
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4783
4784
		if ( $iframe ) {
4785
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4786
		}
4787
4788
		return $url;
4789
	}
4790
4791
	/**
4792
	 * Filters the connection URL parameter array.
4793
	 *
4794
	 * @param array $args default URL parameters used by the package.
4795
	 * @return array the modified URL arguments array.
4796
	 */
4797
	public static function filter_connect_request_body( $args ) {
4798
		if (
4799
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4800
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4801
		) {
4802
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4803
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4804
				? $gp_locale->slug
4805
				: '';
4806
		}
4807
4808
		$tracking        = new Tracking();
4809
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4810
4811
		$args = array_merge(
4812
			$args,
4813
			array(
4814
				'_ui' => $tracks_identity['_ui'],
4815
				'_ut' => $tracks_identity['_ut'],
4816
			)
4817
		);
4818
4819
		$calypso_env = self::get_calypso_env();
4820
4821
		if ( ! empty( $calypso_env ) ) {
4822
			$args['calypso_env'] = $calypso_env;
4823
		}
4824
4825
		return $args;
4826
	}
4827
4828
	/**
4829
	 * Filters the URL that will process the connection data. It can be different from the URL
4830
	 * that we send the user to after everything is done.
4831
	 *
4832
	 * @param String $processing_url the default redirect URL used by the package.
4833
	 * @return String the modified URL.
4834
	 */
4835
	public static function filter_connect_processing_url( $processing_url ) {
4836
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4837
		return $processing_url;
4838
	}
4839
4840
	/**
4841
	 * Filters the redirection URL that is used for connect requests. The redirect
4842
	 * URL should return the user back to the Jetpack console.
4843
	 *
4844
	 * @param String $redirect the default redirect URL used by the package.
4845
	 * @return String the modified URL.
4846
	 */
4847
	public static function filter_connect_redirect_url( $redirect ) {
4848
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4849
		$redirect           = $redirect
4850
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4851
			: $jetpack_admin_page;
4852
4853
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4854
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4855
		}
4856
4857
		return $redirect;
4858
	}
4859
4860
	/**
4861
	 * This action fires at the beginning of the Manager::authorize method.
4862
	 */
4863
	public static function authorize_starting() {
4864
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4865
		// Checking if site has been active/connected previously before recording unique connection.
4866
		if ( ! $jetpack_unique_connection ) {
4867
			// jetpack_unique_connection option has never been set.
4868
			$jetpack_unique_connection = array(
4869
				'connected'    => 0,
4870
				'disconnected' => 0,
4871
				'version'      => '3.6.1',
4872
			);
4873
4874
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4875
4876
			// Track unique connection.
4877
			$jetpack = self::init();
4878
4879
			$jetpack->stat( 'connections', 'unique-connection' );
4880
			$jetpack->do_stats( 'server_side' );
4881
		}
4882
4883
		// Increment number of times connected.
4884
		$jetpack_unique_connection['connected'] += 1;
4885
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4886
	}
4887
4888
	/**
4889
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4890
	 * linked.
4891
	 */
4892
	public static function authorize_ending_linked() {
4893
		// Don't activate anything since we are just connecting a user.
4894
		self::state( 'message', 'linked' );
4895
	}
4896
4897
	/**
4898
	 * This action fires at the end of the Manager::authorize method when the master user is
4899
	 * authorized.
4900
	 *
4901
	 * @param array $data The request data.
4902
	 */
4903
	public static function authorize_ending_authorized( $data ) {
4904
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4905
		self::invalidate_onboarding_token();
4906
4907
		// If redirect_uri is SSO, ensure SSO module is enabled.
4908
		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...
4909
4910
		/** This filter is documented in class.jetpack-cli.php */
4911
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4912
4913
		$activate_sso = (
4914
			isset( $redirect_options['action'] ) &&
4915
			'jetpack-sso' === $redirect_options['action'] &&
4916
			$jetpack_start_enable_sso
4917
		);
4918
4919
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4920
4921
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4922
	}
4923
4924
	/**
4925
	 * Get our assumed site creation date.
4926
	 * Calculated based on the earlier date of either:
4927
	 * - Earliest admin user registration date.
4928
	 * - Earliest date of post of any post type.
4929
	 *
4930
	 * @since 7.2.0
4931
	 * @deprecated since 7.8.0
4932
	 *
4933
	 * @return string Assumed site creation date and time.
4934
	 */
4935
	public static function get_assumed_site_creation_date() {
4936
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4937
		return self::connection()->get_assumed_site_creation_date();
4938
	}
4939
4940 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4941
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4942
4943
		if ( $activation_source_name ) {
4944
			$args['_as'] = urlencode( $activation_source_name );
4945
		}
4946
4947
		if ( $activation_source_keyword ) {
4948
			$args['_ak'] = urlencode( $activation_source_keyword );
4949
		}
4950
	}
4951
4952
	function build_reconnect_url( $raw = false ) {
4953
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4954
		return $raw ? $url : esc_url( $url );
4955
	}
4956
4957
	public static function admin_url( $args = null ) {
4958
		$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...
4959
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4960
		return $url;
4961
	}
4962
4963
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4964
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4965
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4966
	}
4967
4968
	function dismiss_jetpack_notice() {
4969
4970
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4971
			return;
4972
		}
4973
4974
		switch ( $_GET['jetpack-notice'] ) {
4975
			case 'dismiss':
4976
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4977
4978
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4979
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4980
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4981
				}
4982
				break;
4983
		}
4984
	}
4985
4986
	public static function sort_modules( $a, $b ) {
4987
		if ( $a['sort'] == $b['sort'] ) {
4988
			return 0;
4989
		}
4990
4991
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4992
	}
4993
4994
	function ajax_recheck_ssl() {
4995
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4996
		$result = self::permit_ssl( true );
4997
		wp_send_json(
4998
			array(
4999
				'enabled' => $result,
5000
				'message' => get_transient( 'jetpack_https_test_message' ),
5001
			)
5002
		);
5003
	}
5004
5005
	/* Client API */
5006
5007
	/**
5008
	 * Returns the requested Jetpack API URL
5009
	 *
5010
	 * @deprecated since 7.7
5011
	 * @return string
5012
	 */
5013
	public static function api_url( $relative_url ) {
5014
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5015
		$connection = self::connection();
5016
		return $connection->api_url( $relative_url );
5017
	}
5018
5019
	/**
5020
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5021
	 *
5022
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5023
	 */
5024
	public static function fix_url_for_bad_hosts( $url ) {
5025
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5026
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5027
	}
5028
5029
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5030
		// Default to a blog token.
5031
		$token_type = 'blog';
5032
5033
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5034
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5035
			if ( ! empty( $_GET['onboarding'] ) ) {
5036
				$jpo = $_GET;
5037
			} else {
5038
				$jpo = json_decode( $request_data, true );
5039
			}
5040
5041
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5042
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5043
5044
			if (
5045
				isset( $jpo_user )
5046
				&& isset( $jpo_token )
5047
				&& is_email( $jpo_user )
5048
				&& ctype_alnum( $jpo_token )
5049
				&& isset( $_GET['rest_route'] )
5050
				&& self::validate_onboarding_token_action(
5051
					$jpo_token,
5052
					$_GET['rest_route']
5053
				)
5054
			) {
5055
				$jp_user = get_user_by( 'email', $jpo_user );
5056
				if ( is_a( $jp_user, 'WP_User' ) ) {
5057
					wp_set_current_user( $jp_user->ID );
5058
					$user_can = is_multisite()
5059
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5060
						: current_user_can( 'manage_options' );
5061
					if ( $user_can ) {
5062
						$token_type              = 'user';
5063
						$token->external_user_id = $jp_user->ID;
5064
					}
5065
				}
5066
			}
5067
5068
			$token_data['type']    = $token_type;
5069
			$token_data['user_id'] = $token->external_user_id;
5070
		}
5071
5072
		return $token_data;
5073
	}
5074
5075
	/**
5076
	 * Create a random secret for validating onboarding payload
5077
	 *
5078
	 * @return string Secret token
5079
	 */
5080
	public static function create_onboarding_token() {
5081
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5082
			$token = wp_generate_password( 32, false );
5083
			Jetpack_Options::update_option( 'onboarding', $token );
5084
		}
5085
5086
		return $token;
5087
	}
5088
5089
	/**
5090
	 * Remove the onboarding token
5091
	 *
5092
	 * @return bool True on success, false on failure
5093
	 */
5094
	public static function invalidate_onboarding_token() {
5095
		return Jetpack_Options::delete_option( 'onboarding' );
5096
	}
5097
5098
	/**
5099
	 * Validate an onboarding token for a specific action
5100
	 *
5101
	 * @return boolean True if token/action pair is accepted, false if not
5102
	 */
5103
	public static function validate_onboarding_token_action( $token, $action ) {
5104
		// Compare tokens, bail if tokens do not match
5105
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5106
			return false;
5107
		}
5108
5109
		// List of valid actions we can take
5110
		$valid_actions = array(
5111
			'/jetpack/v4/settings',
5112
		);
5113
5114
		// Only allow valid actions.
5115
		if ( ! in_array( $action, $valid_actions ) ) {
5116
			return false;
5117
		}
5118
5119
		return true;
5120
	}
5121
5122
	/**
5123
	 * Checks to see if the URL is using SSL to connect with Jetpack
5124
	 *
5125
	 * @since 2.3.3
5126
	 * @return boolean
5127
	 */
5128
	public static function permit_ssl( $force_recheck = false ) {
5129
		// Do some fancy tests to see if ssl is being supported
5130
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5131
			$message = '';
5132
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5133
				$ssl = 0;
5134
			} else {
5135
				switch ( JETPACK_CLIENT__HTTPS ) {
5136
					case 'NEVER':
5137
						$ssl     = 0;
5138
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5139
						break;
5140
					case 'ALWAYS':
5141
					case 'AUTO':
5142
					default:
5143
						$ssl = 1;
5144
						break;
5145
				}
5146
5147
				// If it's not 'NEVER', test to see
5148
				if ( $ssl ) {
5149
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5150
						$ssl     = 0;
5151
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5152
					} else {
5153
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5154
						if ( is_wp_error( $response ) ) {
5155
							$ssl     = 0;
5156
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5157
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5158
							$ssl     = 0;
5159
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5160
						}
5161
					}
5162
				}
5163
			}
5164
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5165
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5166
		}
5167
5168
		return (bool) $ssl;
5169
	}
5170
5171
	/*
5172
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5173
	 */
5174
	public function alert_auto_ssl_fail() {
5175
		if ( ! current_user_can( 'manage_options' ) ) {
5176
			return;
5177
		}
5178
5179
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5180
		?>
5181
5182
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5183
			<div class="jp-banner__content">
5184
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5185
				<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>
5186
				<p>
5187
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5188
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5189
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5190
				</p>
5191
				<p>
5192
					<?php
5193
					printf(
5194
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5195
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5196
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5197
					);
5198
					?>
5199
				</p>
5200
			</div>
5201
		</div>
5202
		<style>
5203
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5204
		</style>
5205
		<script type="text/javascript">
5206
			jQuery( document ).ready( function( $ ) {
5207
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5208
					var $this = $( this );
5209
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5210
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5211
					e.preventDefault();
5212
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5213
					$.post( ajaxurl, data )
5214
					  .done( function( response ) {
5215
						  if ( response.enabled ) {
5216
							  $( '#jetpack-ssl-warning' ).hide();
5217
						  } else {
5218
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5219
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5220
						  }
5221
					  }.bind( $this ) );
5222
				} );
5223
			} );
5224
		</script>
5225
5226
		<?php
5227
	}
5228
5229
	/**
5230
	 * Returns the Jetpack XML-RPC API
5231
	 *
5232
	 * @deprecated 8.0 Use Connection_Manager instead.
5233
	 * @return string
5234
	 */
5235
	public static function xmlrpc_api_url() {
5236
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5237
		return self::connection()->xmlrpc_api_url();
5238
	}
5239
5240
	/**
5241
	 * Returns the connection manager object.
5242
	 *
5243
	 * @return Automattic\Jetpack\Connection\Manager
5244
	 */
5245
	public static function connection() {
5246
		$jetpack = static::init();
5247
5248
		// If the connection manager hasn't been instantiated, do that now.
5249
		if ( ! $jetpack->connection_manager ) {
5250
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5251
		}
5252
5253
		return $jetpack->connection_manager;
5254
	}
5255
5256
	/**
5257
	 * Creates two secret tokens and the end of life timestamp for them.
5258
	 *
5259
	 * Note these tokens are unique per call, NOT static per site for connecting.
5260
	 *
5261
	 * @since 2.6
5262
	 * @param String  $action  The action name.
5263
	 * @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...
5264
	 * @param Integer $exp     Expiration time in seconds.
5265
	 * @return array
5266
	 */
5267
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5268
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5269
	}
5270
5271
	public static function get_secrets( $action, $user_id ) {
5272
		$secrets = self::connection()->get_secrets( $action, $user_id );
5273
5274
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5275
			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...
5276
		}
5277
5278
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5279
			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...
5280
		}
5281
5282
		return $secrets;
5283
	}
5284
5285
	/**
5286
	 * @deprecated 7.5 Use Connection_Manager instead.
5287
	 *
5288
	 * @param $action
5289
	 * @param $user_id
5290
	 */
5291
	public static function delete_secrets( $action, $user_id ) {
5292
		return self::connection()->delete_secrets( $action, $user_id );
5293
	}
5294
5295
	/**
5296
	 * Builds the timeout limit for queries talking with the wpcom servers.
5297
	 *
5298
	 * Based on local php max_execution_time in php.ini
5299
	 *
5300
	 * @since 2.6
5301
	 * @return int
5302
	 * @deprecated
5303
	 **/
5304
	public function get_remote_query_timeout_limit() {
5305
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5306
		return self::get_max_execution_time();
5307
	}
5308
5309
	/**
5310
	 * Builds the timeout limit for queries talking with the wpcom servers.
5311
	 *
5312
	 * Based on local php max_execution_time in php.ini
5313
	 *
5314
	 * @since 5.4
5315
	 * @return int
5316
	 **/
5317
	public static function get_max_execution_time() {
5318
		$timeout = (int) ini_get( 'max_execution_time' );
5319
5320
		// Ensure exec time set in php.ini
5321
		if ( ! $timeout ) {
5322
			$timeout = 30;
5323
		}
5324
		return $timeout;
5325
	}
5326
5327
	/**
5328
	 * Sets a minimum request timeout, and returns the current timeout
5329
	 *
5330
	 * @since 5.4
5331
	 **/
5332 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5333
		$timeout = self::get_max_execution_time();
5334
		if ( $timeout < $min_timeout ) {
5335
			$timeout = $min_timeout;
5336
			set_time_limit( $timeout );
5337
		}
5338
		return $timeout;
5339
	}
5340
5341
	/**
5342
	 * Takes the response from the Jetpack register new site endpoint and
5343
	 * verifies it worked properly.
5344
	 *
5345
	 * @since 2.6
5346
	 * @deprecated since 7.7.0
5347
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5348
	 **/
5349
	public function validate_remote_register_response() {
5350
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5351
	}
5352
5353
	/**
5354
	 * @return bool|WP_Error
5355
	 */
5356
	public static function register() {
5357
		$tracking = new Tracking();
5358
		$tracking->record_user_event( 'jpc_register_begin' );
5359
5360
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5361
5362
		$connection   = self::connection();
5363
		$registration = $connection->register();
5364
5365
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5366
5367
		if ( ! $registration || is_wp_error( $registration ) ) {
5368
			return $registration;
5369
		}
5370
5371
		return true;
5372
	}
5373
5374
	/**
5375
	 * Filters the registration request body to include tracking properties.
5376
	 *
5377
	 * @param array $properties
5378
	 * @return array amended properties.
5379
	 */
5380 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5381
		$tracking        = new Tracking();
5382
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5383
5384
		return array_merge(
5385
			$properties,
5386
			array(
5387
				'_ui' => $tracks_identity['_ui'],
5388
				'_ut' => $tracks_identity['_ut'],
5389
			)
5390
		);
5391
	}
5392
5393
	/**
5394
	 * Filters the token request body to include tracking properties.
5395
	 *
5396
	 * @param array $properties
5397
	 * @return array amended properties.
5398
	 */
5399 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5400
		$tracking        = new Tracking();
5401
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5402
5403
		return array_merge(
5404
			$properties,
5405
			array(
5406
				'_ui' => $tracks_identity['_ui'],
5407
				'_ut' => $tracks_identity['_ut'],
5408
			)
5409
		);
5410
	}
5411
5412
	/**
5413
	 * If the db version is showing something other that what we've got now, bump it to current.
5414
	 *
5415
	 * @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...
5416
	 */
5417
	public static function maybe_set_version_option() {
5418
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5419
		if ( JETPACK__VERSION != $version ) {
5420
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5421
5422
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5423
				/** This action is documented in class.jetpack.php */
5424
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5425
			}
5426
5427
			return true;
5428
		}
5429
		return false;
5430
	}
5431
5432
	/* Client Server API */
5433
5434
	/**
5435
	 * Loads the Jetpack XML-RPC client.
5436
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5437
	 *
5438
	 * @deprecated since 7.7.0
5439
	 */
5440
	public static function load_xml_rpc_client() {
5441
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5442
	}
5443
5444
	/**
5445
	 * Resets the saved authentication state in between testing requests.
5446
	 */
5447
	public function reset_saved_auth_state() {
5448
		$this->rest_authentication_status = null;
5449
5450
		if ( ! $this->connection_manager ) {
5451
			$this->connection_manager = new Connection_Manager();
5452
		}
5453
5454
		$this->connection_manager->reset_saved_auth_state();
5455
	}
5456
5457
	/**
5458
	 * Verifies the signature of the current request.
5459
	 *
5460
	 * @deprecated since 7.7.0
5461
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5462
	 *
5463
	 * @return false|array
5464
	 */
5465
	public function verify_xml_rpc_signature() {
5466
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5467
		return self::connection()->verify_xml_rpc_signature();
5468
	}
5469
5470
	/**
5471
	 * Verifies the signature of the current request.
5472
	 *
5473
	 * This function has side effects and should not be used. Instead,
5474
	 * use the memoized version `->verify_xml_rpc_signature()`.
5475
	 *
5476
	 * @deprecated since 7.7.0
5477
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5478
	 * @internal
5479
	 */
5480
	private function internal_verify_xml_rpc_signature() {
5481
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5482
	}
5483
5484
	/**
5485
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5486
	 *
5487
	 * @deprecated since 7.7.0
5488
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5489
	 *
5490
	 * @param \WP_User|mixed $user     User object if authenticated.
5491
	 * @param string         $username Username.
5492
	 * @param string         $password Password string.
5493
	 * @return \WP_User|mixed Authenticated user or error.
5494
	 */
5495 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5496
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5497
5498
		if ( ! $this->connection_manager ) {
5499
			$this->connection_manager = new Connection_Manager();
5500
		}
5501
5502
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5503
	}
5504
5505
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5506
	// Uses the existing XMLRPC request signing implementation.
5507
	function wp_rest_authenticate( $user ) {
5508
		if ( ! empty( $user ) ) {
5509
			// Another authentication method is in effect.
5510
			return $user;
5511
		}
5512
5513
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5514
			// Nothing to do for this authentication method.
5515
			return null;
5516
		}
5517
5518
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5519
			// Nothing to do for this authentication method.
5520
			return null;
5521
		}
5522
5523
		// Ensure that we always have the request body available.  At this
5524
		// point, the WP REST API code to determine the request body has not
5525
		// run yet.  That code may try to read from 'php://input' later, but
5526
		// this can only be done once per request in PHP versions prior to 5.6.
5527
		// So we will go ahead and perform this read now if needed, and save
5528
		// the request body where both the Jetpack signature verification code
5529
		// and the WP REST API code can see it.
5530
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5531
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5532
		}
5533
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5534
5535
		// Only support specific request parameters that have been tested and
5536
		// are known to work with signature verification.  A different method
5537
		// can be passed to the WP REST API via the '?_method=' parameter if
5538
		// needed.
5539
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5540
			$this->rest_authentication_status = new WP_Error(
5541
				'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...
5542
				__( 'This request method is not supported.', 'jetpack' ),
5543
				array( 'status' => 400 )
5544
			);
5545
			return null;
5546
		}
5547
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5548
			$this->rest_authentication_status = new WP_Error(
5549
				'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...
5550
				__( 'This request method does not support body parameters.', 'jetpack' ),
5551
				array( 'status' => 400 )
5552
			);
5553
			return null;
5554
		}
5555
5556
		if ( ! $this->connection_manager ) {
5557
			$this->connection_manager = new Connection_Manager();
5558
		}
5559
5560
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5561
5562
		if (
5563
			$verified &&
5564
			isset( $verified['type'] ) &&
5565
			'user' === $verified['type'] &&
5566
			! empty( $verified['user_id'] )
5567
		) {
5568
			// Authentication successful.
5569
			$this->rest_authentication_status = true;
5570
			return $verified['user_id'];
5571
		}
5572
5573
		// Something else went wrong.  Probably a signature error.
5574
		$this->rest_authentication_status = new WP_Error(
5575
			'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...
5576
			__( 'The request is not signed correctly.', 'jetpack' ),
5577
			array( 'status' => 400 )
5578
		);
5579
		return null;
5580
	}
5581
5582
	/**
5583
	 * Report authentication status to the WP REST API.
5584
	 *
5585
	 * @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...
5586
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5587
	 */
5588
	public function wp_rest_authentication_errors( $value ) {
5589
		if ( $value !== null ) {
5590
			return $value;
5591
		}
5592
		return $this->rest_authentication_status;
5593
	}
5594
5595
	/**
5596
	 * Add our nonce to this request.
5597
	 *
5598
	 * @deprecated since 7.7.0
5599
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5600
	 *
5601
	 * @param int    $timestamp Timestamp of the request.
5602
	 * @param string $nonce     Nonce string.
5603
	 */
5604 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5605
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5606
5607
		if ( ! $this->connection_manager ) {
5608
			$this->connection_manager = new Connection_Manager();
5609
		}
5610
5611
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5612
	}
5613
5614
	/**
5615
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5616
	 * Capture it here so we can verify the signature later.
5617
	 *
5618
	 * @deprecated since 7.7.0
5619
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5620
	 *
5621
	 * @param array $methods XMLRPC methods.
5622
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5623
	 */
5624 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5625
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5626
5627
		if ( ! $this->connection_manager ) {
5628
			$this->connection_manager = new Connection_Manager();
5629
		}
5630
5631
		return $this->connection_manager->xmlrpc_methods( $methods );
5632
	}
5633
5634
	/**
5635
	 * Register additional public XMLRPC methods.
5636
	 *
5637
	 * @deprecated since 7.7.0
5638
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5639
	 *
5640
	 * @param array $methods Public XMLRPC methods.
5641
	 * @return array Public XMLRPC methods, with the getOptions one.
5642
	 */
5643 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5644
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5645
5646
		if ( ! $this->connection_manager ) {
5647
			$this->connection_manager = new Connection_Manager();
5648
		}
5649
5650
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5651
	}
5652
5653
	/**
5654
	 * Handles a getOptions XMLRPC method call.
5655
	 *
5656
	 * @deprecated since 7.7.0
5657
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5658
	 *
5659
	 * @param array $args method call arguments.
5660
	 * @return array an amended XMLRPC server options array.
5661
	 */
5662 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5663
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5664
5665
		if ( ! $this->connection_manager ) {
5666
			$this->connection_manager = new Connection_Manager();
5667
		}
5668
5669
		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...
5670
	}
5671
5672
	/**
5673
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5674
	 *
5675
	 * @deprecated since 7.7.0
5676
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5677
	 *
5678
	 * @param array $options Standard Core options.
5679
	 * @return array Amended options.
5680
	 */
5681 View Code Duplication
	public function xmlrpc_options( $options ) {
5682
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5683
5684
		if ( ! $this->connection_manager ) {
5685
			$this->connection_manager = new Connection_Manager();
5686
		}
5687
5688
		return $this->connection_manager->xmlrpc_options( $options );
5689
	}
5690
5691
	/**
5692
	 * Cleans nonces that were saved when calling ::add_nonce.
5693
	 *
5694
	 * @deprecated since 7.7.0
5695
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5696
	 *
5697
	 * @param bool $all whether to clean even non-expired nonces.
5698
	 */
5699
	public static function clean_nonces( $all = false ) {
5700
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5701
		return self::connection()->clean_nonces( $all );
5702
	}
5703
5704
	/**
5705
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5706
	 * SET: state( $key, $value );
5707
	 * GET: $value = state( $key );
5708
	 *
5709
	 * @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...
5710
	 * @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...
5711
	 * @param bool   $restate private
5712
	 */
5713
	public static function state( $key = null, $value = null, $restate = false ) {
5714
		static $state = array();
5715
		static $path, $domain;
5716
		if ( ! isset( $path ) ) {
5717
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5718
			$admin_url = self::admin_url();
5719
			$bits      = wp_parse_url( $admin_url );
5720
5721
			if ( is_array( $bits ) ) {
5722
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5723
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5724
			} else {
5725
				$path = $domain = null;
5726
			}
5727
		}
5728
5729
		// Extract state from cookies and delete cookies
5730
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5731
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5732
			unset( $_COOKIE['jetpackState'] );
5733
			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...
5734
				if ( strlen( $v ) ) {
5735
					$state[ $k ] = $v;
5736
				}
5737
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5738
			}
5739
		}
5740
5741
		if ( $restate ) {
5742
			foreach ( $state as $k => $v ) {
5743
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5744
			}
5745
			return;
5746
		}
5747
5748
		// Get a state variable.
5749
		if ( isset( $key ) && ! isset( $value ) ) {
5750
			if ( array_key_exists( $key, $state ) ) {
5751
				return $state[ $key ];
5752
			}
5753
			return null;
5754
		}
5755
5756
		// Set a state variable.
5757
		if ( isset( $key ) && isset( $value ) ) {
5758
			if ( is_array( $value ) && isset( $value[0] ) ) {
5759
				$value = $value[0];
5760
			}
5761
			$state[ $key ] = $value;
5762
			if ( ! headers_sent() ) {
5763
				if ( self::should_set_cookie( $key ) ) {
5764
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5765
				}
5766
			}
5767
		}
5768
	}
5769
5770
	public static function restate() {
5771
		self::state( null, null, true );
5772
	}
5773
5774
	/**
5775
	 * Determines whether the jetpackState[$key] value should be added to the
5776
	 * cookie.
5777
	 *
5778
	 * @param string $key The state key.
5779
	 *
5780
	 * @return boolean Whether the value should be added to the cookie.
5781
	 */
5782
	public static function should_set_cookie( $key ) {
5783
		global $current_screen;
5784
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5785
5786
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5787
			return false;
5788
		}
5789
5790
		return true;
5791
	}
5792
5793
	public static function check_privacy( $file ) {
5794
		static $is_site_publicly_accessible = null;
5795
5796
		if ( is_null( $is_site_publicly_accessible ) ) {
5797
			$is_site_publicly_accessible = false;
5798
5799
			$rpc = new Jetpack_IXR_Client();
5800
5801
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5802
			if ( $success ) {
5803
				$response = $rpc->getResponse();
5804
				if ( $response ) {
5805
					$is_site_publicly_accessible = true;
5806
				}
5807
			}
5808
5809
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5810
		}
5811
5812
		if ( $is_site_publicly_accessible ) {
5813
			return;
5814
		}
5815
5816
		$module_slug = self::get_module_slug( $file );
5817
5818
		$privacy_checks = self::state( 'privacy_checks' );
5819
		if ( ! $privacy_checks ) {
5820
			$privacy_checks = $module_slug;
5821
		} else {
5822
			$privacy_checks .= ",$module_slug";
5823
		}
5824
5825
		self::state( 'privacy_checks', $privacy_checks );
5826
	}
5827
5828
	/**
5829
	 * Helper method for multicall XMLRPC.
5830
	 *
5831
	 * @param ...$args Args for the async_call.
5832
	 */
5833
	public static function xmlrpc_async_call( ...$args ) {
5834
		global $blog_id;
5835
		static $clients = array();
5836
5837
		$client_blog_id = is_multisite() ? $blog_id : 0;
5838
5839
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5840
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5841
			if ( function_exists( 'ignore_user_abort' ) ) {
5842
				ignore_user_abort( true );
5843
			}
5844
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5845
		}
5846
5847
		if ( ! empty( $args[0] ) ) {
5848
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5849
		} elseif ( is_multisite() ) {
5850
			foreach ( $clients as $client_blog_id => $client ) {
5851
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5852
					continue;
5853
				}
5854
5855
				$switch_success = switch_to_blog( $client_blog_id, true );
5856
				if ( ! $switch_success ) {
5857
					continue;
5858
				}
5859
5860
				flush();
5861
				$client->query();
5862
5863
				restore_current_blog();
5864
			}
5865
		} else {
5866
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5867
				flush();
5868
				$clients[0]->query();
5869
			}
5870
		}
5871
	}
5872
5873
	public static function staticize_subdomain( $url ) {
5874
5875
		// Extract hostname from URL
5876
		$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...
5877
5878
		// Explode hostname on '.'
5879
		$exploded_host = explode( '.', $host );
5880
5881
		// Retrieve the name and TLD
5882
		if ( count( $exploded_host ) > 1 ) {
5883
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5884
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5885
			// Rebuild domain excluding subdomains
5886
			$domain = $name . '.' . $tld;
5887
		} else {
5888
			$domain = $host;
5889
		}
5890
		// Array of Automattic domains.
5891
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5892
5893
		// Return $url if not an Automattic domain.
5894
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5895
			return $url;
5896
		}
5897
5898
		if ( is_ssl() ) {
5899
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5900
		}
5901
5902
		srand( crc32( basename( $url ) ) );
5903
		$static_counter = rand( 0, 2 );
5904
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5905
5906
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5907
	}
5908
5909
	/* JSON API Authorization */
5910
5911
	/**
5912
	 * Handles the login action for Authorizing the JSON API
5913
	 */
5914
	function login_form_json_api_authorization() {
5915
		$this->verify_json_api_authorization_request();
5916
5917
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5918
5919
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5920
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5921
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5922
	}
5923
5924
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5925
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5926
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5927
			return $url;
5928
		}
5929
5930
		$parsed_url = wp_parse_url( $url );
5931
		$url        = strtok( $url, '?' );
5932
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5933
		if ( ! empty( $parsed_url['query'] ) ) {
5934
			$url .= "&{$parsed_url['query']}";
5935
		}
5936
5937
		return $url;
5938
	}
5939
5940
	// Make sure the POSTed request is handled by the same action
5941
	function preserve_action_in_login_form_for_json_api_authorization() {
5942
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5943
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5944
	}
5945
5946
	// If someone logs in to approve API access, store the Access Code in usermeta
5947
	function store_json_api_authorization_token( $user_login, $user ) {
5948
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5949
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5950
		$token = wp_generate_password( 32, false );
5951
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5952
	}
5953
5954
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5955
	function allow_wpcom_public_api_domain( $domains ) {
5956
		$domains[] = 'public-api.wordpress.com';
5957
		return $domains;
5958
	}
5959
5960
	static function is_redirect_encoded( $redirect_url ) {
5961
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5962
	}
5963
5964
	// Add all wordpress.com environments to the safe redirect allowed list.
5965
	function allow_wpcom_environments( $domains ) {
5966
		$domains[] = 'wordpress.com';
5967
		$domains[] = 'wpcalypso.wordpress.com';
5968
		$domains[] = 'horizon.wordpress.com';
5969
		$domains[] = 'calypso.localhost';
5970
		return $domains;
5971
	}
5972
5973
	// Add the Access Code details to the public-api.wordpress.com redirect
5974
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5975
		return add_query_arg(
5976
			urlencode_deep(
5977
				array(
5978
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5979
					'jetpack-user-id' => (int) $user->ID,
5980
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5981
				)
5982
			),
5983
			$redirect_to
5984
		);
5985
	}
5986
5987
5988
	/**
5989
	 * Verifies the request by checking the signature
5990
	 *
5991
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5992
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5993
	 *
5994
	 * @param null|array $environment
5995
	 */
5996
	function verify_json_api_authorization_request( $environment = null ) {
5997
		$environment = is_null( $environment )
5998
			? $_REQUEST
5999
			: $environment;
6000
6001
		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...
6002
		$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...
6003
		if ( ! $token || empty( $token->secret ) ) {
6004
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6005
		}
6006
6007
		$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' );
6008
6009
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6010
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6011
			/**
6012
			 * Jetpack authorisation request Error.
6013
			 *
6014
			 * @since 7.5.0
6015
			 */
6016
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6017
			$die_error = sprintf(
6018
				/* translators: %s is a URL */
6019
				__( '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' ),
6020
				Redirect::get_url( 'jetpack-support-double-encoding' )
6021
			);
6022
		}
6023
6024
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6025
6026
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6027
			$signature = $jetpack_signature->sign_request(
6028
				$environment['token'],
6029
				$environment['timestamp'],
6030
				$environment['nonce'],
6031
				'',
6032
				'GET',
6033
				$environment['jetpack_json_api_original_query'],
6034
				null,
6035
				true
6036
			);
6037
		} else {
6038
			$signature = $jetpack_signature->sign_current_request(
6039
				array(
6040
					'body'   => null,
6041
					'method' => 'GET',
6042
				)
6043
			);
6044
		}
6045
6046
		if ( ! $signature ) {
6047
			wp_die( $die_error );
6048
		} elseif ( is_wp_error( $signature ) ) {
6049
			wp_die( $die_error );
6050
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6051
			if ( is_ssl() ) {
6052
				// 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
6053
				$signature = $jetpack_signature->sign_current_request(
6054
					array(
6055
						'scheme' => 'http',
6056
						'body'   => null,
6057
						'method' => 'GET',
6058
					)
6059
				);
6060
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6061
					wp_die( $die_error );
6062
				}
6063
			} else {
6064
				wp_die( $die_error );
6065
			}
6066
		}
6067
6068
		$timestamp = (int) $environment['timestamp'];
6069
		$nonce     = stripslashes( (string) $environment['nonce'] );
6070
6071
		if ( ! $this->connection_manager ) {
6072
			$this->connection_manager = new Connection_Manager();
6073
		}
6074
6075
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6076
			// De-nonce the nonce, at least for 5 minutes.
6077
			// 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)
6078
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6079
			if ( $old_nonce_time < time() - 300 ) {
6080
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6081
			}
6082
		}
6083
6084
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6085
		$data_filters = array(
6086
			'state'        => 'opaque',
6087
			'client_id'    => 'int',
6088
			'client_title' => 'string',
6089
			'client_image' => 'url',
6090
		);
6091
6092
		foreach ( $data_filters as $key => $sanitation ) {
6093
			if ( ! isset( $data->$key ) ) {
6094
				wp_die( $die_error );
6095
			}
6096
6097
			switch ( $sanitation ) {
6098
				case 'int':
6099
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6100
					break;
6101
				case 'opaque':
6102
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6103
					break;
6104
				case 'string':
6105
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6106
					break;
6107
				case 'url':
6108
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6109
					break;
6110
			}
6111
		}
6112
6113
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6114
			wp_die( $die_error );
6115
		}
6116
	}
6117
6118
	function login_message_json_api_authorization( $message ) {
6119
		return '<p class="message">' . sprintf(
6120
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6121
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6122
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6123
	}
6124
6125
	/**
6126
	 * Get $content_width, but with a <s>twist</s> filter.
6127
	 */
6128
	public static function get_content_width() {
6129
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6130
			? $GLOBALS['content_width']
6131
			: false;
6132
		/**
6133
		 * Filter the Content Width value.
6134
		 *
6135
		 * @since 2.2.3
6136
		 *
6137
		 * @param string $content_width Content Width value.
6138
		 */
6139
		return apply_filters( 'jetpack_content_width', $content_width );
6140
	}
6141
6142
	/**
6143
	 * Pings the WordPress.com Mirror Site for the specified options.
6144
	 *
6145
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6146
	 *
6147
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6148
	 */
6149
	public function get_cloud_site_options( $option_names ) {
6150
		$option_names = array_filter( (array) $option_names, 'is_string' );
6151
6152
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6153
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6154
		if ( $xml->isError() ) {
6155
			return array(
6156
				'error_code' => $xml->getErrorCode(),
6157
				'error_msg'  => $xml->getErrorMessage(),
6158
			);
6159
		}
6160
		$cloud_site_options = $xml->getResponse();
6161
6162
		return $cloud_site_options;
6163
	}
6164
6165
	/**
6166
	 * Checks if the site is currently in an identity crisis.
6167
	 *
6168
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6169
	 */
6170
	public static function check_identity_crisis() {
6171
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6172
			return false;
6173
		}
6174
6175
		return Jetpack_Options::get_option( 'sync_error_idc' );
6176
	}
6177
6178
	/**
6179
	 * Checks whether the home and siteurl specifically are allowed.
6180
	 * Written so that we don't have re-check $key and $value params every time
6181
	 * we want to check if this site is allowed, for example in footer.php
6182
	 *
6183
	 * @since  3.8.0
6184
	 * @return bool True = already allowed False = not on the allowed list.
6185
	 */
6186
	public static function is_staging_site() {
6187
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6188
		return ( new Status() )->is_staging_site();
6189
	}
6190
6191
	/**
6192
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6193
	 *
6194
	 * @since 4.4.0
6195
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6196
	 *
6197
	 * @return bool
6198
	 */
6199
	public static function validate_sync_error_idc_option() {
6200
		$is_valid = false;
6201
6202
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6203
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6204
		if ( $sync_error && self::sync_idc_optin() ) {
6205
			$local_options = self::get_sync_error_idc_option();
6206
			// Ensure all values are set.
6207
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6208
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6209
					$is_valid = true;
6210
				}
6211
			}
6212
		}
6213
6214
		/**
6215
		 * Filters whether the sync_error_idc option is valid.
6216
		 *
6217
		 * @since 4.4.0
6218
		 *
6219
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6220
		 */
6221
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6222
6223
		if ( ! $is_valid && $sync_error ) {
6224
			// Since the option exists, and did not validate, delete it
6225
			Jetpack_Options::delete_option( 'sync_error_idc' );
6226
		}
6227
6228
		return $is_valid;
6229
	}
6230
6231
	/**
6232
	 * Normalizes a url by doing three things:
6233
	 *  - Strips protocol
6234
	 *  - Strips www
6235
	 *  - Adds a trailing slash
6236
	 *
6237
	 * @since 4.4.0
6238
	 * @param string $url
6239
	 * @return WP_Error|string
6240
	 */
6241
	public static function normalize_url_protocol_agnostic( $url ) {
6242
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6243 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6244
			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...
6245
		}
6246
6247
		// Strip www and protocols
6248
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6249
		return $url;
6250
	}
6251
6252
	/**
6253
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6254
	 *
6255
	 * @since 4.4.0
6256
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6257
	 *
6258
	 * @param array $response
6259
	 * @return array Array of the local urls, wpcom urls, and error code
6260
	 */
6261
	public static function get_sync_error_idc_option( $response = array() ) {
6262
		// Since the local options will hit the database directly, store the values
6263
		// in a transient to allow for autoloading and caching on subsequent views.
6264
		$local_options = get_transient( 'jetpack_idc_local' );
6265
		if ( false === $local_options ) {
6266
			$local_options = array(
6267
				'home'    => Functions::home_url(),
6268
				'siteurl' => Functions::site_url(),
6269
			);
6270
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6271
		}
6272
6273
		$options = array_merge( $local_options, $response );
6274
6275
		$returned_values = array();
6276
		foreach ( $options as $key => $option ) {
6277
			if ( 'error_code' === $key ) {
6278
				$returned_values[ $key ] = $option;
6279
				continue;
6280
			}
6281
6282
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6283
				continue;
6284
			}
6285
6286
			$returned_values[ $key ] = $normalized_url;
6287
		}
6288
6289
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6290
6291
		return $returned_values;
6292
	}
6293
6294
	/**
6295
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6296
	 * If set to true, the site will be put into staging mode.
6297
	 *
6298
	 * @since 4.3.2
6299
	 * @return bool
6300
	 */
6301
	public static function sync_idc_optin() {
6302
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6303
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6304
		} else {
6305
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6306
		}
6307
6308
		/**
6309
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6310
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6311
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6312
		 *
6313
		 * @since 4.3.2
6314
		 *
6315
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6316
		 */
6317
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6318
	}
6319
6320
	/**
6321
	 * Maybe Use a .min.css stylesheet, maybe not.
6322
	 *
6323
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6324
	 */
6325
	public static function maybe_min_asset( $url, $path, $plugin ) {
6326
		// Short out on things trying to find actual paths.
6327
		if ( ! $path || empty( $plugin ) ) {
6328
			return $url;
6329
		}
6330
6331
		$path = ltrim( $path, '/' );
6332
6333
		// Strip out the abspath.
6334
		$base = dirname( plugin_basename( $plugin ) );
6335
6336
		// Short out on non-Jetpack assets.
6337
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6338
			return $url;
6339
		}
6340
6341
		// File name parsing.
6342
		$file              = "{$base}/{$path}";
6343
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6344
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6345
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6346
		$extension         = array_shift( $file_name_parts_r );
6347
6348
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6349
			// Already pointing at the minified version.
6350
			if ( 'min' === $file_name_parts_r[0] ) {
6351
				return $url;
6352
			}
6353
6354
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6355
			if ( file_exists( $min_full_path ) ) {
6356
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6357
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6358
				if ( 'css' === $extension ) {
6359
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6360
					self::$min_assets[ $key ] = $path;
6361
				}
6362
			}
6363
		}
6364
6365
		return $url;
6366
	}
6367
6368
	/**
6369
	 * If the asset is minified, let's flag .min as the suffix.
6370
	 *
6371
	 * Attached to `style_loader_src` filter.
6372
	 *
6373
	 * @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...
6374
	 * @param string $handle The registered handle of the script in question.
6375
	 * @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...
6376
	 */
6377
	public static function set_suffix_on_min( $src, $handle ) {
6378
		if ( false === strpos( $src, '.min.css' ) ) {
6379
			return $src;
6380
		}
6381
6382
		if ( ! empty( self::$min_assets ) ) {
6383
			foreach ( self::$min_assets as $file => $path ) {
6384
				if ( false !== strpos( $src, $file ) ) {
6385
					wp_style_add_data( $handle, 'suffix', '.min' );
6386
					return $src;
6387
				}
6388
			}
6389
		}
6390
6391
		return $src;
6392
	}
6393
6394
	/**
6395
	 * Maybe inlines a stylesheet.
6396
	 *
6397
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6398
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6399
	 *
6400
	 * Attached to `style_loader_tag` filter.
6401
	 *
6402
	 * @param string $tag The tag that would link to the external asset.
6403
	 * @param string $handle The registered handle of the script in question.
6404
	 *
6405
	 * @return string
6406
	 */
6407
	public static function maybe_inline_style( $tag, $handle ) {
6408
		global $wp_styles;
6409
		$item = $wp_styles->registered[ $handle ];
6410
6411
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6412
			return $tag;
6413
		}
6414
6415
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6416
			$href = $matches[1];
6417
			// Strip off query string
6418
			if ( $pos = strpos( $href, '?' ) ) {
6419
				$href = substr( $href, 0, $pos );
6420
			}
6421
			// Strip off fragment
6422
			if ( $pos = strpos( $href, '#' ) ) {
6423
				$href = substr( $href, 0, $pos );
6424
			}
6425
		} else {
6426
			return $tag;
6427
		}
6428
6429
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6430
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6431
			return $tag;
6432
		}
6433
6434
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6435
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6436
			// And this isn't the pass that actually deals with the RTL version...
6437
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6438
				// Short out, as the RTL version will deal with it in a moment.
6439
				return $tag;
6440
			}
6441
		}
6442
6443
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6444
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6445
		if ( $css ) {
6446
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6447
			if ( empty( $item->extra['after'] ) ) {
6448
				wp_add_inline_style( $handle, $css );
6449
			} else {
6450
				array_unshift( $item->extra['after'], $css );
6451
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6452
			}
6453
		}
6454
6455
		return $tag;
6456
	}
6457
6458
	/**
6459
	 * Loads a view file from the views
6460
	 *
6461
	 * Data passed in with the $data parameter will be available in the
6462
	 * template file as $data['value']
6463
	 *
6464
	 * @param string $template - Template file to load
6465
	 * @param array  $data - Any data to pass along to the template
6466
	 * @return boolean - If template file was found
6467
	 **/
6468
	public function load_view( $template, $data = array() ) {
6469
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6470
6471
		if ( file_exists( $views_dir . $template ) ) {
6472
			require_once $views_dir . $template;
6473
			return true;
6474
		}
6475
6476
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6477
		return false;
6478
	}
6479
6480
	/**
6481
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6482
	 *
6483
	 * @todo Convert these to use apply_filters_deprecated and do_action_deprecated and remove custom code.
6484
	 */
6485
	public function deprecated_hooks() {
6486
		global $wp_filter;
6487
6488
		/*
6489
		 * Format:
6490
		 * deprecated_filter_name => replacement_name
6491
		 *
6492
		 * If there is no replacement, use null for replacement_name
6493
		 */
6494
		$deprecated_list = array(
6495
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6496
			'wpl_sharing_2014_1'                           => null,
6497
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6498
			'jetpack_identity_crisis_options_to_check'     => null,
6499
			'update_option_jetpack_single_user_site'       => null,
6500
			'audio_player_default_colors'                  => null,
6501
			'add_option_jetpack_featured_images_enabled'   => null,
6502
			'add_option_jetpack_update_details'            => null,
6503
			'add_option_jetpack_updates'                   => null,
6504
			'add_option_jetpack_network_name'              => null,
6505
			'add_option_jetpack_network_allow_new_registrations' => null,
6506
			'add_option_jetpack_network_add_new_users'     => null,
6507
			'add_option_jetpack_network_site_upload_space' => null,
6508
			'add_option_jetpack_network_upload_file_types' => null,
6509
			'add_option_jetpack_network_enable_administration_menus' => null,
6510
			'add_option_jetpack_is_multi_site'             => null,
6511
			'add_option_jetpack_is_main_network'           => null,
6512
			'add_option_jetpack_main_network_site'         => null,
6513
			'jetpack_sync_all_registered_options'          => null,
6514
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6515
			'jetpack_is_post_mailable'                     => null,
6516
			'jetpack_seo_site_host'                        => null,
6517
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6518
			'jetpack_holiday_snow_option_name'             => null,
6519
			'jetpack_holiday_chance_of_snow'               => null,
6520
			'jetpack_holiday_snow_js_url'                  => null,
6521
			'jetpack_is_holiday_snow_season'               => null,
6522
			'jetpack_holiday_snow_option_updated'          => null,
6523
			'jetpack_holiday_snowing'                      => null,
6524
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6525
			'jetpack_cache_plans'                          => null,
6526
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6527
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6528
			'jetpack_enable_site_verification'             => null,
6529
			// Removed in Jetpack 7.3.0
6530
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6531
			// Removed in Jetpack 7.9.0
6532
			'jetpack_pwa_manifest'                         => null,
6533
			'jetpack_pwa_background_color'                 => null,
6534
			// Removed in Jetpack 8.3.0.
6535
			'jetpack_check_mobile'                         => null,
6536
			'jetpack_mobile_stylesheet'                    => null,
6537
			'jetpack_mobile_template'                      => null,
6538
			'mobile_reject_mobile'                         => null,
6539
			'mobile_force_mobile'                          => null,
6540
			'mobile_app_promo_download'                    => null,
6541
			'mobile_setup'                                 => null,
6542
			'jetpack_mobile_footer_before'                 => null,
6543
			'wp_mobile_theme_footer'                       => null,
6544
			'minileven_credits'                            => null,
6545
			'jetpack_mobile_header_before'                 => null,
6546
			'jetpack_mobile_header_after'                  => null,
6547
			'jetpack_mobile_theme_menu'                    => null,
6548
			'minileven_show_featured_images'               => null,
6549
			'minileven_attachment_size'                    => null,
6550
		);
6551
6552
		// This is a silly loop depth. Better way?
6553
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6554
			if ( has_action( $hook ) ) {
6555
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6556
					foreach ( $values as $hooked ) {
6557
						if ( is_callable( $hooked['function'] ) ) {
6558
							$function_name = $hooked['function'];
6559
						} else {
6560
							$function_name = 'an anonymous function';
6561
						}
6562
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6563
					}
6564
				}
6565
			}
6566
		}
6567
6568
		$filter_deprecated_list = array(
6569
			'can_display_jetpack_manage_notice' => array(
6570
				'replacement' => null,
6571
				'version'     => 'jetpack-7.3.0',
6572
			),
6573
			'atd_http_post_timeout'             => array(
6574
				'replacement' => null,
6575
				'version'     => 'jetpack-7.3.0',
6576
			),
6577
			'atd_service_domain'                => array(
6578
				'replacement' => null,
6579
				'version'     => 'jetpack-7.3.0',
6580
			),
6581
			'atd_load_scripts'                  => array(
6582
				'replacement' => null,
6583
				'version'     => 'jetpack-7.3.0',
6584
			),
6585
		);
6586
6587
		foreach ( $filter_deprecated_list as $tag => $args ) {
6588
			if ( has_filter( $tag ) ) {
6589
				apply_filters_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6590
			}
6591
		}
6592
6593
		$action_deprecated_list = array(
6594
			'atd_http_post_error' => array(
6595
				'replacement' => null,
6596
				'version'     => 'jetpack-7.3.0',
6597
			),
6598
		);
6599
6600
		foreach ( $action_deprecated_list as $tag => $args ) {
6601
			if ( has_action( $tag ) ) {
6602
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6603
			}
6604
		}
6605
	}
6606
6607
	/**
6608
	 * Converts any url in a stylesheet, to the correct absolute url.
6609
	 *
6610
	 * Considerations:
6611
	 *  - Normal, relative URLs     `feh.png`
6612
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6613
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6614
	 *  - Absolute URLs             `http://domain.com/feh.png`
6615
	 *  - Domain root relative URLs `/feh.png`
6616
	 *
6617
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6618
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6619
	 *
6620
	 * @return mixed|string
6621
	 */
6622
	public static function absolutize_css_urls( $css, $css_file_url ) {
6623
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6624
		$css_dir = dirname( $css_file_url );
6625
		$p       = wp_parse_url( $css_dir );
6626
		$domain  = sprintf(
6627
			'%1$s//%2$s%3$s%4$s',
6628
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6629
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6630
			$p['host'],
6631
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6632
		);
6633
6634
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6635
			$find = $replace = array();
6636
			foreach ( $matches as $match ) {
6637
				$url = trim( $match['path'], "'\" \t" );
6638
6639
				// If this is a data url, we don't want to mess with it.
6640
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6641
					continue;
6642
				}
6643
6644
				// If this is an absolute or protocol-agnostic url,
6645
				// we don't want to mess with it.
6646
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6647
					continue;
6648
				}
6649
6650
				switch ( substr( $url, 0, 1 ) ) {
6651
					case '/':
6652
						$absolute = $domain . $url;
6653
						break;
6654
					default:
6655
						$absolute = $css_dir . '/' . $url;
6656
				}
6657
6658
				$find[]    = $match[0];
6659
				$replace[] = sprintf( 'url("%s")', $absolute );
6660
			}
6661
			$css = str_replace( $find, $replace, $css );
6662
		}
6663
6664
		return $css;
6665
	}
6666
6667
	/**
6668
	 * This methods removes all of the registered css files on the front end
6669
	 * from Jetpack in favor of using a single file. In effect "imploding"
6670
	 * all the files into one file.
6671
	 *
6672
	 * Pros:
6673
	 * - Uses only ONE css asset connection instead of 15
6674
	 * - Saves a minimum of 56k
6675
	 * - Reduces server load
6676
	 * - Reduces time to first painted byte
6677
	 *
6678
	 * Cons:
6679
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6680
	 *      should not cause any issues with themes.
6681
	 * - Plugins/themes dequeuing styles no longer do anything. See
6682
	 *      jetpack_implode_frontend_css filter for a workaround
6683
	 *
6684
	 * For some situations developers may wish to disable css imploding and
6685
	 * instead operate in legacy mode where each file loads seperately and
6686
	 * can be edited individually or dequeued. This can be accomplished with
6687
	 * the following line:
6688
	 *
6689
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6690
	 *
6691
	 * @since 3.2
6692
	 **/
6693
	public function implode_frontend_css( $travis_test = false ) {
6694
		$do_implode = true;
6695
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6696
			$do_implode = false;
6697
		}
6698
6699
		// Do not implode CSS when the page loads via the AMP plugin.
6700
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6701
			$do_implode = false;
6702
		}
6703
6704
		/**
6705
		 * Allow CSS to be concatenated into a single jetpack.css file.
6706
		 *
6707
		 * @since 3.2.0
6708
		 *
6709
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6710
		 */
6711
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6712
6713
		// Do not use the imploded file when default behavior was altered through the filter
6714
		if ( ! $do_implode ) {
6715
			return;
6716
		}
6717
6718
		// We do not want to use the imploded file in dev mode, or if not connected
6719
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6720
			if ( ! $travis_test ) {
6721
				return;
6722
			}
6723
		}
6724
6725
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6726
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6727
			return;
6728
		}
6729
6730
		/*
6731
		 * Now we assume Jetpack is connected and able to serve the single
6732
		 * file.
6733
		 *
6734
		 * In the future there will be a check here to serve the file locally
6735
		 * or potentially from the Jetpack CDN
6736
		 *
6737
		 * For now:
6738
		 * - Enqueue a single imploded css file
6739
		 * - Zero out the style_loader_tag for the bundled ones
6740
		 * - Be happy, drink scotch
6741
		 */
6742
6743
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6744
6745
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6746
6747
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6748
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6749
	}
6750
6751
	function concat_remove_style_loader_tag( $tag, $handle ) {
6752
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6753
			$tag = '';
6754
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6755
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6756
			}
6757
		}
6758
6759
		return $tag;
6760
	}
6761
6762
	/**
6763
	 * @deprecated
6764
	 * @see Automattic\Jetpack\Assets\add_aync_script
6765
	 */
6766
	public function script_add_async( $tag, $handle, $src ) {
6767
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6768
	}
6769
6770
	/*
6771
	 * Check the heartbeat data
6772
	 *
6773
	 * Organizes the heartbeat data by severity.  For example, if the site
6774
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6775
	 *
6776
	 * Data will be added to "caution" array, if it either:
6777
	 *  - Out of date Jetpack version
6778
	 *  - Out of date WP version
6779
	 *  - Out of date PHP version
6780
	 *
6781
	 * $return array $filtered_data
6782
	 */
6783
	public static function jetpack_check_heartbeat_data() {
6784
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6785
6786
		$good    = array();
6787
		$caution = array();
6788
		$bad     = array();
6789
6790
		foreach ( $raw_data as $stat => $value ) {
6791
6792
			// Check jetpack version
6793
			if ( 'version' == $stat ) {
6794
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6795
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6796
					continue;
6797
				}
6798
			}
6799
6800
			// Check WP version
6801
			if ( 'wp-version' == $stat ) {
6802
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6803
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6804
					continue;
6805
				}
6806
			}
6807
6808
			// Check PHP version
6809
			if ( 'php-version' == $stat ) {
6810
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6811
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6812
					continue;
6813
				}
6814
			}
6815
6816
			// Check ID crisis
6817
			if ( 'identitycrisis' == $stat ) {
6818
				if ( 'yes' == $value ) {
6819
					$bad[ $stat ] = $value;
6820
					continue;
6821
				}
6822
			}
6823
6824
			// The rest are good :)
6825
			$good[ $stat ] = $value;
6826
		}
6827
6828
		$filtered_data = array(
6829
			'good'    => $good,
6830
			'caution' => $caution,
6831
			'bad'     => $bad,
6832
		);
6833
6834
		return $filtered_data;
6835
	}
6836
6837
6838
	/*
6839
	 * This method is used to organize all options that can be reset
6840
	 * without disconnecting Jetpack.
6841
	 *
6842
	 * It is used in class.jetpack-cli.php to reset options
6843
	 *
6844
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6845
	 *
6846
	 * @return array of options to delete.
6847
	 */
6848
	public static function get_jetpack_options_for_reset() {
6849
		return Jetpack_Options::get_options_for_reset();
6850
	}
6851
6852
	/*
6853
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6854
	 * so we can bring them directly to their site in calypso.
6855
	 *
6856
	 * @param string | url
6857
	 * @return string | url without the guff
6858
	 */
6859 View Code Duplication
	public static function build_raw_urls( $url ) {
6860
		$strip_http = '/.*?:\/\//i';
6861
		$url        = preg_replace( $strip_http, '', $url );
6862
		$url        = str_replace( '/', '::', $url );
6863
		return $url;
6864
	}
6865
6866
	/**
6867
	 * Stores and prints out domains to prefetch for page speed optimization.
6868
	 *
6869
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6870
	 *
6871
	 * @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...
6872
	 */
6873
	public static function dns_prefetch( $urls = null ) {
6874
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6875
		if ( $urls ) {
6876
			Assets::add_resource_hint( $urls );
6877
		}
6878
	}
6879
6880
	public function wp_dashboard_setup() {
6881
		if ( self::is_active() ) {
6882
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6883
		}
6884
6885
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6886
			$jetpack_logo = new Jetpack_Logo();
6887
			$widget_title = sprintf(
6888
				wp_kses(
6889
					/* translators: Placeholder is a Jetpack logo. */
6890
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6891
					array( 'span' => array() )
6892
				),
6893
				$jetpack_logo->get_jp_emblem( true )
6894
			);
6895
6896
			wp_add_dashboard_widget(
6897
				'jetpack_summary_widget',
6898
				$widget_title,
6899
				array( __CLASS__, 'dashboard_widget' )
6900
			);
6901
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6902
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6903
6904
			// If we're inactive and not in offline mode, sort our box to the top.
6905
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6906
				global $wp_meta_boxes;
6907
6908
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6909
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6910
6911
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6912
			}
6913
		}
6914
	}
6915
6916
	/**
6917
	 * @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...
6918
	 * @return mixed
6919
	 */
6920
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6921
		if ( ! is_array( $sorted ) ) {
6922
			return $sorted;
6923
		}
6924
6925
		foreach ( $sorted as $box_context => $ids ) {
6926
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6927
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6928
				continue;
6929
			}
6930
6931
			$ids_array = explode( ',', $ids );
6932
			$key       = array_search( 'dashboard_stats', $ids_array );
6933
6934
			if ( false !== $key ) {
6935
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6936
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6937
				$sorted[ $box_context ] = implode( ',', $ids_array );
6938
				// We've found it, stop searching, and just return.
6939
				break;
6940
			}
6941
		}
6942
6943
		return $sorted;
6944
	}
6945
6946
	public static function dashboard_widget() {
6947
		/**
6948
		 * Fires when the dashboard is loaded.
6949
		 *
6950
		 * @since 3.4.0
6951
		 */
6952
		do_action( 'jetpack_dashboard_widget' );
6953
	}
6954
6955
	public static function dashboard_widget_footer() {
6956
		?>
6957
		<footer>
6958
6959
		<div class="protect">
6960
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6961
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6962
				<p class="blocked-count">
6963
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6964
				</p>
6965
				<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>
6966
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
6967
				<a href="
6968
				<?php
6969
				echo esc_url(
6970
					wp_nonce_url(
6971
						self::admin_url(
6972
							array(
6973
								'action' => 'activate',
6974
								'module' => 'protect',
6975
							)
6976
						),
6977
						'jetpack_activate-protect'
6978
					)
6979
				);
6980
				?>
6981
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6982
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6983
				</a>
6984
			<?php else : ?>
6985
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6986
			<?php endif; ?>
6987
		</div>
6988
6989
		<div class="akismet">
6990
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6991
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6992
				<p class="blocked-count">
6993
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6994
				</p>
6995
				<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>
6996
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6997
				<a href="
6998
				<?php
6999
				echo esc_url(
7000
					wp_nonce_url(
7001
						add_query_arg(
7002
							array(
7003
								'action' => 'activate',
7004
								'plugin' => 'akismet/akismet.php',
7005
							),
7006
							admin_url( 'plugins.php' )
7007
						),
7008
						'activate-plugin_akismet/akismet.php'
7009
					)
7010
				);
7011
				?>
7012
							" class="button button-jetpack">
7013
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7014
				</a>
7015
			<?php else : ?>
7016
				<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>
7017
			<?php endif; ?>
7018
		</div>
7019
7020
		</footer>
7021
		<?php
7022
	}
7023
7024
	/*
7025
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7026
	 */
7027
	function jetpack_icon_user_connected( $columns ) {
7028
		$columns['user_jetpack'] = '';
7029
		return $columns;
7030
	}
7031
7032
	/*
7033
	 * Show Jetpack icon if the user is linked.
7034
	 */
7035
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7036
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7037
			$jetpack_logo = new Jetpack_Logo();
7038
			$emblem_html  = sprintf(
7039
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7040
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7041
				$jetpack_logo->get_jp_emblem()
7042
			);
7043
			return $emblem_html;
7044
		}
7045
7046
		return $val;
7047
	}
7048
7049
	/*
7050
	 * Style the Jetpack user column
7051
	 */
7052
	function jetpack_user_col_style() {
7053
		global $current_screen;
7054
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7055
			?>
7056
			<style>
7057
				.fixed .column-user_jetpack {
7058
					width: 21px;
7059
				}
7060
				.jp-emblem-user-admin svg {
7061
					width: 20px;
7062
					height: 20px;
7063
				}
7064
				.jp-emblem-user-admin path {
7065
					fill: #00BE28;
7066
				}
7067
			</style>
7068
			<?php
7069
		}
7070
	}
7071
7072
	/**
7073
	 * Checks if Akismet is active and working.
7074
	 *
7075
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7076
	 * that implied usage of methods present since more recent version.
7077
	 * See https://github.com/Automattic/jetpack/pull/9585
7078
	 *
7079
	 * @since  5.1.0
7080
	 *
7081
	 * @return bool True = Akismet available. False = Aksimet not available.
7082
	 */
7083
	public static function is_akismet_active() {
7084
		static $status = null;
7085
7086
		if ( ! is_null( $status ) ) {
7087
			return $status;
7088
		}
7089
7090
		// Check if a modern version of Akismet is active.
7091
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7092
			$status = false;
7093
			return $status;
7094
		}
7095
7096
		// Make sure there is a key known to Akismet at all before verifying key.
7097
		$akismet_key = Akismet::get_api_key();
7098
		if ( ! $akismet_key ) {
7099
			$status = false;
7100
			return $status;
7101
		}
7102
7103
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7104
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7105
7106
		// 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.
7107
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7108
		// We cache the result of the Akismet key verification for ten minutes.
7109
		if ( ! $akismet_key_state || $recheck ) {
7110
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7111
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7112
		}
7113
7114
		$status = 'valid' === $akismet_key_state;
7115
7116
		return $status;
7117
	}
7118
7119
	/**
7120
	 * @deprecated
7121
	 *
7122
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7123
	 */
7124
	public static function is_function_in_backtrace() {
7125
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7126
	}
7127
7128
	/**
7129
	 * Given a minified path, and a non-minified path, will return
7130
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7131
	 *
7132
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7133
	 * root Jetpack directory.
7134
	 *
7135
	 * @since 5.6.0
7136
	 *
7137
	 * @param string $min_path
7138
	 * @param string $non_min_path
7139
	 * @return string The URL to the file
7140
	 */
7141
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7142
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7143
	}
7144
7145
	/**
7146
	 * Checks for whether Jetpack Backup is enabled.
7147
	 * Will return true if the state of Backup is anything except "unavailable".
7148
	 *
7149
	 * @return bool|int|mixed
7150
	 */
7151
	public static function is_rewind_enabled() {
7152
		if ( ! self::is_active() ) {
7153
			return false;
7154
		}
7155
7156
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7157
		if ( false === $rewind_enabled ) {
7158
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7159
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7160
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7161
				&& ! empty( $rewind_data['state'] )
7162
				&& 'active' === $rewind_data['state'] )
7163
				? 1
7164
				: 0;
7165
7166
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7167
		}
7168
		return $rewind_enabled;
7169
	}
7170
7171
	/**
7172
	 * Return Calypso environment value; used for developing Jetpack and pairing
7173
	 * it with different Calypso enrionments, such as localhost.
7174
	 *
7175
	 * @since 7.4.0
7176
	 *
7177
	 * @return string Calypso environment
7178
	 */
7179
	public static function get_calypso_env() {
7180
		if ( isset( $_GET['calypso_env'] ) ) {
7181
			return sanitize_key( $_GET['calypso_env'] );
7182
		}
7183
7184
		if ( getenv( 'CALYPSO_ENV' ) ) {
7185
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7186
		}
7187
7188
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7189
			return sanitize_key( CALYPSO_ENV );
7190
		}
7191
7192
		return '';
7193
	}
7194
7195
	/**
7196
	 * Returns the hostname with protocol for Calypso.
7197
	 * Used for developing Jetpack with Calypso.
7198
	 *
7199
	 * @since 8.4.0
7200
	 *
7201
	 * @return string Calypso host.
7202
	 */
7203
	public static function get_calypso_host() {
7204
		$calypso_env = self::get_calypso_env();
7205
		switch ( $calypso_env ) {
7206
			case 'development':
7207
				return 'http://calypso.localhost:3000/';
7208
			case 'wpcalypso':
7209
				return 'https://wpcalypso.wordpress.com/';
7210
			case 'horizon':
7211
				return 'https://horizon.wordpress.com/';
7212
			default:
7213
				return 'https://wordpress.com/';
7214
		}
7215
	}
7216
7217
	/**
7218
	 * Checks whether or not TOS has been agreed upon.
7219
	 * Will return true if a user has clicked to register, or is already connected.
7220
	 */
7221
	public static function jetpack_tos_agreed() {
7222
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7223
7224
		$terms_of_service = new Terms_Of_Service();
7225
		return $terms_of_service->has_agreed();
7226
7227
	}
7228
7229
	/**
7230
	 * Handles activating default modules as well general cleanup for the new connection.
7231
	 *
7232
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7233
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7234
	 * @param boolean $send_state_messages          Whether to send state messages.
7235
	 * @return void
7236
	 */
7237
	public static function handle_post_authorization_actions(
7238
		$activate_sso = false,
7239
		$redirect_on_activation_error = false,
7240
		$send_state_messages = true
7241
	) {
7242
		$other_modules = $activate_sso
7243
			? array( 'sso' )
7244
			: array();
7245
7246
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7247
			self::delete_active_modules();
7248
7249
			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...
7250
		} else {
7251
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7252
		}
7253
7254
		// Since this is a fresh connection, be sure to clear out IDC options
7255
		Jetpack_IDC::clear_all_idc_options();
7256
7257
		if ( $send_state_messages ) {
7258
			self::state( 'message', 'authorized' );
7259
		}
7260
	}
7261
7262
	/**
7263
	 * Returns a boolean for whether backups UI should be displayed or not.
7264
	 *
7265
	 * @return bool Should backups UI be displayed?
7266
	 */
7267
	public static function show_backups_ui() {
7268
		/**
7269
		 * Whether UI for backups should be displayed.
7270
		 *
7271
		 * @since 6.5.0
7272
		 *
7273
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7274
		 */
7275
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7276
	}
7277
7278
	/*
7279
	 * Deprecated manage functions
7280
	 */
7281
	function prepare_manage_jetpack_notice() {
7282
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7283
	}
7284
	function manage_activate_screen() {
7285
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7286
	}
7287
	function admin_jetpack_manage_notice() {
7288
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7289
	}
7290
	function opt_out_jetpack_manage_url() {
7291
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7292
	}
7293
	function opt_in_jetpack_manage_url() {
7294
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7295
	}
7296
	function opt_in_jetpack_manage_notice() {
7297
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7298
	}
7299
	function can_display_jetpack_manage_notice() {
7300
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7301
	}
7302
7303
	/**
7304
	 * Clean leftoveruser meta.
7305
	 *
7306
	 * Delete Jetpack-related user meta when it is no longer needed.
7307
	 *
7308
	 * @since 7.3.0
7309
	 *
7310
	 * @param int $user_id User ID being updated.
7311
	 */
7312
	public static function user_meta_cleanup( $user_id ) {
7313
		$meta_keys = array(
7314
			// AtD removed from Jetpack 7.3
7315
			'AtD_options',
7316
			'AtD_check_when',
7317
			'AtD_guess_lang',
7318
			'AtD_ignored_phrases',
7319
		);
7320
7321
		foreach ( $meta_keys as $meta_key ) {
7322
			if ( get_user_meta( $user_id, $meta_key ) ) {
7323
				delete_user_meta( $user_id, $meta_key );
7324
			}
7325
		}
7326
	}
7327
7328
	/**
7329
	 * Checks if a Jetpack site is both active and not in offline mode.
7330
	 *
7331
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7332
	 *
7333
	 * @deprecated 8.8.0
7334
	 *
7335
	 * @return bool True if Jetpack is active and not in offline mode.
7336
	 */
7337
	public static function is_active_and_not_development_mode() {
7338
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7339
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7340
			return false;
7341
		}
7342
		return true;
7343
	}
7344
7345
	/**
7346
	 * Checks if a Jetpack site is both active and not in offline mode.
7347
	 *
7348
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7349
	 *
7350
	 * @since 8.8.0
7351
	 *
7352
	 * @return bool True if Jetpack is active and not in offline mode.
7353
	 */
7354
	public static function is_active_and_not_offline_mode() {
7355
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7356
			return false;
7357
		}
7358
		return true;
7359
	}
7360
7361
	/**
7362
	 * Returns the list of products that we have available for purchase.
7363
	 */
7364
	public static function get_products_for_purchase() {
7365
		$products = array();
7366
		if ( ! is_multisite() ) {
7367
			$products[] = array(
7368
				'key'               => 'backup',
7369
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7370
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7371
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7372
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7373
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7374
				'options'           => array(
7375
					array(
7376
						'type'        => 'daily',
7377
						'slug'        => 'jetpack-backup-daily',
7378
						'key'         => 'jetpack_backup_daily',
7379
						'name'        => __( 'Daily Backups', 'jetpack' ),
7380
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7381
					),
7382
					array(
7383
						'type'        => 'realtime',
7384
						'slug'        => 'jetpack-backup-realtime',
7385
						'key'         => 'jetpack_backup_realtime',
7386
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7387
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7388
					),
7389
				),
7390
				'default_option'    => 'realtime',
7391
				'show_promotion'    => true,
7392
				'discount_percent'  => 70,
7393
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7394
			);
7395
7396
			$products[] = array(
7397
				'key'               => 'scan',
7398
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7399
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7400
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7401
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7402
				'show_promotion'    => true,
7403
				'discount_percent'  => 30,
7404
				'options'           => array(
7405
					array(
7406
						'type'      => 'scan',
7407
						'slug'      => 'jetpack-scan',
7408
						'key'       => 'jetpack_scan',
7409
						'name'      => __( 'Daily Scan', 'jetpack' ),
7410
					),
7411
				),
7412
				'default_option'    => 'scan',
7413
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7414
			);
7415
		}
7416
7417
		$products[] = array(
7418
			'key'               => 'search',
7419
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7420
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7421
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7422
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7423
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7424
			'options'           => array(
7425
				array(
7426
					'type'      => 'search',
7427
					'slug'      => 'jetpack-search',
7428
					'key'       => 'jetpack_search',
7429
					'name'      => __( 'Search', 'jetpack' ),
7430
				),
7431
			),
7432
			'tears'             => array(),
7433
			'default_option'    => 'search',
7434
			'show_promotion'    => false,
7435
			'included_in_plans' => array( 'search-plan' ),
7436
		);
7437
7438
		$products[] = array(
7439
			'key'               => 'anti-spam',
7440
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7441
			'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' ),
7442
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7443
			'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' ),
7444
			'options'           => array(
7445
				array(
7446
					'type'      => 'anti-spam',
7447
					'slug'      => 'jetpack-anti-spam',
7448
					'key'       => 'jetpack_anti_spam',
7449
					'name'      => __( 'Anti-Spam', 'jetpack' ),
7450
				),
7451
			),
7452
			'default_option'    => 'anti-spam',
7453
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7454
		);
7455
7456
		return $products;
7457
	}
7458
}
7459