Completed
Push — improve/rename-anti-spam-in-si... ( e5a567...f08131 )
by
unknown
75:27 queued 67:29
created

Jetpack::allow_wpcom_public_api_domain()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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