Completed
Push — update/wp-55-autoupdate ( edccb1...32ccef )
by
unknown
09:55
created

Jetpack::get_option()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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