Completed
Push — branch-8.8 ( bc69c8...0e168b )
by Jeremy
66:56 queued 59:01
created

Jetpack::user_role_change()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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