Completed
Push — fix/local_script_translation_p... ( f509ec...67e374 )
by
unknown
18:29 queued 11:00
created

Jetpack::dns_prefetch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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