Completed
Push — add/e2e-connection-purchase-fl... ( d02cce...68beb5 )
by Yaroslav
14:07 queued 04:35
created

Jetpack::wp_rest_authenticate()   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\Connection\Rest_Authentication as Connection_Rest_Authentication;
10
use Automattic\Jetpack\Constants;
11
use Automattic\Jetpack\Partner;
12
use Automattic\Jetpack\Roles;
13
use Automattic\Jetpack\Status;
14
use Automattic\Jetpack\Sync\Functions;
15
use Automattic\Jetpack\Sync\Health;
16
use Automattic\Jetpack\Sync\Sender;
17
use Automattic\Jetpack\Sync\Users;
18
use Automattic\Jetpack\Terms_Of_Service;
19
use Automattic\Jetpack\Tracking;
20
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
21
use Automattic\Jetpack\Redirect;
22
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
23
24
/*
25
Options:
26
jetpack_options (array)
27
	An array of options.
28
	@see Jetpack_Options::get_option_names()
29
30
jetpack_register (string)
31
	Temporary verification secrets.
32
33
jetpack_activated (int)
34
	1: the plugin was activated normally
35
	2: the plugin was activated on this site because of a network-wide activation
36
	3: the plugin was auto-installed
37
	4: the plugin was manually disconnected (but is still installed)
38
39
jetpack_active_modules (array)
40
	Array of active module slugs.
41
42
jetpack_do_activate (bool)
43
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
44
*/
45
46
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
47
48
class Jetpack {
49
	public $xmlrpc_server = null;
50
51
	/**
52
	 * @var array The handles of styles that are concatenated into jetpack.css.
53
	 *
54
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
55
	 */
56
	public $concatenated_style_handles = array(
57
		'jetpack-carousel',
58
		'grunion.css',
59
		'the-neverending-homepage',
60
		'jetpack_likes',
61
		'jetpack_related-posts',
62
		'sharedaddy',
63
		'jetpack-slideshow',
64
		'presentations',
65
		'quiz',
66
		'jetpack-subscriptions',
67
		'jetpack-responsive-videos-style',
68
		'jetpack-social-menu',
69
		'tiled-gallery',
70
		'jetpack_display_posts_widget',
71
		'gravatar-profile-widget',
72
		'goodreads-widget',
73
		'jetpack_social_media_icons_widget',
74
		'jetpack-top-posts-widget',
75
		'jetpack_image_widget',
76
		'jetpack-my-community-widget',
77
		'jetpack-authors-widget',
78
		'wordads',
79
		'eu-cookie-law-style',
80
		'flickr-widget-style',
81
		'jetpack-search-widget',
82
		'jetpack-simple-payments-widget-style',
83
		'jetpack-widget-social-icons-styles',
84
		'wpcom_instagram_widget',
85
	);
86
87
	/**
88
	 * Contains all assets that have had their URL rewritten to minified versions.
89
	 *
90
	 * @var array
91
	 */
92
	static $min_assets = array();
93
94
	public $plugins_to_deactivate = array(
95
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
96
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
97
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
98
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
99
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
100
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
101
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
102
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
103
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
104
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
105
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
106
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
107
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
108
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
109
	);
110
111
	/**
112
	 * Map of roles we care about, and their corresponding minimum capabilities.
113
	 *
114
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
115
	 *
116
	 * @access public
117
	 * @static
118
	 *
119
	 * @var array
120
	 */
121
	public static $capability_translations = array(
122
		'administrator' => 'manage_options',
123
		'editor'        => 'edit_others_posts',
124
		'author'        => 'publish_posts',
125
		'contributor'   => 'edit_posts',
126
		'subscriber'    => 'read',
127
	);
128
129
	/**
130
	 * Map of modules that have conflicts with plugins and should not be auto-activated
131
	 * if the plugins are active.  Used by filter_default_modules
132
	 *
133
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
134
	 * change `module-slug` and add this to your plugin:
135
	 *
136
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
137
	 * function my_jetpack_get_default_modules( $modules ) {
138
	 *     return array_diff( $modules, array( 'module-slug' ) );
139
	 * }
140
	 *
141
	 * @var array
142
	 */
143
	private $conflicting_plugins = array(
144
		'comments'           => array(
145
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
146
			'Disqus'                         => 'disqus-comment-system/disqus.php',
147
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
148
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
149
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
150
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
151
		),
152
		'comment-likes'      => array(
153
			'Epoch' => 'epoch/plugincore.php',
154
		),
155
		'contact-form'       => array(
156
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
157
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
158
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
159
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
160
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
161
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
162
		),
163
		'latex'              => array(
164
			'LaTeX for WordPress'     => 'latex/latex.php',
165
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
166
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
167
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
168
			'Enable Latex'            => 'enable-latex/enable-latex.php',
169
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
170
		),
171
		'protect'            => array(
172
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
173
			'Captcha'                           => 'captcha/captcha.php',
174
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
175
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
176
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
177
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
178
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
179
			'Security-protection'               => 'security-protection/security-protection.php',
180
			'Login Security'                    => 'login-security/login-security.php',
181
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
182
			'Wordfence Security'                => 'wordfence/wordfence.php',
183
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
184
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
185
		),
186
		'random-redirect'    => array(
187
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
188
		),
189
		'related-posts'      => array(
190
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
191
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
192
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
193
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
194
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
195
			'outbrain'                    => 'outbrain/outbrain.php',
196
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
197
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
198
		),
199
		'sharedaddy'         => array(
200
			'AddThis'     => 'addthis/addthis_social_widget.php',
201
			'Add To Any'  => 'add-to-any/add-to-any.php',
202
			'ShareThis'   => 'share-this/sharethis.php',
203
			'Shareaholic' => 'shareaholic/shareaholic.php',
204
		),
205
		'seo-tools'          => array(
206
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
207
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
208
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
209
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
210
			'The SEO Framework'              => 'autodescription/autodescription.php',
211
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
212
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
213
		),
214
		'verification-tools' => array(
215
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'              => 'autodescription/autodescription.php',
220
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
221
			'Slim SEO'                       => 'slim-seo/slim-seo.php',
222
		),
223
		'widget-visibility'  => array(
224
			'Widget Logic'    => 'widget-logic/widget_logic.php',
225
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
226
		),
227
		'sitemaps'           => array(
228
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
229
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
230
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
231
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
232
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
233
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
234
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
235
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
236
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
237
			'The SEO Framework'                    => 'autodescription/autodescription.php',
238
			'Sitemap'                              => 'sitemap/sitemap.php',
239
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
240
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
241
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
242
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
243
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
244
			'Slim SEO'                             => 'slim-seo/slim-seo.php',
245
		),
246
		'lazy-images'        => array(
247
			'Lazy Load'              => 'lazy-load/lazy-load.php',
248
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
249
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
250
		),
251
	);
252
253
	/**
254
	 * Plugins for which we turn off our Facebook OG Tags implementation.
255
	 *
256
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
257
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
258
	 *
259
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
260
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
261
	 */
262
	private $open_graph_conflicting_plugins = array(
263
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
264
		// 2 Click Social Media Buttons
265
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
266
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
267
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
268
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
269
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
270
		// Open Graph Meta Tags by Heateor
271
		'facebook/facebook.php',                                 // Facebook (official plugin)
272
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
273
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
274
		// Facebook Featured Image & OG Meta Tags
275
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
276
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
277
		// Facebook Open Graph Meta Tags for WordPress
278
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
279
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
280
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
281
		// Fedmich's Facebook Open Graph Meta
282
		'network-publisher/networkpub.php',                      // Network Publisher
283
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
284
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
285
		// NextScripts SNAP
286
		'og-tags/og-tags.php',                                   // OG Tags
287
		'opengraph/opengraph.php',                               // Open Graph
288
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
289
		// Open Graph Protocol Framework
290
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
291
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
292
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
293
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
294
		'sharepress/sharepress.php',                             // SharePress
295
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
296
		'social-discussions/social-discussions.php',             // Social Discussions
297
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
298
		'socialize/socialize.php',                               // Socialize
299
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
300
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
301
		// Tweet, Like, Google +1 and Share
302
		'wordbooker/wordbooker.php',                             // Wordbooker
303
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
304
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
305
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
306
		// WP Facebook Like Send & Open Graph Meta
307
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
308
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
309
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
310
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
311
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
312
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
313
		'slim-seo/slim-seo.php',                                 // Slim SEO
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
		// 'twitter/twitter.php',                       // The official one handles this on its own.
321
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
		'seo-by-rank-math/rank-math.php',            // Rank Math.
332
		'slim-seo/slim-seo.php',                     // Slim SEO
333
	);
334
335
	/**
336
	 * Message to display in admin_notice
337
	 *
338
	 * @var string
339
	 */
340
	public $message = '';
341
342
	/**
343
	 * Error to display in admin_notice
344
	 *
345
	 * @var string
346
	 */
347
	public $error = '';
348
349
	/**
350
	 * Modules that need more privacy description.
351
	 *
352
	 * @var string
353
	 */
354
	public $privacy_checks = '';
355
356
	/**
357
	 * Stats to record once the page loads
358
	 *
359
	 * @var array
360
	 */
361
	public $stats = array();
362
363
	/**
364
	 * Jetpack_Sync object
365
	 */
366
	public $sync;
367
368
	/**
369
	 * Verified data for JSON authorization request
370
	 */
371
	public $json_api_authorization_request = array();
372
373
	/**
374
	 * @var Automattic\Jetpack\Connection\Manager
375
	 */
376
	protected $connection_manager;
377
378
	/**
379
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
380
	 */
381
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
382
383
	/**
384
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
385
	 *
386
	 * @var Automattic\Jetpack\A8c_Mc_Stats
387
	 */
388
	public $a8c_mc_stats_instance;
389
390
	/**
391
	 * Constant for login redirect key.
392
	 *
393
	 * @var string
394
	 * @since 8.4.0
395
	 */
396
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
397
398
	/**
399
	 * Holds the singleton instance of this class
400
	 *
401
	 * @since 2.3.3
402
	 * @var Jetpack
403
	 */
404
	static $instance = false;
405
406
	/**
407
	 * Singleton
408
	 *
409
	 * @static
410
	 */
411
	public static function init() {
412
		if ( ! self::$instance ) {
413
			self::$instance = new Jetpack();
414
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
415
		}
416
417
		return self::$instance;
418
	}
419
420
	/**
421
	 * Must never be called statically
422
	 */
423
	function plugin_upgrade() {
424
		if ( self::is_active() ) {
425
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
426
			if ( JETPACK__VERSION != $version ) {
427
				// Prevent multiple upgrades at once - only a single process should trigger
428
				// an upgrade to avoid stampedes
429
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
430
					return;
431
				}
432
433
				// Set a short lock to prevent multiple instances of the upgrade
434
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
435
436
				// check which active modules actually exist and remove others from active_modules list
437
				$unfiltered_modules = self::get_active_modules();
438
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
439
				if ( array_diff( $unfiltered_modules, $modules ) ) {
440
					self::update_active_modules( $modules );
441
				}
442
443
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
444
445
				// Upgrade to 4.3.0
446
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
447
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
448
				}
449
450
				// Make sure Markdown for posts gets turned back on
451
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
452
					update_option( 'wpcom_publish_posts_with_markdown', true );
453
				}
454
455
				/*
456
				 * Minileven deprecation. 8.3.0.
457
				 * Only delete options if not using
458
				 * the replacement standalone Minileven plugin.
459
				 */
460
				if (
461
					! self::is_plugin_active( 'minileven-master/minileven.php' )
462
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
463
				) {
464
					if ( get_option( 'wp_mobile_custom_css' ) ) {
465
						delete_option( 'wp_mobile_custom_css' );
466
					}
467
					if ( get_option( 'wp_mobile_excerpt' ) ) {
468
						delete_option( 'wp_mobile_excerpt' );
469
					}
470
					if ( get_option( 'wp_mobile_featured_images' ) ) {
471
						delete_option( 'wp_mobile_featured_images' );
472
					}
473
					if ( get_option( 'wp_mobile_app_promos' ) ) {
474
						delete_option( 'wp_mobile_app_promos' );
475
					}
476
				}
477
478
				// Upgrade to 8.4.0.
479
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
480
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
481
				}
482
483
				// Update to 8.8.x (WordPress 5.5 Compatibility).
484
				if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
485
					$updated = update_site_option(
486
						'auto_update_plugins',
487
						array_unique(
488
							array_merge(
489
								(array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
490
								(array) get_site_option( 'auto_update_plugins', array() )
491
							)
492
						)
493
					);
494
495
					if ( $updated ) {
496
						Jetpack_Options::delete_option( 'autoupdate_plugins' );
497
					} // Should we have some type of fallback if something fails here?
498
				}
499
500
				if ( did_action( 'wp_loaded' ) ) {
501
					self::upgrade_on_load();
502
				} else {
503
					add_action(
504
						'wp_loaded',
505
						array( __CLASS__, 'upgrade_on_load' )
506
					);
507
				}
508
			}
509
		}
510
	}
511
512
	/**
513
	 * Runs upgrade routines that need to have modules loaded.
514
	 */
515
	static function upgrade_on_load() {
516
517
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
518
		// This can happen in case Jetpack has been just upgraded and is
519
		// being initialized late during the page load. In this case we wait
520
		// until the next proper admin page load with Jetpack active.
521
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
522
			delete_transient( self::$plugin_upgrade_lock_key );
523
524
			return;
525
		}
526
527
		self::maybe_set_version_option();
528
529
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
530
			Jetpack_Widget_Conditions::migrate_post_type_rules();
531
		}
532
533
		if (
534
			class_exists( 'Jetpack_Sitemap_Manager' )
535
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
536
		) {
537
			do_action( 'jetpack_sitemaps_purge_data' );
538
		}
539
540
		// Delete old stats cache
541
		delete_option( 'jetpack_restapi_stats_cache' );
542
543
		delete_transient( self::$plugin_upgrade_lock_key );
544
	}
545
546
	/**
547
	 * Saves all the currently active modules to options.
548
	 * Also fires Action hooks for each newly activated and deactivated module.
549
	 *
550
	 * @param $modules Array Array of active modules to be saved in options.
551
	 *
552
	 * @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...
553
	 */
554
	static function update_active_modules( $modules ) {
555
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
556
		$active_modules       = self::get_active_modules();
557
		$new_active_modules   = array_diff( $modules, $current_modules );
558
		$new_inactive_modules = array_diff( $active_modules, $modules );
559
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
560
		$reindexed_modules    = array_values( $new_current_modules );
561
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
562
563
		foreach ( $new_active_modules as $module ) {
564
			/**
565
			 * Fires when a specific module is activated.
566
			 *
567
			 * @since 1.9.0
568
			 *
569
			 * @param string $module Module slug.
570
			 * @param boolean $success whether the module was activated. @since 4.2
571
			 */
572
			do_action( 'jetpack_activate_module', $module, $success );
573
			/**
574
			 * Fires when a module is activated.
575
			 * The dynamic part of the filter, $module, is the module slug.
576
			 *
577
			 * @since 1.9.0
578
			 *
579
			 * @param string $module Module slug.
580
			 */
581
			do_action( "jetpack_activate_module_$module", $module );
582
		}
583
584
		foreach ( $new_inactive_modules as $module ) {
585
			/**
586
			 * Fired after a module has been deactivated.
587
			 *
588
			 * @since 4.2.0
589
			 *
590
			 * @param string $module Module slug.
591
			 * @param boolean $success whether the module was deactivated.
592
			 */
593
			do_action( 'jetpack_deactivate_module', $module, $success );
594
			/**
595
			 * Fires when a module is deactivated.
596
			 * The dynamic part of the filter, $module, is the module slug.
597
			 *
598
			 * @since 1.9.0
599
			 *
600
			 * @param string $module Module slug.
601
			 */
602
			do_action( "jetpack_deactivate_module_$module", $module );
603
		}
604
605
		return $success;
606
	}
607
608
	static function delete_active_modules() {
609
		self::update_active_modules( array() );
610
	}
611
612
	/**
613
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
614
	 * available.
615
	 */
616
	public function add_configure_hook() {
617
		global $wp_filter;
618
619
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
620
		if ( false !== $current_priority ) {
621
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
622
		}
623
624
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
625
		sort( $taken_priorities );
626
627
		$first_priority = array_shift( $taken_priorities );
628
629
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
630
			$new_priority = - PHP_INT_MAX;
631
		} else {
632
			$new_priority = $first_priority - 1;
633
		}
634
635
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
636
	}
637
638
	/**
639
	 * Constructor.  Initializes WordPress hooks
640
	 */
641
	private function __construct() {
642
		/*
643
		 * Check for and alert any deprecated hooks
644
		 */
645
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
646
647
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
648
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
649
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
650
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
651
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
652
653
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
654
655
		add_filter(
656
			'jetpack_signature_check_token',
657
			array( __CLASS__, 'verify_onboarding_token' ),
658
			10,
659
			3
660
		);
661
662
		/**
663
		 * Prepare Gutenberg Editor functionality
664
		 */
665
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
666
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
667
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
668
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
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
		// Set up the REST authentication hooks.
683
		Connection_Rest_Authentication::init();
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
			)
796
			as $feature
797
		) {
798
			$config->ensure( $feature );
799
		}
800
801
		$config->ensure(
802
			'connection',
803
			array(
804
				'slug' => 'jetpack',
805
				'name' => 'Jetpack',
806
			)
807
		);
808
809
		if ( is_admin() ) {
810
			$config->ensure( 'jitm' );
811
		}
812
813
		if ( ! $this->connection_manager ) {
814
			$this->connection_manager = new Connection_Manager( 'jetpack' );
815
		}
816
817
		/*
818
		 * Load things that should only be in Network Admin.
819
		 *
820
		 * For now blow away everything else until a more full
821
		 * understanding of what is needed at the network level is
822
		 * available
823
		 */
824
		if ( is_multisite() ) {
825
			$network = Jetpack_Network::init();
826
			$network->set_connection( $this->connection_manager );
827
		}
828
829
		if ( $this->connection_manager->is_active() ) {
830
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
831
832
			Jetpack_Heartbeat::init();
833
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
834
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
835
				Jetpack_Search_Performance_Logger::init();
836
			}
837
		}
838
839
		// Initialize remote file upload request handlers.
840
		$this->add_remote_request_handlers();
841
842
		/*
843
		 * Enable enhanced handling of previewing sites in Calypso
844
		 */
845
		if ( self::is_active() ) {
846
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
847
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
848
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
849
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
850
		}
851
852
		if ( ( new Tracking( $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) ) {
0 ignored issues
show
Documentation introduced by
$this->connection_manager is of type object<Automattic\Jetpack\Connection\Manager>, 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...
Documentation introduced by
new \Automattic\Jetpack\Terms_Of_Service() is of type object<Automattic\Jetpack\Terms_Of_Service>, but the function expects a object<Automattic\Jetpac...tpack\Terms_Of_Service>.

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...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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