Completed
Push — update/story-block-loading-med... ( 27619f...a94e37 )
by
unknown
08:38
created

Jetpack::intercept_plugin_error_scrape()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 2
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Health;
15
use Automattic\Jetpack\Sync\Sender;
16
use Automattic\Jetpack\Sync\Users;
17
use Automattic\Jetpack\Terms_Of_Service;
18
use Automattic\Jetpack\Tracking;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
22
23
/*
24
Options:
25
jetpack_options (array)
26
	An array of options.
27
	@see Jetpack_Options::get_option_names()
28
29
jetpack_register (string)
30
	Temporary verification secrets.
31
32
jetpack_activated (int)
33
	1: the plugin was activated normally
34
	2: the plugin was activated on this site because of a network-wide activation
35
	3: the plugin was auto-installed
36
	4: the plugin was manually disconnected (but is still installed)
37
38
jetpack_active_modules (array)
39
	Array of active module slugs.
40
41
jetpack_do_activate (bool)
42
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
43
*/
44
45
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
46
47
class Jetpack {
48
	public $xmlrpc_server = null;
49
50
	private $rest_authentication_status = null;
51
52
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
53
54
	/**
55
	 * @var array The handles of styles that are concatenated into jetpack.css.
56
	 *
57
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
58
	 */
59
	public $concatenated_style_handles = array(
60
		'jetpack-carousel',
61
		'grunion.css',
62
		'the-neverending-homepage',
63
		'jetpack_likes',
64
		'jetpack_related-posts',
65
		'sharedaddy',
66
		'jetpack-slideshow',
67
		'presentations',
68
		'quiz',
69
		'jetpack-subscriptions',
70
		'jetpack-responsive-videos-style',
71
		'jetpack-social-menu',
72
		'tiled-gallery',
73
		'jetpack_display_posts_widget',
74
		'gravatar-profile-widget',
75
		'goodreads-widget',
76
		'jetpack_social_media_icons_widget',
77
		'jetpack-top-posts-widget',
78
		'jetpack_image_widget',
79
		'jetpack-my-community-widget',
80
		'jetpack-authors-widget',
81
		'wordads',
82
		'eu-cookie-law-style',
83
		'flickr-widget-style',
84
		'jetpack-search-widget',
85
		'jetpack-simple-payments-widget-style',
86
		'jetpack-widget-social-icons-styles',
87
		'wpcom_instagram_widget',
88
	);
89
90
	/**
91
	 * Contains all assets that have had their URL rewritten to minified versions.
92
	 *
93
	 * @var array
94
	 */
95
	static $min_assets = array();
96
97
	public $plugins_to_deactivate = array(
98
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
99
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
100
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
101
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
102
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
103
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
104
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
105
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
106
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
107
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
108
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
109
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
110
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
111
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
112
	);
113
114
	/**
115
	 * Map of roles we care about, and their corresponding minimum capabilities.
116
	 *
117
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
118
	 *
119
	 * @access public
120
	 * @static
121
	 *
122
	 * @var array
123
	 */
124
	public static $capability_translations = array(
125
		'administrator' => 'manage_options',
126
		'editor'        => 'edit_others_posts',
127
		'author'        => 'publish_posts',
128
		'contributor'   => 'edit_posts',
129
		'subscriber'    => 'read',
130
	);
131
132
	/**
133
	 * Map of modules that have conflicts with plugins and should not be auto-activated
134
	 * if the plugins are active.  Used by filter_default_modules
135
	 *
136
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
137
	 * change `module-slug` and add this to your plugin:
138
	 *
139
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
140
	 * function my_jetpack_get_default_modules( $modules ) {
141
	 *     return array_diff( $modules, array( 'module-slug' ) );
142
	 * }
143
	 *
144
	 * @var array
145
	 */
146
	private $conflicting_plugins = array(
147
		'comments'           => array(
148
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
149
			'Disqus'                         => 'disqus-comment-system/disqus.php',
150
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
151
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
152
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
153
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
154
		),
155
		'comment-likes'      => array(
156
			'Epoch' => 'epoch/plugincore.php',
157
		),
158
		'contact-form'       => array(
159
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
160
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
161
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
162
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
163
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
164
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
165
		),
166
		'latex'              => array(
167
			'LaTeX for WordPress'     => 'latex/latex.php',
168
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
169
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
170
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
171
			'Enable Latex'            => 'enable-latex/enable-latex.php',
172
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
173
		),
174
		'protect'            => array(
175
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
176
			'Captcha'                           => 'captcha/captcha.php',
177
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
178
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
179
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
180
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
181
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
182
			'Security-protection'               => 'security-protection/security-protection.php',
183
			'Login Security'                    => 'login-security/login-security.php',
184
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
185
			'Wordfence Security'                => 'wordfence/wordfence.php',
186
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
187
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
188
		),
189
		'random-redirect'    => array(
190
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
191
		),
192
		'related-posts'      => array(
193
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
194
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
195
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
196
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
197
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
198
			'outbrain'                    => 'outbrain/outbrain.php',
199
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
200
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
201
		),
202
		'sharedaddy'         => array(
203
			'AddThis'     => 'addthis/addthis_social_widget.php',
204
			'Add To Any'  => 'add-to-any/add-to-any.php',
205
			'ShareThis'   => 'share-this/sharethis.php',
206
			'Shareaholic' => 'shareaholic/shareaholic.php',
207
		),
208
		'seo-tools'          => array(
209
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
210
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
211
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
212
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
213
			'The SEO Framework'              => 'autodescription/autodescription.php',
214
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
215
		),
216
		'verification-tools' => array(
217
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
218
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
219
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
220
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
221
			'The SEO Framework'              => 'autodescription/autodescription.php',
222
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
223
		),
224
		'widget-visibility'  => array(
225
			'Widget Logic'    => 'widget-logic/widget_logic.php',
226
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
227
		),
228
		'sitemaps'           => array(
229
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
230
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
231
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
232
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
233
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
234
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
235
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
236
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
237
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
238
			'The SEO Framework'                    => 'autodescription/autodescription.php',
239
			'Sitemap'                              => 'sitemap/sitemap.php',
240
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
241
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
242
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
243
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
244
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
245
		),
246
		'lazy-images'        => array(
247
			'Lazy Load'              => 'lazy-load/lazy-load.php',
248
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
249
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
250
		),
251
	);
252
253
	/**
254
	 * Plugins for which we turn off our Facebook OG Tags implementation.
255
	 *
256
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
257
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
258
	 *
259
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
260
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
261
	 */
262
	private $open_graph_conflicting_plugins = array(
263
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
264
		// 2 Click Social Media Buttons
265
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
266
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
267
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
268
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
269
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
270
		// Open Graph Meta Tags by Heateor
271
		'facebook/facebook.php',                                 // Facebook (official plugin)
272
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
273
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
274
		// Facebook Featured Image & OG Meta Tags
275
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
276
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
277
		// Facebook Open Graph Meta Tags for WordPress
278
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
279
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
280
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
281
		// Fedmich's Facebook Open Graph Meta
282
		'network-publisher/networkpub.php',                      // Network Publisher
283
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
284
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
285
		// NextScripts SNAP
286
		'og-tags/og-tags.php',                                   // OG Tags
287
		'opengraph/opengraph.php',                               // Open Graph
288
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
289
		// Open Graph Protocol Framework
290
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
291
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
292
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
293
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
294
		'sharepress/sharepress.php',                             // SharePress
295
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
296
		'social-discussions/social-discussions.php',             // Social Discussions
297
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
298
		'socialize/socialize.php',                               // Socialize
299
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
300
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
301
		// Tweet, Like, Google +1 and Share
302
		'wordbooker/wordbooker.php',                             // Wordbooker
303
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
304
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
305
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
306
		// WP Facebook Like Send & Open Graph Meta
307
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
308
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
309
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
310
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
311
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
312
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
313
	);
314
315
	/**
316
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
317
	 */
318
	private $twitter_cards_conflicting_plugins = array(
319
		// 'twitter/twitter.php',                       // The official one handles this on its own.
320
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
321
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
322
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
323
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
324
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
325
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
326
		'twitter-cards/twitter-cards.php',           // Twitter Cards
327
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
328
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
329
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
330
		'seo-by-rank-math/rank-math.php',            // Rank Math.
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 *
336
	 * @var string
337
	 */
338
	public $message = '';
339
340
	/**
341
	 * Error to display in admin_notice
342
	 *
343
	 * @var string
344
	 */
345
	public $error = '';
346
347
	/**
348
	 * Modules that need more privacy description.
349
	 *
350
	 * @var string
351
	 */
352
	public $privacy_checks = '';
353
354
	/**
355
	 * Stats to record once the page loads
356
	 *
357
	 * @var array
358
	 */
359
	public $stats = array();
360
361
	/**
362
	 * Jetpack_Sync object
363
	 */
364
	public $sync;
365
366
	/**
367
	 * Verified data for JSON authorization request
368
	 */
369
	public $json_api_authorization_request = array();
370
371
	/**
372
	 * @var Automattic\Jetpack\Connection\Manager
373
	 */
374
	protected $connection_manager;
375
376
	/**
377
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
378
	 */
379
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
380
381
	/**
382
	 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
383
	 *
384
	 * @var Automattic\Jetpack\A8c_Mc_Stats
385
	 */
386
	public $a8c_mc_stats_instance;
387
388
	/**
389
	 * Constant for login redirect key.
390
	 *
391
	 * @var string
392
	 * @since 8.4.0
393
	 */
394
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
395
396
	/**
397
	 * Holds the singleton instance of this class
398
	 *
399
	 * @since 2.3.3
400
	 * @var Jetpack
401
	 */
402
	static $instance = false;
403
404
	/**
405
	 * Singleton
406
	 *
407
	 * @static
408
	 */
409
	public static function init() {
410
		if ( ! self::$instance ) {
411
			self::$instance = new Jetpack();
412
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
413
		}
414
415
		return self::$instance;
416
	}
417
418
	/**
419
	 * Must never be called statically
420
	 */
421
	function plugin_upgrade() {
422
		if ( self::is_active() ) {
423
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
424
			if ( JETPACK__VERSION != $version ) {
425
				// Prevent multiple upgrades at once - only a single process should trigger
426
				// an upgrade to avoid stampedes
427
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
428
					return;
429
				}
430
431
				// Set a short lock to prevent multiple instances of the upgrade
432
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
433
434
				// check which active modules actually exist and remove others from active_modules list
435
				$unfiltered_modules = self::get_active_modules();
436
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
437
				if ( array_diff( $unfiltered_modules, $modules ) ) {
438
					self::update_active_modules( $modules );
439
				}
440
441
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
442
443
				// Upgrade to 4.3.0
444
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
445
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
446
				}
447
448
				// Make sure Markdown for posts gets turned back on
449
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
450
					update_option( 'wpcom_publish_posts_with_markdown', true );
451
				}
452
453
				/*
454
				 * Minileven deprecation. 8.3.0.
455
				 * Only delete options if not using
456
				 * the replacement standalone Minileven plugin.
457
				 */
458
				if (
459
					! self::is_plugin_active( 'minileven-master/minileven.php' )
460
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
461
				) {
462
					if ( get_option( 'wp_mobile_custom_css' ) ) {
463
						delete_option( 'wp_mobile_custom_css' );
464
					}
465
					if ( get_option( 'wp_mobile_excerpt' ) ) {
466
						delete_option( 'wp_mobile_excerpt' );
467
					}
468
					if ( get_option( 'wp_mobile_featured_images' ) ) {
469
						delete_option( 'wp_mobile_featured_images' );
470
					}
471
					if ( get_option( 'wp_mobile_app_promos' ) ) {
472
						delete_option( 'wp_mobile_app_promos' );
473
					}
474
				}
475
476
				// Upgrade to 8.4.0.
477
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
478
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
479
				}
480
481
				if ( did_action( 'wp_loaded' ) ) {
482
					self::upgrade_on_load();
483
				} else {
484
					add_action(
485
						'wp_loaded',
486
						array( __CLASS__, 'upgrade_on_load' )
487
					);
488
				}
489
			}
490
		}
491
	}
492
493
	/**
494
	 * Runs upgrade routines that need to have modules loaded.
495
	 */
496
	static function upgrade_on_load() {
497
498
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
499
		// This can happen in case Jetpack has been just upgraded and is
500
		// being initialized late during the page load. In this case we wait
501
		// until the next proper admin page load with Jetpack active.
502
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
503
			delete_transient( self::$plugin_upgrade_lock_key );
504
505
			return;
506
		}
507
508
		self::maybe_set_version_option();
509
510
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
511
			Jetpack_Widget_Conditions::migrate_post_type_rules();
512
		}
513
514
		if (
515
			class_exists( 'Jetpack_Sitemap_Manager' )
516
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
517
		) {
518
			do_action( 'jetpack_sitemaps_purge_data' );
519
		}
520
521
		// Delete old stats cache
522
		delete_option( 'jetpack_restapi_stats_cache' );
523
524
		delete_transient( self::$plugin_upgrade_lock_key );
525
	}
526
527
	/**
528
	 * Saves all the currently active modules to options.
529
	 * Also fires Action hooks for each newly activated and deactivated module.
530
	 *
531
	 * @param $modules Array Array of active modules to be saved in options.
532
	 *
533
	 * @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...
534
	 */
535
	static function update_active_modules( $modules ) {
536
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
537
		$active_modules       = self::get_active_modules();
538
		$new_active_modules   = array_diff( $modules, $current_modules );
539
		$new_inactive_modules = array_diff( $active_modules, $modules );
540
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
541
		$reindexed_modules    = array_values( $new_current_modules );
542
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
543
544
		foreach ( $new_active_modules as $module ) {
545
			/**
546
			 * Fires when a specific module is activated.
547
			 *
548
			 * @since 1.9.0
549
			 *
550
			 * @param string $module Module slug.
551
			 * @param boolean $success whether the module was activated. @since 4.2
552
			 */
553
			do_action( 'jetpack_activate_module', $module, $success );
554
			/**
555
			 * Fires when a module is activated.
556
			 * The dynamic part of the filter, $module, is the module slug.
557
			 *
558
			 * @since 1.9.0
559
			 *
560
			 * @param string $module Module slug.
561
			 */
562
			do_action( "jetpack_activate_module_$module", $module );
563
		}
564
565
		foreach ( $new_inactive_modules as $module ) {
566
			/**
567
			 * Fired after a module has been deactivated.
568
			 *
569
			 * @since 4.2.0
570
			 *
571
			 * @param string $module Module slug.
572
			 * @param boolean $success whether the module was deactivated.
573
			 */
574
			do_action( 'jetpack_deactivate_module', $module, $success );
575
			/**
576
			 * Fires when a module is deactivated.
577
			 * The dynamic part of the filter, $module, is the module slug.
578
			 *
579
			 * @since 1.9.0
580
			 *
581
			 * @param string $module Module slug.
582
			 */
583
			do_action( "jetpack_deactivate_module_$module", $module );
584
		}
585
586
		return $success;
587
	}
588
589
	static function delete_active_modules() {
590
		self::update_active_modules( array() );
591
	}
592
593
	/**
594
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
595
	 * available.
596
	 */
597
	public function add_configure_hook() {
598
		global $wp_filter;
599
600
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
601
		if ( false !== $current_priority ) {
602
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
603
		}
604
605
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
606
		sort( $taken_priorities );
607
608
		$first_priority = array_shift( $taken_priorities );
609
610
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
611
			$new_priority = - PHP_INT_MAX;
612
		} else {
613
			$new_priority = $first_priority - 1;
614
		}
615
616
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
617
	}
618
619
	/**
620
	 * Constructor.  Initializes WordPress hooks
621
	 */
622
	private function __construct() {
623
		/*
624
		 * Check for and alert any deprecated hooks
625
		 */
626
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
627
628
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
629
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
630
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
631
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
632
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
633
634
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
635
636
		add_filter(
637
			'jetpack_signature_check_token',
638
			array( __CLASS__, 'verify_onboarding_token' ),
639
			10,
640
			3
641
		);
642
643
		/**
644
		 * Prepare Gutenberg Editor functionality
645
		 */
646
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
647
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
648
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
649
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
650
651
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
652
653
		// Unlink user before deleting the user from WP.com.
654
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
655
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
656
657
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
658
659
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
660
		add_action( 'login_init', array( $this, 'login_init' ) );
661
662
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
663
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
664
665
		add_action( 'admin_init', array( $this, 'admin_init' ) );
666
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
667
668
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
669
670
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
671
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
672
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
673
674
		// returns HTTPS support status
675
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
676
677
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
678
679
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
680
681
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
682
683
		/**
684
		 * These actions run checks to load additional files.
685
		 * They check for external files or plugins, so they need to run as late as possible.
686
		 */
687
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
688
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
689
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
690
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
691
692
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
693
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
694
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
695
696
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
697
698
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
700
701
		// A filter to control all just in time messages
702
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
703
704
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
705
706
		/*
707
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
708
		 * We should make sure to only do this for front end links.
709
		 */
710
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
711
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
712
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
713
714
			/*
715
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
716
			 * so they point moderation links on emails to Calypso.
717
			 */
718
			jetpack_require_lib( 'functions.wp-notify' );
719
		}
720
721
		add_action(
722
			'plugins_loaded',
723
			function() {
724
				if ( User_Agent_Info::is_mobile_app() ) {
725
					add_filter( 'get_edit_post_link', '__return_empty_string' );
726
				}
727
			}
728
		);
729
730
		// Update the Jetpack plan from API on heartbeats.
731
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
732
733
		/**
734
		 * This is the hack to concatenate all css files into one.
735
		 * For description and reasoning see the implode_frontend_css method.
736
		 *
737
		 * Super late priority so we catch all the registered styles.
738
		 */
739
		if ( ! is_admin() ) {
740
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
741
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
742
		}
743
744
		/**
745
		 * These are sync actions that we need to keep track of for jitms
746
		 */
747
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
748
749
		// Actually push the stats on shutdown.
750
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
751
			add_action( 'shutdown', array( $this, 'push_stats' ) );
752
		}
753
754
		// Actions for Manager::authorize().
755
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
756
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
757
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
758
759
		// Filters for the Manager::get_token() urls and request body.
760
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
761
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
762
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
763
	}
764
765
	/**
766
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
767
	 * Config object.
768
	 */
769
	public function configure() {
770
		$config = new Config();
771
772
		foreach (
773
			array(
774
				'sync',
775
				'tracking',
776
				'tos',
777
			)
778
			as $feature
779
		) {
780
			$config->ensure( $feature );
781
		}
782
783
		$config->ensure(
784
			'connection',
785
			array(
786
				'slug' => 'jetpack',
787
				'name' => 'Jetpack',
788
			)
789
		);
790
791
		if ( is_admin() ) {
792
			$config->ensure( 'jitm' );
793
		}
794
795
		if ( ! $this->connection_manager ) {
796
			$this->connection_manager = new Connection_Manager( 'jetpack' );
797
		}
798
799
		/*
800
		 * Load things that should only be in Network Admin.
801
		 *
802
		 * For now blow away everything else until a more full
803
		 * understanding of what is needed at the network level is
804
		 * available
805
		 */
806
		if ( is_multisite() ) {
807
			$network = Jetpack_Network::init();
808
			$network->set_connection( $this->connection_manager );
809
		}
810
811
		if ( $this->connection_manager->is_active() ) {
812
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
813
814
			Jetpack_Heartbeat::init();
815
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
816
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
817
				Jetpack_Search_Performance_Logger::init();
818
			}
819
		}
820
821
		// Initialize remote file upload request handlers.
822
		$this->add_remote_request_handlers();
823
824
		/*
825
		 * Enable enhanced handling of previewing sites in Calypso
826
		 */
827
		if ( self::is_active() ) {
828
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
829
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
830
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
831
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
832
		}
833
	}
834
835
	/**
836
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
837
	 * initialization code.
838
	 *
839
	 * @action plugins_loaded
840
	 */
841
	public function late_initialization() {
842
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
843
844
		Partner::init();
845
846
		/**
847
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
848
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
849
		 *
850
		 * @since 8.1.0
851
		 *
852
		 * @param Jetpack $jetpack the main plugin class object.
853
		 */
854
		do_action( 'jetpack_loaded', $this );
855
856
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
857
	}
858
859
	/**
860
	 * Sets up the XMLRPC request handlers.
861
	 *
862
	 * @deprecated since 7.7.0
863
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
864
	 *
865
	 * @param array                 $request_params Incoming request parameters.
866
	 * @param Boolean               $is_active      Whether the connection is currently active.
867
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
868
	 * @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...
869
	 */
870 View Code Duplication
	public function setup_xmlrpc_handlers(
871
		$request_params,
872
		$is_active,
873
		$is_signed,
874
		Jetpack_XMLRPC_Server $xmlrpc_server = null
875
	) {
876
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
877
878
		if ( ! $this->connection_manager ) {
879
			$this->connection_manager = new Connection_Manager();
880
		}
881
882
		return $this->connection_manager->setup_xmlrpc_handlers(
883
			$request_params,
884
			$is_active,
885
			$is_signed,
886
			$xmlrpc_server
887
		);
888
	}
889
890
	/**
891
	 * Initialize REST API registration connector.
892
	 *
893
	 * @deprecated since 7.7.0
894
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
895
	 */
896 View Code Duplication
	public function initialize_rest_api_registration_connector() {
897
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
898
899
		if ( ! $this->connection_manager ) {
900
			$this->connection_manager = new Connection_Manager();
901
		}
902
903
		$this->connection_manager->initialize_rest_api_registration_connector();
904
	}
905
906
	/**
907
	 * This is ported over from the manage module, which has been deprecated and baked in here.
908
	 *
909
	 * @param $domains
910
	 */
911
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
912
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
913
	}
914
915
	/**
916
	 * Return $domains, with 'wordpress.com' appended.
917
	 * This is ported over from the manage module, which has been deprecated and baked in here.
918
	 *
919
	 * @param $domains
920
	 * @return array
921
	 */
922
	function allow_wpcom_domain( $domains ) {
923
		if ( empty( $domains ) ) {
924
			$domains = array();
925
		}
926
		$domains[] = 'wordpress.com';
927
		return array_unique( $domains );
928
	}
929
930
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
931
		$post = get_post( $post_id );
932
933
		if ( empty( $post ) ) {
934
			return $default_url;
935
		}
936
937
		$post_type = $post->post_type;
938
939
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
940
		// https://en.support.wordpress.com/custom-post-types/
941
		$allowed_post_types = array(
942
			'post',
943
			'page',
944
			'jetpack-portfolio',
945
			'jetpack-testimonial',
946
		);
947
948
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
949
			return $default_url;
950
		}
951
952
		return Redirect::get_url(
953
			'calypso-edit-' . $post_type,
954
			array(
955
				'path' => $post_id,
956
			)
957
		);
958
	}
959
960
	function point_edit_comment_links_to_calypso( $url ) {
961
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
962
		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...
963
964
		return Redirect::get_url(
965
			'calypso-edit-comment',
966
			array(
967
				'path' => $query_args['amp;c'],
968
			)
969
		);
970
971
	}
972
973
	function jetpack_track_last_sync_callback( $params ) {
974
		/**
975
		 * Filter to turn off jitm caching
976
		 *
977
		 * @since 5.4.0
978
		 *
979
		 * @param bool false Whether to cache just in time messages
980
		 */
981
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
982
			return $params;
983
		}
984
985
		if ( is_array( $params ) && isset( $params[0] ) ) {
986
			$option = $params[0];
987
			if ( 'active_plugins' === $option ) {
988
				// use the cache if we can, but not terribly important if it gets evicted
989
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
990
			}
991
		}
992
993
		return $params;
994
	}
995
996
	function jetpack_connection_banner_callback() {
997
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
998
999
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1000
		if (
1001
			isset( $_REQUEST['dismissBanner'] ) &&
1002
			! Jetpack_Connection_Banner::force_display()
1003
		) {
1004
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1005
			wp_send_json_success();
1006
		}
1007
1008
		wp_die();
1009
	}
1010
1011
	/**
1012
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1013
	 * Only used in our alternate XML-RPC endpoint, where we want to
1014
	 * ensure that Core and other plugins' methods are not exposed.
1015
	 *
1016
	 * @deprecated since 7.7.0
1017
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1018
	 *
1019
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1020
	 * @return array Filtered $methods
1021
	 */
1022 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1023
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1024
1025
		if ( ! $this->connection_manager ) {
1026
			$this->connection_manager = new Connection_Manager();
1027
		}
1028
1029
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1030
	}
1031
1032
	/**
1033
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1034
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1035
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1036
	 * which is accessible via a different URI. Most of the below is copied directly
1037
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1038
	 *
1039
	 * @deprecated since 7.7.0
1040
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1041
	 */
1042 View Code Duplication
	public function alternate_xmlrpc() {
1043
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1044
1045
		if ( ! $this->connection_manager ) {
1046
			$this->connection_manager = new Connection_Manager();
1047
		}
1048
1049
		$this->connection_manager->alternate_xmlrpc();
1050
	}
1051
1052
	/**
1053
	 * The callback for the JITM ajax requests.
1054
	 *
1055
	 * @deprecated since 7.9.0
1056
	 */
1057
	function jetpack_jitm_ajax_callback() {
1058
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1059
	}
1060
1061
	/**
1062
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1063
	 */
1064
	function push_stats() {
1065
		if ( ! empty( $this->stats ) ) {
1066
			$this->do_stats( 'server_side' );
1067
		}
1068
	}
1069
1070
	/**
1071
	 * Sets the Jetpack custom capabilities.
1072
	 *
1073
	 * @param string[] $caps    Array of the user's capabilities.
1074
	 * @param string   $cap     Capability name.
1075
	 * @param int      $user_id The user ID.
1076
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1077
	 */
1078
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1079
		$is_offline_mode = ( new Status() )->is_offline_mode();
1080
		switch ( $cap ) {
1081
			case 'jetpack_manage_modules':
1082
			case 'jetpack_activate_modules':
1083
			case 'jetpack_deactivate_modules':
1084
				$caps = array( 'manage_options' );
1085
				break;
1086
			case 'jetpack_configure_modules':
1087
				$caps = array( 'manage_options' );
1088
				break;
1089
			case 'jetpack_manage_autoupdates':
1090
				$caps = array(
1091
					'manage_options',
1092
					'update_plugins',
1093
				);
1094
				break;
1095
			case 'jetpack_network_admin_page':
1096
			case 'jetpack_network_settings_page':
1097
				$caps = array( 'manage_network_plugins' );
1098
				break;
1099
			case 'jetpack_network_sites_page':
1100
				$caps = array( 'manage_sites' );
1101
				break;
1102
			case 'jetpack_admin_page':
1103
				if ( $is_offline_mode ) {
1104
					$caps = array( 'manage_options' );
1105
					break;
1106
				} else {
1107
					$caps = array( 'read' );
1108
				}
1109
				break;
1110
		}
1111
		return $caps;
1112
	}
1113
1114
	/**
1115
	 * Require a Jetpack authentication.
1116
	 *
1117
	 * @deprecated since 7.7.0
1118
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1119
	 */
1120 View Code Duplication
	public function require_jetpack_authentication() {
1121
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1122
1123
		if ( ! $this->connection_manager ) {
1124
			$this->connection_manager = new Connection_Manager();
1125
		}
1126
1127
		$this->connection_manager->require_jetpack_authentication();
1128
	}
1129
1130
	/**
1131
	 * Register assets for use in various modules and the Jetpack admin page.
1132
	 *
1133
	 * @uses wp_script_is, wp_register_script, plugins_url
1134
	 * @action wp_loaded
1135
	 * @return null
1136
	 */
1137
	public function register_assets() {
1138 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1139
			wp_register_script(
1140
				'jetpack-gallery-settings',
1141
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1142
				array( 'media-views' ),
1143
				'20121225'
1144
			);
1145
		}
1146
1147
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1148
			wp_register_script(
1149
				'jetpack-twitter-timeline',
1150
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1151
				array( 'jquery' ),
1152
				'4.0.0',
1153
				true
1154
			);
1155
		}
1156
1157
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1158
			wp_register_script(
1159
				'jetpack-facebook-embed',
1160
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1161
				array(),
1162
				null,
1163
				true
1164
			);
1165
1166
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1167
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1168
			if ( ! is_numeric( $fb_app_id ) ) {
1169
				$fb_app_id = '';
1170
			}
1171
			wp_localize_script(
1172
				'jetpack-facebook-embed',
1173
				'jpfbembed',
1174
				array(
1175
					'appid'  => $fb_app_id,
1176
					'locale' => $this->get_locale(),
1177
				)
1178
			);
1179
		}
1180
1181
		/**
1182
		 * As jetpack_register_genericons is by default fired off a hook,
1183
		 * the hook may have already fired by this point.
1184
		 * So, let's just trigger it manually.
1185
		 */
1186
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1187
		jetpack_register_genericons();
1188
1189
		/**
1190
		 * Register the social logos
1191
		 */
1192
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1193
		jetpack_register_social_logos();
1194
1195 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1196
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1197
		}
1198
	}
1199
1200
	/**
1201
	 * Guess locale from language code.
1202
	 *
1203
	 * @param string $lang Language code.
1204
	 * @return string|bool
1205
	 */
1206 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1207
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1208
			return 'en_US';
1209
		}
1210
1211
		if ( ! class_exists( 'GP_Locales' ) ) {
1212
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1213
				return false;
1214
			}
1215
1216
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1217
		}
1218
1219
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1220
			// WP.com: get_locale() returns 'it'
1221
			$locale = GP_Locales::by_slug( $lang );
1222
		} else {
1223
			// Jetpack: get_locale() returns 'it_IT';
1224
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1225
		}
1226
1227
		if ( ! $locale ) {
1228
			return false;
1229
		}
1230
1231
		if ( empty( $locale->facebook_locale ) ) {
1232
			if ( empty( $locale->wp_locale ) ) {
1233
				return false;
1234
			} else {
1235
				// Facebook SDK is smart enough to fall back to en_US if a
1236
				// locale isn't supported. Since supported Facebook locales
1237
				// can fall out of sync, we'll attempt to use the known
1238
				// wp_locale value and rely on said fallback.
1239
				return $locale->wp_locale;
1240
			}
1241
		}
1242
1243
		return $locale->facebook_locale;
1244
	}
1245
1246
	/**
1247
	 * Get the locale.
1248
	 *
1249
	 * @return string|bool
1250
	 */
1251
	function get_locale() {
1252
		$locale = $this->guess_locale_from_lang( get_locale() );
1253
1254
		if ( ! $locale ) {
1255
			$locale = 'en_US';
1256
		}
1257
1258
		return $locale;
1259
	}
1260
1261
	/**
1262
	 * Return the network_site_url so that .com knows what network this site is a part of.
1263
	 *
1264
	 * @param  bool $option
1265
	 * @return string
1266
	 */
1267
	public function jetpack_main_network_site_option( $option ) {
1268
		return network_site_url();
1269
	}
1270
	/**
1271
	 * Network Name.
1272
	 */
1273
	static function network_name( $option = null ) {
1274
		global $current_site;
1275
		return $current_site->site_name;
1276
	}
1277
	/**
1278
	 * Does the network allow new user and site registrations.
1279
	 *
1280
	 * @return string
1281
	 */
1282
	static function network_allow_new_registrations( $option = null ) {
1283
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1284
	}
1285
	/**
1286
	 * Does the network allow admins to add new users.
1287
	 *
1288
	 * @return boolian
1289
	 */
1290
	static function network_add_new_users( $option = null ) {
1291
		return (bool) get_site_option( 'add_new_users' );
1292
	}
1293
	/**
1294
	 * File upload psace left per site in MB.
1295
	 *  -1 means NO LIMIT.
1296
	 *
1297
	 * @return number
1298
	 */
1299
	static function network_site_upload_space( $option = null ) {
1300
		// value in MB
1301
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1302
	}
1303
1304
	/**
1305
	 * Network allowed file types.
1306
	 *
1307
	 * @return string
1308
	 */
1309
	static function network_upload_file_types( $option = null ) {
1310
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1311
	}
1312
1313
	/**
1314
	 * Maximum file upload size set by the network.
1315
	 *
1316
	 * @return number
1317
	 */
1318
	static function network_max_upload_file_size( $option = null ) {
1319
		// value in KB
1320
		return get_site_option( 'fileupload_maxk', 300 );
1321
	}
1322
1323
	/**
1324
	 * Lets us know if a site allows admins to manage the network.
1325
	 *
1326
	 * @return array
1327
	 */
1328
	static function network_enable_administration_menus( $option = null ) {
1329
		return get_site_option( 'menu_items' );
1330
	}
1331
1332
	/**
1333
	 * If a user has been promoted to or demoted from admin, we need to clear the
1334
	 * jetpack_other_linked_admins transient.
1335
	 *
1336
	 * @since 4.3.2
1337
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1338
	 *
1339
	 * @param int    $user_id   The user ID whose role changed.
1340
	 * @param string $role      The new role.
1341
	 * @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...
1342
	 */
1343
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1344
		if ( 'administrator' == $role
1345
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1346
			|| is_null( $old_roles )
1347
		) {
1348
			delete_transient( 'jetpack_other_linked_admins' );
1349
		}
1350
	}
1351
1352
	/**
1353
	 * Checks to see if there are any other users available to become primary
1354
	 * Users must both:
1355
	 * - Be linked to wpcom
1356
	 * - Be an admin
1357
	 *
1358
	 * @return mixed False if no other users are linked, Int if there are.
1359
	 */
1360
	static function get_other_linked_admins() {
1361
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1362
1363
		if ( false === $other_linked_users ) {
1364
			$admins = get_users( array( 'role' => 'administrator' ) );
1365
			if ( count( $admins ) > 1 ) {
1366
				$available = array();
1367
				foreach ( $admins as $admin ) {
1368
					if ( self::is_user_connected( $admin->ID ) ) {
1369
						$available[] = $admin->ID;
1370
					}
1371
				}
1372
1373
				$count_connected_admins = count( $available );
1374
				if ( count( $available ) > 1 ) {
1375
					$other_linked_users = $count_connected_admins;
1376
				} else {
1377
					$other_linked_users = 0;
1378
				}
1379
			} else {
1380
				$other_linked_users = 0;
1381
			}
1382
1383
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1384
		}
1385
1386
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1387
	}
1388
1389
	/**
1390
	 * Return whether we are dealing with a multi network setup or not.
1391
	 * The reason we are type casting this is because we want to avoid the situation where
1392
	 * the result is false since when is_main_network_option return false it cases
1393
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1394
	 * database which could be set to anything as opposed to what this function returns.
1395
	 *
1396
	 * @param  bool $option
1397
	 *
1398
	 * @return boolean
1399
	 */
1400
	public function is_main_network_option( $option ) {
1401
		// return '1' or ''
1402
		return (string) (bool) self::is_multi_network();
1403
	}
1404
1405
	/**
1406
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1407
	 *
1408
	 * @param  string $option
1409
	 * @return boolean
1410
	 */
1411
	public function is_multisite( $option ) {
1412
		return (string) (bool) is_multisite();
1413
	}
1414
1415
	/**
1416
	 * Implemented since there is no core is multi network function
1417
	 * Right now there is no way to tell if we which network is the dominant network on the system
1418
	 *
1419
	 * @since  3.3
1420
	 * @return boolean
1421
	 */
1422 View Code Duplication
	public static function is_multi_network() {
1423
		global  $wpdb;
1424
1425
		// if we don't have a multi site setup no need to do any more
1426
		if ( ! is_multisite() ) {
1427
			return false;
1428
		}
1429
1430
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1431
		if ( $num_sites > 1 ) {
1432
			return true;
1433
		} else {
1434
			return false;
1435
		}
1436
	}
1437
1438
	/**
1439
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1440
	 *
1441
	 * @return null
1442
	 */
1443
	function update_jetpack_main_network_site_option() {
1444
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1445
	}
1446
	/**
1447
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1448
	 */
1449
	function update_jetpack_network_settings() {
1450
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1451
		// Only sync this info for the main network site.
1452
	}
1453
1454
	/**
1455
	 * Get back if the current site is single user site.
1456
	 *
1457
	 * @return bool
1458
	 */
1459 View Code Duplication
	public static function is_single_user_site() {
1460
		global $wpdb;
1461
1462
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1463
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1464
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1465
		}
1466
		return 1 === (int) $some_users;
1467
	}
1468
1469
	/**
1470
	 * Returns true if the site has file write access false otherwise.
1471
	 *
1472
	 * @return string ( '1' | '0' )
1473
	 **/
1474
	public static function file_system_write_access() {
1475
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1476
			require_once ABSPATH . 'wp-admin/includes/file.php';
1477
		}
1478
1479
		require_once ABSPATH . 'wp-admin/includes/template.php';
1480
1481
		$filesystem_method = get_filesystem_method();
1482
		if ( $filesystem_method === 'direct' ) {
1483
			return 1;
1484
		}
1485
1486
		ob_start();
1487
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1488
		ob_end_clean();
1489
		if ( $filesystem_credentials_are_stored ) {
1490
			return 1;
1491
		}
1492
		return 0;
1493
	}
1494
1495
	/**
1496
	 * Finds out if a site is using a version control system.
1497
	 *
1498
	 * @return string ( '1' | '0' )
1499
	 **/
1500
	public static function is_version_controlled() {
1501
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1502
		return (string) (int) Functions::is_version_controlled();
1503
	}
1504
1505
	/**
1506
	 * Determines whether the current theme supports featured images or not.
1507
	 *
1508
	 * @return string ( '1' | '0' )
1509
	 */
1510
	public static function featured_images_enabled() {
1511
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1512
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1513
	}
1514
1515
	/**
1516
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1517
	 *
1518
	 * @deprecated 4.7 use get_avatar_url instead.
1519
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1520
	 * @param int               $size Size of the avatar image
1521
	 * @param string            $default URL to a default image to use if no avatar is available
1522
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1523
	 *
1524
	 * @return array
1525
	 */
1526
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1527
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1528
		return get_avatar_url(
1529
			$id_or_email,
1530
			array(
1531
				'size'          => $size,
1532
				'default'       => $default,
1533
				'force_default' => $force_display,
1534
			)
1535
		);
1536
	}
1537
1538
	/**
1539
	 * jetpack_updates is saved in the following schema:
1540
	 *
1541
	 * array (
1542
	 *      'plugins'                       => (int) Number of plugin updates available.
1543
	 *      'themes'                        => (int) Number of theme updates available.
1544
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1545
	 *      'translations'                  => (int) Number of translation updates available.
1546
	 *      'total'                         => (int) Total of all available updates.
1547
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1548
	 * )
1549
	 *
1550
	 * @return array
1551
	 */
1552
	public static function get_updates() {
1553
		$update_data = wp_get_update_data();
1554
1555
		// Stores the individual update counts as well as the total count.
1556
		if ( isset( $update_data['counts'] ) ) {
1557
			$updates = $update_data['counts'];
1558
		}
1559
1560
		// If we need to update WordPress core, let's find the latest version number.
1561 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1562
			$cur = get_preferred_from_update_core();
1563
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1564
				$updates['wp_update_version'] = $cur->current;
1565
			}
1566
		}
1567
		return isset( $updates ) ? $updates : array();
1568
	}
1569
1570
	public static function get_update_details() {
1571
		$update_details = array(
1572
			'update_core'    => get_site_transient( 'update_core' ),
1573
			'update_plugins' => get_site_transient( 'update_plugins' ),
1574
			'update_themes'  => get_site_transient( 'update_themes' ),
1575
		);
1576
		return $update_details;
1577
	}
1578
1579
	public static function refresh_update_data() {
1580
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1581
1582
	}
1583
1584
	public static function refresh_theme_data() {
1585
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1586
	}
1587
1588
	/**
1589
	 * Is Jetpack active?
1590
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1591
	 *
1592
	 * @return bool
1593
	 */
1594
	public static function is_active() {
1595
		return self::connection()->is_active();
1596
	}
1597
1598
	/**
1599
	 * Make an API call to WordPress.com for plan status
1600
	 *
1601
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1602
	 *
1603
	 * @return bool True if plan is updated, false if no update
1604
	 */
1605
	public static function refresh_active_plan_from_wpcom() {
1606
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1607
		return Jetpack_Plan::refresh_from_wpcom();
1608
	}
1609
1610
	/**
1611
	 * Get the plan that this Jetpack site is currently using
1612
	 *
1613
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1614
	 * @return array Active Jetpack plan details.
1615
	 */
1616
	public static function get_active_plan() {
1617
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1618
		return Jetpack_Plan::get();
1619
	}
1620
1621
	/**
1622
	 * Determine whether the active plan supports a particular feature
1623
	 *
1624
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1625
	 * @return bool True if plan supports feature, false if not.
1626
	 */
1627
	public static function active_plan_supports( $feature ) {
1628
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1629
		return Jetpack_Plan::supports( $feature );
1630
	}
1631
1632
	/**
1633
	 * Deprecated: Is Jetpack in development (offline) mode?
1634
	 *
1635
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1636
	 * and themes still use it, and we do not want to flood them with notices.
1637
	 *
1638
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1639
	 *
1640
	 * @deprecated since 8.0.
1641
	 */
1642
	public static function is_development_mode() {
1643
		return ( new Status() )->is_offline_mode();
1644
	}
1645
1646
	/**
1647
	 * Whether the site is currently onboarding or not.
1648
	 * A site is considered as being onboarded if it currently has an onboarding token.
1649
	 *
1650
	 * @since 5.8
1651
	 *
1652
	 * @access public
1653
	 * @static
1654
	 *
1655
	 * @return bool True if the site is currently onboarding, false otherwise
1656
	 */
1657
	public static function is_onboarding() {
1658
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1659
	}
1660
1661
	/**
1662
	 * Determines reason for Jetpack offline mode.
1663
	 */
1664
	public static function development_mode_trigger_text() {
1665
		$status = new Status();
1666
1667
		if ( ! $status->is_offline_mode() ) {
1668
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1669
		}
1670
1671
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1672
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1673
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1674
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1675
		} elseif ( $status->is_local_site() ) {
1676
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1677
			/** This filter is documented in packages/status/src/class-status.php */
1678
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1679
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1680
		} else {
1681
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1682
		}
1683
1684
		return $notice;
1685
1686
	}
1687
	/**
1688
	 * Get Jetpack offline mode notice text and notice class.
1689
	 *
1690
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1691
	 */
1692
	public static function show_development_mode_notice() {
1693 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1694
			$notice = sprintf(
1695
				/* translators: %s is a URL */
1696
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1697
				Redirect::get_url( 'jetpack-support-development-mode' )
1698
			);
1699
1700
			$notice .= ' ' . self::development_mode_trigger_text();
1701
1702
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1703
		}
1704
1705
		// Throw up a notice if using a development version and as for feedback.
1706
		if ( self::is_development_version() ) {
1707
			/* translators: %s is a URL */
1708
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1709
1710
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1711
		}
1712
		// Throw up a notice if using staging mode
1713 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1714
			/* translators: %s is a URL */
1715
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1716
1717
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1718
		}
1719
	}
1720
1721
	/**
1722
	 * Whether Jetpack's version maps to a public release, or a development version.
1723
	 */
1724
	public static function is_development_version() {
1725
		/**
1726
		 * Allows filtering whether this is a development version of Jetpack.
1727
		 *
1728
		 * This filter is especially useful for tests.
1729
		 *
1730
		 * @since 4.3.0
1731
		 *
1732
		 * @param bool $development_version Is this a develoment version of Jetpack?
1733
		 */
1734
		return (bool) apply_filters(
1735
			'jetpack_development_version',
1736
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1737
		);
1738
	}
1739
1740
	/**
1741
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1742
	 */
1743
	public static function is_user_connected( $user_id = false ) {
1744
		return self::connection()->is_user_connected( $user_id );
1745
	}
1746
1747
	/**
1748
	 * Get the wpcom user data of the current|specified connected user.
1749
	 */
1750 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1751
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1752
		if ( ! $user_id ) {
1753
			$user_id = get_current_user_id();
1754
		}
1755
1756
		$transient_key = "jetpack_connected_user_data_$user_id";
1757
1758
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1759
			return $cached_user_data;
1760
		}
1761
1762
		$xml = new Jetpack_IXR_Client(
1763
			array(
1764
				'user_id' => $user_id,
1765
			)
1766
		);
1767
		$xml->query( 'wpcom.getUser' );
1768
		if ( ! $xml->isError() ) {
1769
			$user_data = $xml->getResponse();
1770
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1771
			return $user_data;
1772
		}
1773
1774
		return false;
1775
	}
1776
1777
	/**
1778
	 * Get the wpcom email of the current|specified connected user.
1779
	 */
1780
	public static function get_connected_user_email( $user_id = null ) {
1781
		if ( ! $user_id ) {
1782
			$user_id = get_current_user_id();
1783
		}
1784
1785
		$xml = new Jetpack_IXR_Client(
1786
			array(
1787
				'user_id' => $user_id,
1788
			)
1789
		);
1790
		$xml->query( 'wpcom.getUserEmail' );
1791
		if ( ! $xml->isError() ) {
1792
			return $xml->getResponse();
1793
		}
1794
		return false;
1795
	}
1796
1797
	/**
1798
	 * Get the wpcom email of the master user.
1799
	 */
1800
	public static function get_master_user_email() {
1801
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1802
		if ( $master_user_id ) {
1803
			return self::get_connected_user_email( $master_user_id );
1804
		}
1805
		return '';
1806
	}
1807
1808
	/**
1809
	 * Whether the current user is the connection owner.
1810
	 *
1811
	 * @deprecated since 7.7
1812
	 *
1813
	 * @return bool Whether the current user is the connection owner.
1814
	 */
1815
	public function current_user_is_connection_owner() {
1816
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1817
		return self::connection()->is_connection_owner();
1818
	}
1819
1820
	/**
1821
	 * Gets current user IP address.
1822
	 *
1823
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1824
	 *
1825
	 * @return string                  Current user IP address.
1826
	 */
1827
	public static function current_user_ip( $check_all_headers = false ) {
1828
		if ( $check_all_headers ) {
1829
			foreach ( array(
1830
				'HTTP_CF_CONNECTING_IP',
1831
				'HTTP_CLIENT_IP',
1832
				'HTTP_X_FORWARDED_FOR',
1833
				'HTTP_X_FORWARDED',
1834
				'HTTP_X_CLUSTER_CLIENT_IP',
1835
				'HTTP_FORWARDED_FOR',
1836
				'HTTP_FORWARDED',
1837
				'HTTP_VIA',
1838
			) as $key ) {
1839
				if ( ! empty( $_SERVER[ $key ] ) ) {
1840
					return $_SERVER[ $key ];
1841
				}
1842
			}
1843
		}
1844
1845
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1846
	}
1847
1848
	/**
1849
	 * Synchronize connected user role changes
1850
	 */
1851
	function user_role_change( $user_id ) {
1852
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1853
		Users::user_role_change( $user_id );
1854
	}
1855
1856
	/**
1857
	 * Loads the currently active modules.
1858
	 */
1859
	public static function load_modules() {
1860
		$is_offline_mode = ( new Status() )->is_offline_mode();
1861
		if (
1862
			! self::is_active()
1863
			&& ! $is_offline_mode
1864
			&& ! self::is_onboarding()
1865
			&& (
1866
				! is_multisite()
1867
				|| ! get_site_option( 'jetpack_protect_active' )
1868
			)
1869
		) {
1870
			return;
1871
		}
1872
1873
		$version = Jetpack_Options::get_option( 'version' );
1874 View Code Duplication
		if ( ! $version ) {
1875
			$version = $old_version = JETPACK__VERSION . ':' . time();
1876
			/** This action is documented in class.jetpack.php */
1877
			do_action( 'updating_jetpack_version', $version, false );
1878
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1879
		}
1880
		list( $version ) = explode( ':', $version );
1881
1882
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1883
1884
		$modules_data = array();
1885
1886
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1887
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1888
			$updated_modules = array();
1889
			foreach ( $modules as $module ) {
1890
				$modules_data[ $module ] = self::get_module( $module );
1891
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1892
					continue;
1893
				}
1894
1895
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1896
					continue;
1897
				}
1898
1899
				$updated_modules[] = $module;
1900
			}
1901
1902
			$modules = array_diff( $modules, $updated_modules );
1903
		}
1904
1905
		foreach ( $modules as $index => $module ) {
1906
			// If we're in offline mode, disable modules requiring a connection.
1907
			if ( $is_offline_mode ) {
1908
				// Prime the pump if we need to
1909
				if ( empty( $modules_data[ $module ] ) ) {
1910
					$modules_data[ $module ] = self::get_module( $module );
1911
				}
1912
				// If the module requires a connection, but we're in local mode, don't include it.
1913
				if ( $modules_data[ $module ]['requires_connection'] ) {
1914
					continue;
1915
				}
1916
			}
1917
1918
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1919
				continue;
1920
			}
1921
1922
			if ( ! include_once self::get_module_path( $module ) ) {
1923
				unset( $modules[ $index ] );
1924
				self::update_active_modules( array_values( $modules ) );
1925
				continue;
1926
			}
1927
1928
			/**
1929
			 * Fires when a specific module is loaded.
1930
			 * The dynamic part of the hook, $module, is the module slug.
1931
			 *
1932
			 * @since 1.1.0
1933
			 */
1934
			do_action( 'jetpack_module_loaded_' . $module );
1935
		}
1936
1937
		/**
1938
		 * Fires when all the modules are loaded.
1939
		 *
1940
		 * @since 1.1.0
1941
		 */
1942
		do_action( 'jetpack_modules_loaded' );
1943
1944
		// Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
1945
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1946
	}
1947
1948
	/**
1949
	 * Check if Jetpack's REST API compat file should be included
1950
	 *
1951
	 * @action plugins_loaded
1952
	 * @return null
1953
	 */
1954
	public function check_rest_api_compat() {
1955
		/**
1956
		 * Filters the list of REST API compat files to be included.
1957
		 *
1958
		 * @since 2.2.5
1959
		 *
1960
		 * @param array $args Array of REST API compat files to include.
1961
		 */
1962
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1963
1964
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1965
			require_once $_jetpack_rest_api_compat_include;
1966
		}
1967
	}
1968
1969
	/**
1970
	 * Gets all plugins currently active in values, regardless of whether they're
1971
	 * traditionally activated or network activated.
1972
	 *
1973
	 * @todo Store the result in core's object cache maybe?
1974
	 */
1975
	public static function get_active_plugins() {
1976
		$active_plugins = (array) get_option( 'active_plugins', array() );
1977
1978
		if ( is_multisite() ) {
1979
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1980
			// whereas active_plugins stores them in the values.
1981
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1982
			if ( $network_plugins ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $network_plugins of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1983
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1984
			}
1985
		}
1986
1987
		sort( $active_plugins );
1988
1989
		return array_unique( $active_plugins );
1990
	}
1991
1992
	/**
1993
	 * Gets and parses additional plugin data to send with the heartbeat data
1994
	 *
1995
	 * @since 3.8.1
1996
	 *
1997
	 * @return array Array of plugin data
1998
	 */
1999
	public static function get_parsed_plugin_data() {
2000
		if ( ! function_exists( 'get_plugins' ) ) {
2001
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2002
		}
2003
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2004
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2005
		$active_plugins = self::get_active_plugins();
2006
2007
		$plugins = array();
2008
		foreach ( $all_plugins as $path => $plugin_data ) {
2009
			$plugins[ $path ] = array(
2010
				'is_active' => in_array( $path, $active_plugins ),
2011
				'file'      => $path,
2012
				'name'      => $plugin_data['Name'],
2013
				'version'   => $plugin_data['Version'],
2014
				'author'    => $plugin_data['Author'],
2015
			);
2016
		}
2017
2018
		return $plugins;
2019
	}
2020
2021
	/**
2022
	 * Gets and parses theme data to send with the heartbeat data
2023
	 *
2024
	 * @since 3.8.1
2025
	 *
2026
	 * @return array Array of theme data
2027
	 */
2028
	public static function get_parsed_theme_data() {
2029
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2030
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2031
2032
		$themes = array();
2033
		foreach ( $all_themes as $slug => $theme_data ) {
2034
			$theme_headers = array();
2035
			foreach ( $header_keys as $header_key ) {
2036
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2037
			}
2038
2039
			$themes[ $slug ] = array(
2040
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2041
				'slug'            => $slug,
2042
				'theme_root'      => $theme_data->get_theme_root_uri(),
2043
				'parent'          => $theme_data->parent(),
2044
				'headers'         => $theme_headers,
2045
			);
2046
		}
2047
2048
		return $themes;
2049
	}
2050
2051
	/**
2052
	 * Checks whether a specific plugin is active.
2053
	 *
2054
	 * We don't want to store these in a static variable, in case
2055
	 * there are switch_to_blog() calls involved.
2056
	 */
2057
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2058
		return in_array( $plugin, self::get_active_plugins() );
2059
	}
2060
2061
	/**
2062
	 * Check if Jetpack's Open Graph tags should be used.
2063
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2064
	 *
2065
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2066
	 * @action plugins_loaded
2067
	 * @return null
2068
	 */
2069
	public function check_open_graph() {
2070
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2071
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2072
		}
2073
2074
		$active_plugins = self::get_active_plugins();
2075
2076
		if ( ! empty( $active_plugins ) ) {
2077
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2078
				if ( in_array( $plugin, $active_plugins ) ) {
2079
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2080
					break;
2081
				}
2082
			}
2083
		}
2084
2085
		/**
2086
		 * Allow the addition of Open Graph Meta Tags to all pages.
2087
		 *
2088
		 * @since 2.0.3
2089
		 *
2090
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2091
		 */
2092
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2093
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2094
		}
2095
	}
2096
2097
	/**
2098
	 * Check if Jetpack's Twitter tags should be used.
2099
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2100
	 *
2101
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2102
	 * @action plugins_loaded
2103
	 * @return null
2104
	 */
2105
	public function check_twitter_tags() {
2106
2107
		$active_plugins = self::get_active_plugins();
2108
2109
		if ( ! empty( $active_plugins ) ) {
2110
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2111
				if ( in_array( $plugin, $active_plugins ) ) {
2112
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2113
					break;
2114
				}
2115
			}
2116
		}
2117
2118
		/**
2119
		 * Allow Twitter Card Meta tags to be disabled.
2120
		 *
2121
		 * @since 2.6.0
2122
		 *
2123
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2124
		 */
2125
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2126
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2127
		}
2128
	}
2129
2130
	/**
2131
	 * Allows plugins to submit security reports.
2132
	 *
2133
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2134
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2135
	 * @param array  $args         See definitions above
2136
	 */
2137
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2138
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2139
	}
2140
2141
	/* Jetpack Options API */
2142
2143
	public static function get_option_names( $type = 'compact' ) {
2144
		return Jetpack_Options::get_option_names( $type );
2145
	}
2146
2147
	/**
2148
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2149
	 *
2150
	 * @param string $name    Option name
2151
	 * @param mixed  $default (optional)
2152
	 */
2153
	public static function get_option( $name, $default = false ) {
2154
		return Jetpack_Options::get_option( $name, $default );
2155
	}
2156
2157
	/**
2158
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2159
	 *
2160
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2161
	 * @param string $name  Option name
2162
	 * @param mixed  $value Option value
2163
	 */
2164
	public static function update_option( $name, $value ) {
2165
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2166
		return Jetpack_Options::update_option( $name, $value );
2167
	}
2168
2169
	/**
2170
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2171
	 *
2172
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2173
	 * @param array $array array( option name => option value, ... )
2174
	 */
2175
	public static function update_options( $array ) {
2176
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2177
		return Jetpack_Options::update_options( $array );
2178
	}
2179
2180
	/**
2181
	 * Deletes the given option.  May be passed multiple option names as an array.
2182
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2183
	 *
2184
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2185
	 * @param string|array $names
2186
	 */
2187
	public static function delete_option( $names ) {
2188
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2189
		return Jetpack_Options::delete_option( $names );
2190
	}
2191
2192
	/**
2193
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2194
	 *
2195
	 * Enters a user token into the user_tokens option
2196
	 *
2197
	 * @param int    $user_id The user id.
2198
	 * @param string $token The user token.
2199
	 * @param bool   $is_master_user Whether the user is the master user.
2200
	 * @return bool
2201
	 */
2202
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2203
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2204
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2205
	}
2206
2207
	/**
2208
	 * Returns an array of all PHP files in the specified absolute path.
2209
	 * Equivalent to glob( "$absolute_path/*.php" ).
2210
	 *
2211
	 * @param string $absolute_path The absolute path of the directory to search.
2212
	 * @return array Array of absolute paths to the PHP files.
2213
	 */
2214
	public static function glob_php( $absolute_path ) {
2215
		if ( function_exists( 'glob' ) ) {
2216
			return glob( "$absolute_path/*.php" );
2217
		}
2218
2219
		$absolute_path = untrailingslashit( $absolute_path );
2220
		$files         = array();
2221
		if ( ! $dir = @opendir( $absolute_path ) ) {
2222
			return $files;
2223
		}
2224
2225
		while ( false !== $file = readdir( $dir ) ) {
2226
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2227
				continue;
2228
			}
2229
2230
			$file = "$absolute_path/$file";
2231
2232
			if ( ! is_file( $file ) ) {
2233
				continue;
2234
			}
2235
2236
			$files[] = $file;
2237
		}
2238
2239
		closedir( $dir );
2240
2241
		return $files;
2242
	}
2243
2244
	public static function activate_new_modules( $redirect = false ) {
2245
		if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
2246
			return;
2247
		}
2248
2249
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2250 View Code Duplication
		if ( ! $jetpack_old_version ) {
2251
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2252
			/** This action is documented in class.jetpack.php */
2253
			do_action( 'updating_jetpack_version', $version, false );
2254
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2255
		}
2256
2257
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2258
2259
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2260
			return;
2261
		}
2262
2263
		$active_modules     = self::get_active_modules();
2264
		$reactivate_modules = array();
2265
		foreach ( $active_modules as $active_module ) {
2266
			$module = self::get_module( $active_module );
2267
			if ( ! isset( $module['changed'] ) ) {
2268
				continue;
2269
			}
2270
2271
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2272
				continue;
2273
			}
2274
2275
			$reactivate_modules[] = $active_module;
2276
			self::deactivate_module( $active_module );
2277
		}
2278
2279
		$new_version = JETPACK__VERSION . ':' . time();
2280
		/** This action is documented in class.jetpack.php */
2281
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2282
		Jetpack_Options::update_options(
2283
			array(
2284
				'version'     => $new_version,
2285
				'old_version' => $jetpack_old_version,
2286
			)
2287
		);
2288
2289
		self::state( 'message', 'modules_activated' );
2290
2291
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2292
2293
		if ( $redirect ) {
2294
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2295
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2296
				$page = $_GET['page'];
2297
			}
2298
2299
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2300
			exit;
2301
		}
2302
	}
2303
2304
	/**
2305
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2306
	 * Make sure to tuck away module "library" files in a sub-directory.
2307
	 */
2308
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2309
		static $modules = null;
2310
2311
		if ( ! isset( $modules ) ) {
2312
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2313
			// Use the cache if we're on the front-end and it's available...
2314
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2315
				$modules = $available_modules_option[ JETPACK__VERSION ];
2316
			} else {
2317
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2318
2319
				$modules = array();
2320
2321
				foreach ( $files as $file ) {
2322
					if ( ! $headers = self::get_module( $file ) ) {
2323
						continue;
2324
					}
2325
2326
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2327
				}
2328
2329
				Jetpack_Options::update_option(
2330
					'available_modules',
2331
					array(
2332
						JETPACK__VERSION => $modules,
2333
					)
2334
				);
2335
			}
2336
		}
2337
2338
		/**
2339
		 * Filters the array of modules available to be activated.
2340
		 *
2341
		 * @since 2.4.0
2342
		 *
2343
		 * @param array $modules Array of available modules.
2344
		 * @param string $min_version Minimum version number required to use modules.
2345
		 * @param string $max_version Maximum version number required to use modules.
2346
		 */
2347
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2348
2349
		if ( ! $min_version && ! $max_version ) {
2350
			return array_keys( $mods );
2351
		}
2352
2353
		$r = array();
2354
		foreach ( $mods as $slug => $introduced ) {
2355
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2356
				continue;
2357
			}
2358
2359
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2360
				continue;
2361
			}
2362
2363
			$r[] = $slug;
2364
		}
2365
2366
		return $r;
2367
	}
2368
2369
	/**
2370
	 * Default modules loaded on activation.
2371
	 */
2372
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2373
		$return = array();
2374
2375
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2376
			$module_data = self::get_module( $module );
2377
2378
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2379
				case 'yes':
2380
					$return[] = $module;
2381
					break;
2382
				case 'public':
2383
					if ( Jetpack_Options::get_option( 'public' ) ) {
2384
						$return[] = $module;
2385
					}
2386
					break;
2387
				case 'no':
2388
				default:
2389
					break;
2390
			}
2391
		}
2392
		/**
2393
		 * Filters the array of default modules.
2394
		 *
2395
		 * @since 2.5.0
2396
		 *
2397
		 * @param array $return Array of default modules.
2398
		 * @param string $min_version Minimum version number required to use modules.
2399
		 * @param string $max_version Maximum version number required to use modules.
2400
		 */
2401
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2402
	}
2403
2404
	/**
2405
	 * Checks activated modules during auto-activation to determine
2406
	 * if any of those modules are being deprecated.  If so, close
2407
	 * them out, and add any replacement modules.
2408
	 *
2409
	 * Runs at priority 99 by default.
2410
	 *
2411
	 * This is run late, so that it can still activate a module if
2412
	 * the new module is a replacement for another that the user
2413
	 * currently has active, even if something at the normal priority
2414
	 * would kibosh everything.
2415
	 *
2416
	 * @since 2.6
2417
	 * @uses jetpack_get_default_modules filter
2418
	 * @param array $modules
2419
	 * @return array
2420
	 */
2421
	function handle_deprecated_modules( $modules ) {
2422
		$deprecated_modules = array(
2423
			'debug'            => null,  // Closed out and moved to the debugger library.
2424
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2425
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2426
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2427
		);
2428
2429
		// Don't activate SSO if they never completed activating WPCC.
2430
		if ( self::is_module_active( 'wpcc' ) ) {
2431
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2432
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2433
				$deprecated_modules['wpcc'] = null;
2434
			}
2435
		}
2436
2437
		foreach ( $deprecated_modules as $module => $replacement ) {
2438
			if ( self::is_module_active( $module ) ) {
2439
				self::deactivate_module( $module );
2440
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2441
					$modules[] = $replacement;
2442
				}
2443
			}
2444
		}
2445
2446
		return array_unique( $modules );
2447
	}
2448
2449
	/**
2450
	 * Checks activated plugins during auto-activation to determine
2451
	 * if any of those plugins are in the list with a corresponding module
2452
	 * that is not compatible with the plugin. The module will not be allowed
2453
	 * to auto-activate.
2454
	 *
2455
	 * @since 2.6
2456
	 * @uses jetpack_get_default_modules filter
2457
	 * @param array $modules
2458
	 * @return array
2459
	 */
2460
	function filter_default_modules( $modules ) {
2461
2462
		$active_plugins = self::get_active_plugins();
2463
2464
		if ( ! empty( $active_plugins ) ) {
2465
2466
			// For each module we'd like to auto-activate...
2467
			foreach ( $modules as $key => $module ) {
2468
				// If there are potential conflicts for it...
2469
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2470
					// For each potential conflict...
2471
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2472
						// If that conflicting plugin is active...
2473
						if ( in_array( $plugin, $active_plugins ) ) {
2474
							// Remove that item from being auto-activated.
2475
							unset( $modules[ $key ] );
2476
						}
2477
					}
2478
				}
2479
			}
2480
		}
2481
2482
		return $modules;
2483
	}
2484
2485
	/**
2486
	 * Extract a module's slug from its full path.
2487
	 */
2488
	public static function get_module_slug( $file ) {
2489
		return str_replace( '.php', '', basename( $file ) );
2490
	}
2491
2492
	/**
2493
	 * Generate a module's path from its slug.
2494
	 */
2495
	public static function get_module_path( $slug ) {
2496
		/**
2497
		 * Filters the path of a modules.
2498
		 *
2499
		 * @since 7.4.0
2500
		 *
2501
		 * @param array $return The absolute path to a module's root php file
2502
		 * @param string $slug The module slug
2503
		 */
2504
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2505
	}
2506
2507
	/**
2508
	 * Load module data from module file. Headers differ from WordPress
2509
	 * plugin headers to avoid them being identified as standalone
2510
	 * plugins on the WordPress plugins page.
2511
	 */
2512
	public static function get_module( $module ) {
2513
		$headers = array(
2514
			'name'                      => 'Module Name',
2515
			'description'               => 'Module Description',
2516
			'sort'                      => 'Sort Order',
2517
			'recommendation_order'      => 'Recommendation Order',
2518
			'introduced'                => 'First Introduced',
2519
			'changed'                   => 'Major Changes In',
2520
			'deactivate'                => 'Deactivate',
2521
			'free'                      => 'Free',
2522
			'requires_connection'       => 'Requires Connection',
2523
			'auto_activate'             => 'Auto Activate',
2524
			'module_tags'               => 'Module Tags',
2525
			'feature'                   => 'Feature',
2526
			'additional_search_queries' => 'Additional Search Queries',
2527
			'plan_classes'              => 'Plans',
2528
		);
2529
2530
		$file = self::get_module_path( self::get_module_slug( $module ) );
2531
2532
		$mod = self::get_file_data( $file, $headers );
2533
		if ( empty( $mod['name'] ) ) {
2534
			return false;
2535
		}
2536
2537
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2538
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2539
		$mod['deactivate']           = empty( $mod['deactivate'] );
2540
		$mod['free']                 = empty( $mod['free'] );
2541
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2542
2543
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2544
			$mod['auto_activate'] = 'No';
2545
		} else {
2546
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2547
		}
2548
2549
		if ( $mod['module_tags'] ) {
2550
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2551
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2552
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2553
		} else {
2554
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2555
		}
2556
2557 View Code Duplication
		if ( $mod['plan_classes'] ) {
2558
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2559
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2560
		} else {
2561
			$mod['plan_classes'] = array( 'free' );
2562
		}
2563
2564 View Code Duplication
		if ( $mod['feature'] ) {
2565
			$mod['feature'] = explode( ',', $mod['feature'] );
2566
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2567
		} else {
2568
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2569
		}
2570
2571
		/**
2572
		 * Filters the feature array on a module.
2573
		 *
2574
		 * This filter allows you to control where each module is filtered: Recommended,
2575
		 * and the default "Other" listing.
2576
		 *
2577
		 * @since 3.5.0
2578
		 *
2579
		 * @param array   $mod['feature'] The areas to feature this module:
2580
		 *     'Recommended' shows on the main Jetpack admin screen.
2581
		 *     'Other' should be the default if no other value is in the array.
2582
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2583
		 * @param array   $mod All the currently assembled module data.
2584
		 */
2585
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2586
2587
		/**
2588
		 * Filter the returned data about a module.
2589
		 *
2590
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2591
		 * so please be careful.
2592
		 *
2593
		 * @since 3.6.0
2594
		 *
2595
		 * @param array   $mod    The details of the requested module.
2596
		 * @param string  $module The slug of the module, e.g. sharedaddy
2597
		 * @param string  $file   The path to the module source file.
2598
		 */
2599
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
2600
	}
2601
2602
	/**
2603
	 * Like core's get_file_data implementation, but caches the result.
2604
	 */
2605
	public static function get_file_data( $file, $headers ) {
2606
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2607
		$file_name = basename( $file );
2608
2609
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2610
2611
		$file_data_option = get_transient( $cache_key );
2612
2613
		if ( ! is_array( $file_data_option ) ) {
2614
			delete_transient( $cache_key );
2615
			$file_data_option = false;
2616
		}
2617
2618
		if ( false === $file_data_option ) {
2619
			$file_data_option = array();
2620
		}
2621
2622
		$key           = md5( $file_name . serialize( $headers ) );
2623
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2624
2625
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2626
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2627
			return $file_data_option[ $key ];
2628
		}
2629
2630
		$data = get_file_data( $file, $headers );
2631
2632
		$file_data_option[ $key ] = $data;
2633
2634
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2635
2636
		return $data;
2637
	}
2638
2639
2640
	/**
2641
	 * Return translated module tag.
2642
	 *
2643
	 * @param string $tag Tag as it appears in each module heading.
2644
	 *
2645
	 * @return mixed
2646
	 */
2647
	public static function translate_module_tag( $tag ) {
2648
		return jetpack_get_module_i18n_tag( $tag );
2649
	}
2650
2651
	/**
2652
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2653
	 *
2654
	 * @since 3.9.2
2655
	 *
2656
	 * @param array $modules
2657
	 *
2658
	 * @return string|void
2659
	 */
2660
	public static function get_translated_modules( $modules ) {
2661
		foreach ( $modules as $index => $module ) {
2662
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2663
			if ( isset( $module['name'] ) ) {
2664
				$modules[ $index ]['name'] = $i18n_module['name'];
2665
			}
2666
			if ( isset( $module['description'] ) ) {
2667
				$modules[ $index ]['description']       = $i18n_module['description'];
2668
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2669
			}
2670
		}
2671
		return $modules;
2672
	}
2673
2674
	/**
2675
	 * Get a list of activated modules as an array of module slugs.
2676
	 */
2677
	public static function get_active_modules() {
2678
		$active = Jetpack_Options::get_option( 'active_modules' );
2679
2680
		if ( ! is_array( $active ) ) {
2681
			$active = array();
2682
		}
2683
2684
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2685
			$active[] = 'vaultpress';
2686
		} else {
2687
			$active = array_diff( $active, array( 'vaultpress' ) );
2688
		}
2689
2690
		// If protect is active on the main site of a multisite, it should be active on all sites.
2691
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2692
			$active[] = 'protect';
2693
		}
2694
2695
		/**
2696
		 * Allow filtering of the active modules.
2697
		 *
2698
		 * Gives theme and plugin developers the power to alter the modules that
2699
		 * are activated on the fly.
2700
		 *
2701
		 * @since 5.8.0
2702
		 *
2703
		 * @param array $active Array of active module slugs.
2704
		 */
2705
		$active = apply_filters( 'jetpack_active_modules', $active );
2706
2707
		return array_unique( $active );
2708
	}
2709
2710
	/**
2711
	 * Check whether or not a Jetpack module is active.
2712
	 *
2713
	 * @param string $module The slug of a Jetpack module.
2714
	 * @return bool
2715
	 *
2716
	 * @static
2717
	 */
2718
	public static function is_module_active( $module ) {
2719
		return in_array( $module, self::get_active_modules() );
2720
	}
2721
2722
	public static function is_module( $module ) {
2723
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2724
	}
2725
2726
	/**
2727
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2728
	 *
2729
	 * @param bool $catch True to start catching, False to stop.
2730
	 *
2731
	 * @static
2732
	 */
2733
	public static function catch_errors( $catch ) {
2734
		static $display_errors, $error_reporting;
2735
2736
		if ( $catch ) {
2737
			$display_errors  = @ini_set( 'display_errors', 1 );
2738
			$error_reporting = @error_reporting( E_ALL );
2739
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2740
		} else {
2741
			@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...
2742
			@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...
2743
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2744
		}
2745
	}
2746
2747
	/**
2748
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2749
	 */
2750
	public static function catch_errors_on_shutdown() {
2751
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2752
	}
2753
2754
	/**
2755
	 * Rewrite any string to make paths easier to read.
2756
	 *
2757
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2758
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2759
	 *
2760
	 * @param $string
2761
	 * @return mixed
2762
	 */
2763
	public static function alias_directories( $string ) {
2764
		// ABSPATH has a trailing slash.
2765
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2766
		// WP_CONTENT_DIR does not have a trailing slash.
2767
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2768
2769
		return $string;
2770
	}
2771
2772
	public static function activate_default_modules(
2773
		$min_version = false,
2774
		$max_version = false,
2775
		$other_modules = array(),
2776
		$redirect = null,
2777
		$send_state_messages = null
2778
	) {
2779
		$jetpack = self::init();
2780
2781
		if ( is_null( $redirect ) ) {
2782
			if (
2783
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2784
			||
2785
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2786
			||
2787
				( defined( 'WP_CLI' ) && WP_CLI )
2788
			||
2789
				( defined( 'DOING_CRON' ) && DOING_CRON )
2790
			||
2791
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2792
			) {
2793
				$redirect = false;
2794
			} elseif ( is_admin() ) {
2795
				$redirect = true;
2796
			} else {
2797
				$redirect = false;
2798
			}
2799
		}
2800
2801
		if ( is_null( $send_state_messages ) ) {
2802
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2803
		}
2804
2805
		$modules = self::get_default_modules( $min_version, $max_version );
2806
		$modules = array_merge( $other_modules, $modules );
2807
2808
		// Look for standalone plugins and disable if active.
2809
2810
		$to_deactivate = array();
2811
		foreach ( $modules as $module ) {
2812
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2813
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2814
			}
2815
		}
2816
2817
		$deactivated = array();
2818
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2819
			list( $probable_file, $probable_title ) = $deactivate_me;
2820
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2821
				$deactivated[] = $module;
2822
			}
2823
		}
2824
2825
		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...
2826
			if ( $send_state_messages ) {
2827
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2828
			}
2829
2830
			if ( $redirect ) {
2831
				$url = add_query_arg(
2832
					array(
2833
						'action'   => 'activate_default_modules',
2834
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2835
					),
2836
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2837
				);
2838
				wp_safe_redirect( $url );
2839
				exit;
2840
			}
2841
		}
2842
2843
		/**
2844
		 * Fires before default modules are activated.
2845
		 *
2846
		 * @since 1.9.0
2847
		 *
2848
		 * @param string $min_version Minimum version number required to use modules.
2849
		 * @param string $max_version Maximum version number required to use modules.
2850
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2851
		 */
2852
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2853
2854
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2855
		if ( $send_state_messages ) {
2856
			self::restate();
2857
			self::catch_errors( true );
2858
		}
2859
2860
		$active = self::get_active_modules();
2861
2862
		foreach ( $modules as $module ) {
2863
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2864
				$active[] = $module;
2865
				self::update_active_modules( $active );
2866
				continue;
2867
			}
2868
2869
			if ( $send_state_messages && in_array( $module, $active ) ) {
2870
				$module_info = self::get_module( $module );
2871 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2872
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2873
					if ( $active_state = self::state( $state ) ) {
2874
						$active_state = explode( ',', $active_state );
2875
					} else {
2876
						$active_state = array();
2877
					}
2878
					$active_state[] = $module;
2879
					self::state( $state, implode( ',', $active_state ) );
2880
				}
2881
				continue;
2882
			}
2883
2884
			$file = self::get_module_path( $module );
2885
			if ( ! file_exists( $file ) ) {
2886
				continue;
2887
			}
2888
2889
			// we'll override this later if the plugin can be included without fatal error
2890
			if ( $redirect ) {
2891
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2892
			}
2893
2894
			if ( $send_state_messages ) {
2895
				self::state( 'error', 'module_activation_failed' );
2896
				self::state( 'module', $module );
2897
			}
2898
2899
			ob_start();
2900
			require_once $file;
2901
2902
			$active[] = $module;
2903
2904 View Code Duplication
			if ( $send_state_messages ) {
2905
2906
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2907
				if ( $active_state = self::state( $state ) ) {
2908
					$active_state = explode( ',', $active_state );
2909
				} else {
2910
					$active_state = array();
2911
				}
2912
				$active_state[] = $module;
2913
				self::state( $state, implode( ',', $active_state ) );
2914
			}
2915
2916
			self::update_active_modules( $active );
2917
2918
			ob_end_clean();
2919
		}
2920
2921
		if ( $send_state_messages ) {
2922
			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...
2923
			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...
2924
		}
2925
2926
		self::catch_errors( false );
2927
		/**
2928
		 * Fires when default modules are activated.
2929
		 *
2930
		 * @since 1.9.0
2931
		 *
2932
		 * @param string $min_version Minimum version number required to use modules.
2933
		 * @param string $max_version Maximum version number required to use modules.
2934
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2935
		 */
2936
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2937
	}
2938
2939
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2940
		/**
2941
		 * Fires before a module is activated.
2942
		 *
2943
		 * @since 2.6.0
2944
		 *
2945
		 * @param string $module Module slug.
2946
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2947
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2948
		 */
2949
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2950
2951
		$jetpack = self::init();
2952
2953
		if ( ! strlen( $module ) ) {
2954
			return false;
2955
		}
2956
2957
		if ( ! self::is_module( $module ) ) {
2958
			return false;
2959
		}
2960
2961
		// If it's already active, then don't do it again
2962
		$active = self::get_active_modules();
2963
		foreach ( $active as $act ) {
2964
			if ( $act == $module ) {
2965
				return true;
2966
			}
2967
		}
2968
2969
		$module_data = self::get_module( $module );
2970
2971
		$is_offline_mode = ( new Status() )->is_offline_mode();
2972
		if ( ! self::is_active() ) {
2973
			if ( ! $is_offline_mode && ! self::is_onboarding() ) {
2974
				return false;
2975
			}
2976
2977
			// If we're not connected but in offline mode, make sure the module doesn't require a connection.
2978
			if ( $is_offline_mode && $module_data['requires_connection'] ) {
2979
				return false;
2980
			}
2981
		}
2982
2983
		// Check and see if the old plugin is active
2984
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2985
			// Deactivate the old plugin
2986
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2987
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2988
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2989
				self::state( 'deactivated_plugins', $module );
2990
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2991
				exit;
2992
			}
2993
		}
2994
2995
		// Protect won't work with mis-configured IPs
2996
		if ( 'protect' === $module ) {
2997
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2998
			if ( ! jetpack_protect_get_ip() ) {
2999
				self::state( 'message', 'protect_misconfigured_ip' );
3000
				return false;
3001
			}
3002
		}
3003
3004
		if ( ! Jetpack_Plan::supports( $module ) ) {
3005
			return false;
3006
		}
3007
3008
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3009
		self::state( 'module', $module );
3010
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3011
3012
		self::catch_errors( true );
3013
		ob_start();
3014
		require self::get_module_path( $module );
3015
		/** This action is documented in class.jetpack.php */
3016
		do_action( 'jetpack_activate_module', $module );
3017
		$active[] = $module;
3018
		self::update_active_modules( $active );
3019
3020
		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...
3021
		ob_end_clean();
3022
		self::catch_errors( false );
3023
3024
		if ( $redirect ) {
3025
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3026
		}
3027
		if ( $exit ) {
3028
			exit;
3029
		}
3030
		return true;
3031
	}
3032
3033
	function activate_module_actions( $module ) {
3034
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3035
	}
3036
3037
	public static function deactivate_module( $module ) {
3038
		/**
3039
		 * Fires when a module is deactivated.
3040
		 *
3041
		 * @since 1.9.0
3042
		 *
3043
		 * @param string $module Module slug.
3044
		 */
3045
		do_action( 'jetpack_pre_deactivate_module', $module );
3046
3047
		$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...
3048
3049
		$active = self::get_active_modules();
3050
		$new    = array_filter( array_diff( $active, (array) $module ) );
3051
3052
		return self::update_active_modules( $new );
3053
	}
3054
3055
	public static function enable_module_configurable( $module ) {
3056
		$module = self::get_module_slug( $module );
3057
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3058
	}
3059
3060
	/**
3061
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3062
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3063
	 *
3064
	 * @param string $module Module slug
3065
	 * @return string $url module configuration URL
3066
	 */
3067
	public static function module_configuration_url( $module ) {
3068
		$module      = self::get_module_slug( $module );
3069
		$default_url = self::admin_url() . "#/settings?term=$module";
3070
		/**
3071
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3072
		 *
3073
		 * @since 6.9.0
3074
		 *
3075
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3076
		 */
3077
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3078
3079
		return $url;
3080
	}
3081
3082
	/* Installation */
3083
	public static function bail_on_activation( $message, $deactivate = true ) {
3084
		?>
3085
<!doctype html>
3086
<html>
3087
<head>
3088
<meta charset="<?php bloginfo( 'charset' ); ?>">
3089
<style>
3090
* {
3091
	text-align: center;
3092
	margin: 0;
3093
	padding: 0;
3094
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3095
}
3096
p {
3097
	margin-top: 1em;
3098
	font-size: 18px;
3099
}
3100
</style>
3101
<body>
3102
<p><?php echo esc_html( $message ); ?></p>
3103
</body>
3104
</html>
3105
		<?php
3106
		if ( $deactivate ) {
3107
			$plugins = get_option( 'active_plugins' );
3108
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3109
			$update  = false;
3110
			foreach ( $plugins as $i => $plugin ) {
3111
				if ( $plugin === $jetpack ) {
3112
					$plugins[ $i ] = false;
3113
					$update        = true;
3114
				}
3115
			}
3116
3117
			if ( $update ) {
3118
				update_option( 'active_plugins', array_filter( $plugins ) );
3119
			}
3120
		}
3121
		exit;
3122
	}
3123
3124
	/**
3125
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3126
	 *
3127
	 * @static
3128
	 */
3129
	public static function plugin_activation( $network_wide ) {
3130
		Jetpack_Options::update_option( 'activated', 1 );
3131
3132
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3133
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3134
		}
3135
3136
		if ( $network_wide ) {
3137
			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...
3138
		}
3139
3140
		// For firing one-off events (notices) immediately after activation
3141
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3142
3143
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3144
3145
		Health::on_jetpack_activated();
3146
3147
		self::plugin_initialize();
3148
	}
3149
3150
	public static function get_activation_source( $referer_url ) {
3151
3152
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3153
			return array( 'wp-cli', null );
3154
		}
3155
3156
		$referer = wp_parse_url( $referer_url );
3157
3158
		$source_type  = 'unknown';
3159
		$source_query = null;
3160
3161
		if ( ! is_array( $referer ) ) {
3162
			return array( $source_type, $source_query );
3163
		}
3164
3165
		$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...
3166
		$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...
3167
3168
		if ( isset( $referer['query'] ) ) {
3169
			parse_str( $referer['query'], $query_parts );
3170
		} else {
3171
			$query_parts = array();
3172
		}
3173
3174
		if ( $plugins_path === $referer['path'] ) {
3175
			$source_type = 'list';
3176
		} elseif ( $plugins_install_path === $referer['path'] ) {
3177
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3178
			switch ( $tab ) {
3179
				case 'popular':
3180
					$source_type = 'popular';
3181
					break;
3182
				case 'recommended':
3183
					$source_type = 'recommended';
3184
					break;
3185
				case 'favorites':
3186
					$source_type = 'favorites';
3187
					break;
3188
				case 'search':
3189
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3190
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3191
					break;
3192
				default:
3193
					$source_type = 'featured';
3194
			}
3195
		}
3196
3197
		return array( $source_type, $source_query );
3198
	}
3199
3200
	/**
3201
	 * Runs before bumping version numbers up to a new version
3202
	 *
3203
	 * @param string $version    Version:timestamp.
3204
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3205
	 */
3206
	public static function do_version_bump( $version, $old_version ) {
3207
		if ( $old_version ) { // For existing Jetpack installations.
3208
3209
			// If a front end page is visited after the update, the 'wp' action will fire.
3210
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3211
3212
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3213
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3214
		}
3215
	}
3216
3217
	/**
3218
	 * Sets the display_update_modal state.
3219
	 */
3220
	public static function set_update_modal_display() {
3221
		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...
3222
	}
3223
3224
	/**
3225
	 * Sets the internal version number and activation state.
3226
	 *
3227
	 * @static
3228
	 */
3229
	public static function plugin_initialize() {
3230
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3231
			Jetpack_Options::update_option( 'activated', 2 );
3232
		}
3233
3234 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3235
			$version = $old_version = JETPACK__VERSION . ':' . time();
3236
			/** This action is documented in class.jetpack.php */
3237
			do_action( 'updating_jetpack_version', $version, false );
3238
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3239
		}
3240
3241
		self::load_modules();
3242
3243
		Jetpack_Options::delete_option( 'do_activate' );
3244
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3245
	}
3246
3247
	/**
3248
	 * Removes all connection options
3249
	 *
3250
	 * @static
3251
	 */
3252
	public static function plugin_deactivation() {
3253
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3254
		$tracking = new Tracking();
3255
		$tracking->record_user_event( 'deactivate_plugin', array() );
3256
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3257
			Jetpack_Network::init()->deactivate();
3258
		} else {
3259
			self::disconnect( false );
3260
			// Jetpack_Heartbeat::init()->deactivate();
3261
		}
3262
	}
3263
3264
	/**
3265
	 * Disconnects from the Jetpack servers.
3266
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3267
	 *
3268
	 * @static
3269
	 */
3270
	public static function disconnect( $update_activated_state = true ) {
3271
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3272
		$connection = self::connection();
3273
		$connection->clean_nonces( true );
3274
3275
		// If the site is in an IDC because sync is not allowed,
3276
		// let's make sure to not disconnect the production site.
3277
		if ( ! self::validate_sync_error_idc_option() ) {
3278
			$tracking = new Tracking();
3279
			$tracking->record_user_event( 'disconnect_site', array() );
3280
3281
			$connection->disconnect_site_wpcom( true );
3282
		}
3283
3284
		$connection->delete_all_connection_tokens( true );
3285
		Jetpack_IDC::clear_all_idc_options();
3286
3287
		if ( $update_activated_state ) {
3288
			Jetpack_Options::update_option( 'activated', 4 );
3289
		}
3290
3291
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3292
			// Check then record unique disconnection if site has never been disconnected previously
3293
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3294
				$jetpack_unique_connection['disconnected'] = 1;
3295
			} else {
3296
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3297
					// track unique disconnect
3298
					$jetpack = self::init();
3299
3300
					$jetpack->stat( 'connections', 'unique-disconnect' );
3301
					$jetpack->do_stats( 'server_side' );
3302
				}
3303
				// increment number of times disconnected
3304
				$jetpack_unique_connection['disconnected'] += 1;
3305
			}
3306
3307
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3308
		}
3309
3310
		// Delete all the sync related data. Since it could be taking up space.
3311
		Sender::get_instance()->uninstall();
3312
3313
		// Disable the Heartbeat cron
3314
		Jetpack_Heartbeat::init()->deactivate();
3315
	}
3316
3317
	/**
3318
	 * Unlinks the current user from the linked WordPress.com user.
3319
	 *
3320
	 * @deprecated since 7.7
3321
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3322
	 *
3323
	 * @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...
3324
	 * @return Boolean Whether the disconnection of the user was successful.
3325
	 */
3326
	public static function unlink_user( $user_id = null ) {
3327
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3328
		return Connection_Manager::disconnect_user( $user_id );
3329
	}
3330
3331
	/**
3332
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3333
	 */
3334
	public static function try_registration() {
3335
		$terms_of_service = new Terms_Of_Service();
3336
		// The user has agreed to the TOS at some point by now.
3337
		$terms_of_service->agree();
3338
3339
		// Let's get some testing in beta versions and such.
3340
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3341
			// Before attempting to connect, let's make sure that the domains are viable.
3342
			$domains_to_check = array_unique(
3343
				array(
3344
					'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...
3345
					'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...
3346
				)
3347
			);
3348
			foreach ( $domains_to_check as $domain ) {
3349
				$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...
3350
				if ( is_wp_error( $result ) ) {
3351
					return $result;
3352
				}
3353
			}
3354
		}
3355
3356
		$result = self::register();
3357
3358
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3359
		if ( ! $result || is_wp_error( $result ) ) {
3360
			return $result;
3361
		} else {
3362
			return true;
3363
		}
3364
	}
3365
3366
	/**
3367
	 * Tracking an internal event log. Try not to put too much chaff in here.
3368
	 *
3369
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3370
	 */
3371
	public static function log( $code, $data = null ) {
3372
		// only grab the latest 200 entries
3373
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3374
3375
		// Append our event to the log
3376
		$log_entry = array(
3377
			'time'    => time(),
3378
			'user_id' => get_current_user_id(),
3379
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3380
			'code'    => $code,
3381
		);
3382
		// Don't bother storing it unless we've got some.
3383
		if ( ! is_null( $data ) ) {
3384
			$log_entry['data'] = $data;
3385
		}
3386
		$log[] = $log_entry;
3387
3388
		// Try add_option first, to make sure it's not autoloaded.
3389
		// @todo: Add an add_option method to Jetpack_Options
3390
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3391
			Jetpack_Options::update_option( 'log', $log );
3392
		}
3393
3394
		/**
3395
		 * Fires when Jetpack logs an internal event.
3396
		 *
3397
		 * @since 3.0.0
3398
		 *
3399
		 * @param array $log_entry {
3400
		 *  Array of details about the log entry.
3401
		 *
3402
		 *  @param string time Time of the event.
3403
		 *  @param int user_id ID of the user who trigerred the event.
3404
		 *  @param int blog_id Jetpack Blog ID.
3405
		 *  @param string code Unique name for the event.
3406
		 *  @param string data Data about the event.
3407
		 * }
3408
		 */
3409
		do_action( 'jetpack_log_entry', $log_entry );
3410
	}
3411
3412
	/**
3413
	 * Get the internal event log.
3414
	 *
3415
	 * @param $event (string) - only return the specific log events
3416
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3417
	 *
3418
	 * @return array of log events || WP_Error for invalid params
3419
	 */
3420
	public static function get_log( $event = false, $num = false ) {
3421
		if ( $event && ! is_string( $event ) ) {
3422
			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...
3423
		}
3424
3425
		if ( $num && ! is_numeric( $num ) ) {
3426
			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...
3427
		}
3428
3429
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3430
3431
		// If nothing set - act as it did before, otherwise let's start customizing the output
3432
		if ( ! $num && ! $event ) {
3433
			return $entire_log;
3434
		} else {
3435
			$entire_log = array_reverse( $entire_log );
3436
		}
3437
3438
		$custom_log_output = array();
3439
3440
		if ( $event ) {
3441
			foreach ( $entire_log as $log_event ) {
3442
				if ( $event == $log_event['code'] ) {
3443
					$custom_log_output[] = $log_event;
3444
				}
3445
			}
3446
		} else {
3447
			$custom_log_output = $entire_log;
3448
		}
3449
3450
		if ( $num ) {
3451
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3452
		}
3453
3454
		return $custom_log_output;
3455
	}
3456
3457
	/**
3458
	 * Log modification of important settings.
3459
	 */
3460
	public static function log_settings_change( $option, $old_value, $value ) {
3461
		switch ( $option ) {
3462
			case 'jetpack_sync_non_public_post_stati':
3463
				self::log( $option, $value );
3464
				break;
3465
		}
3466
	}
3467
3468
	/**
3469
	 * Return stat data for WPCOM sync
3470
	 */
3471
	public static function get_stat_data( $encode = true, $extended = true ) {
3472
		$data = Jetpack_Heartbeat::generate_stats_array();
3473
3474
		if ( $extended ) {
3475
			$additional_data = self::get_additional_stat_data();
3476
			$data            = array_merge( $data, $additional_data );
3477
		}
3478
3479
		if ( $encode ) {
3480
			return json_encode( $data );
3481
		}
3482
3483
		return $data;
3484
	}
3485
3486
	/**
3487
	 * Get additional stat data to sync to WPCOM
3488
	 */
3489
	public static function get_additional_stat_data( $prefix = '' ) {
3490
		$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...
3491
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3492
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3493
		$return[ "{$prefix}site-count" ]    = 0;
3494
3495
		if ( function_exists( 'get_blog_count' ) ) {
3496
			$return[ "{$prefix}site-count" ] = get_blog_count();
3497
		}
3498
		return $return;
3499
	}
3500
3501
	private static function get_site_user_count() {
3502
		global $wpdb;
3503
3504
		if ( function_exists( 'wp_is_large_network' ) ) {
3505
			if ( wp_is_large_network( 'users' ) ) {
3506
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3507
			}
3508
		}
3509
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3510
			// It wasn't there, so regenerate the data and save the transient
3511
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3512
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3513
		}
3514
		return $user_count;
3515
	}
3516
3517
	/* Admin Pages */
3518
3519
	function admin_init() {
3520
		// If the plugin is not connected, display a connect message.
3521
		if (
3522
			// the plugin was auto-activated and needs its candy
3523
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3524
		||
3525
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3526
			! Jetpack_Options::get_option( 'activated' )
3527
		) {
3528
			self::plugin_initialize();
3529
		}
3530
3531
		$is_offline_mode = ( new Status() )->is_offline_mode();
3532
		if ( ! self::is_active() && ! $is_offline_mode ) {
3533
			Jetpack_Connection_Banner::init();
3534
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3535
			// Upgrade: 1.1 -> 1.1.1
3536
			// Check and see if host can verify the Jetpack servers' SSL certificate
3537
			$args       = array();
3538
			$connection = self::connection();
3539
			Client::_wp_remote_request(
3540
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3541
				$args,
3542
				true
3543
			);
3544
		}
3545
3546
		Jetpack_Wizard_Banner::init();
3547
3548
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3549
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3550
		}
3551
3552
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3553
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3554
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3555
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3556
3557
		if ( self::is_active() || $is_offline_mode ) {
3558
			// Artificially throw errors in certain specific cases during plugin activation.
3559
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3560
		}
3561
3562
		// Add custom column in wp-admin/users.php to show whether user is linked.
3563
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3564
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3565
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3566
	}
3567
3568
	function admin_body_class( $admin_body_class = '' ) {
3569
		$classes = explode( ' ', trim( $admin_body_class ) );
3570
3571
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3572
3573
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3574
		return " $admin_body_class ";
3575
	}
3576
3577
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3578
		return $admin_body_class . ' jetpack-pagestyles ';
3579
	}
3580
3581
	/**
3582
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3583
	 * This function artificially throws errors for such cases (per a specific list).
3584
	 *
3585
	 * @param string $plugin The activated plugin.
3586
	 */
3587
	function throw_error_on_activate_plugin( $plugin ) {
3588
		$active_modules = self::get_active_modules();
3589
3590
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3591
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3592
			$throw = false;
3593
3594
			// Try and make sure it really was the stats plugin
3595
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3596
				if ( 'stats.php' == basename( $plugin ) ) {
3597
					$throw = true;
3598
				}
3599
			} else {
3600
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3601
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3602
					$throw = true;
3603
				}
3604
			}
3605
3606
			if ( $throw ) {
3607
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3608
			}
3609
		}
3610
	}
3611
3612
	function intercept_plugin_error_scrape_init() {
3613
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3614
	}
3615
3616
	function intercept_plugin_error_scrape( $action, $result ) {
3617
		if ( ! $result ) {
3618
			return;
3619
		}
3620
3621
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3622
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3623
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3624
			}
3625
		}
3626
	}
3627
3628
	/**
3629
	 * Register the remote file upload request handlers, if needed.
3630
	 *
3631
	 * @access public
3632
	 */
3633
	public function add_remote_request_handlers() {
3634
		// Remote file uploads are allowed only via AJAX requests.
3635
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3636
			return;
3637
		}
3638
3639
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3640
		$remote_request_actions = array(
3641
			'jetpack_upload_file',
3642
			'jetpack_update_file',
3643
		);
3644
3645
		// phpcs:ignore WordPress.Security.NonceVerification
3646
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3647
			return;
3648
		}
3649
3650
		// Require Jetpack authentication for the remote file upload AJAX requests.
3651
		if ( ! $this->connection_manager ) {
3652
			$this->connection_manager = new Connection_Manager();
3653
		}
3654
3655
		$this->connection_manager->require_jetpack_authentication();
3656
3657
		// Register the remote file upload AJAX handlers.
3658
		foreach ( $remote_request_actions as $action ) {
3659
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3660
		}
3661
	}
3662
3663
	/**
3664
	 * Handler for Jetpack remote file uploads.
3665
	 *
3666
	 * @access public
3667
	 */
3668
	public function remote_request_handlers() {
3669
		$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...
3670
3671
		switch ( current_filter() ) {
3672
			case 'wp_ajax_nopriv_jetpack_upload_file':
3673
				$response = $this->upload_handler();
3674
				break;
3675
3676
			case 'wp_ajax_nopriv_jetpack_update_file':
3677
				$response = $this->upload_handler( true );
3678
				break;
3679
			default:
3680
				$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...
3681
				break;
3682
		}
3683
3684
		if ( ! $response ) {
3685
			$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...
3686
		}
3687
3688
		if ( is_wp_error( $response ) ) {
3689
			$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...
3690
			$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...
3691
			$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...
3692
3693
			if ( ! is_int( $status_code ) ) {
3694
				$status_code = 400;
3695
			}
3696
3697
			status_header( $status_code );
3698
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3699
		}
3700
3701
		status_header( 200 );
3702
		if ( true === $response ) {
3703
			exit;
3704
		}
3705
3706
		die( json_encode( (object) $response ) );
3707
	}
3708
3709
	/**
3710
	 * Uploads a file gotten from the global $_FILES.
3711
	 * If `$update_media_item` is true and `post_id` is defined
3712
	 * the attachment file of the media item (gotten through of the post_id)
3713
	 * will be updated instead of add a new one.
3714
	 *
3715
	 * @param  boolean $update_media_item - update media attachment
3716
	 * @return array - An array describing the uploadind files process
3717
	 */
3718
	function upload_handler( $update_media_item = false ) {
3719
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3720
			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...
3721
		}
3722
3723
		$user = wp_authenticate( '', '' );
3724
		if ( ! $user || is_wp_error( $user ) ) {
3725
			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...
3726
		}
3727
3728
		wp_set_current_user( $user->ID );
3729
3730
		if ( ! current_user_can( 'upload_files' ) ) {
3731
			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...
3732
		}
3733
3734
		if ( empty( $_FILES ) ) {
3735
			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...
3736
		}
3737
3738
		foreach ( array_keys( $_FILES ) as $files_key ) {
3739
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3740
				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...
3741
			}
3742
		}
3743
3744
		$media_keys = array_keys( $_FILES['media'] );
3745
3746
		$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...
3747
		if ( ! $token || is_wp_error( $token ) ) {
3748
			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...
3749
		}
3750
3751
		$uploaded_files = array();
3752
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3753
		unset( $GLOBALS['post'] );
3754
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3755
			$file = array();
3756
			foreach ( $media_keys as $media_key ) {
3757
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3758
			}
3759
3760
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3761
3762
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3763
			if ( $hmac_provided !== $hmac_file ) {
3764
				$uploaded_files[ $index ] = (object) array(
3765
					'error'             => 'invalid_hmac',
3766
					'error_description' => 'The corresponding HMAC for this file does not match',
3767
				);
3768
				continue;
3769
			}
3770
3771
			$_FILES['.jetpack.upload.'] = $file;
3772
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3773
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3774
				$post_id = 0;
3775
			}
3776
3777
			if ( $update_media_item ) {
3778
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3779
					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...
3780
				}
3781
3782
				$media_array = $_FILES['media'];
3783
3784
				$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...
3785
				$file_array['type']     = $media_array['type'][0];
3786
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3787
				$file_array['error']    = $media_array['error'][0];
3788
				$file_array['size']     = $media_array['size'][0];
3789
3790
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3791
3792
				if ( is_wp_error( $edited_media_item ) ) {
3793
					return $edited_media_item;
3794
				}
3795
3796
				$response = (object) array(
3797
					'id'   => (string) $post_id,
3798
					'file' => (string) $edited_media_item->post_title,
3799
					'url'  => (string) wp_get_attachment_url( $post_id ),
3800
					'type' => (string) $edited_media_item->post_mime_type,
3801
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3802
				);
3803
3804
				return (array) array( $response );
3805
			}
3806
3807
			$attachment_id = media_handle_upload(
3808
				'.jetpack.upload.',
3809
				$post_id,
3810
				array(),
3811
				array(
3812
					'action' => 'jetpack_upload_file',
3813
				)
3814
			);
3815
3816
			if ( ! $attachment_id ) {
3817
				$uploaded_files[ $index ] = (object) array(
3818
					'error'             => 'unknown',
3819
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3820
				);
3821
			} elseif ( is_wp_error( $attachment_id ) ) {
3822
				$uploaded_files[ $index ] = (object) array(
3823
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3824
					'error_description' => $attachment_id->get_error_message(),
3825
				);
3826
			} else {
3827
				$attachment               = get_post( $attachment_id );
3828
				$uploaded_files[ $index ] = (object) array(
3829
					'id'   => (string) $attachment_id,
3830
					'file' => $attachment->post_title,
3831
					'url'  => wp_get_attachment_url( $attachment_id ),
3832
					'type' => $attachment->post_mime_type,
3833
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3834
				);
3835
				// Zip files uploads are not supported unless they are done for installation purposed
3836
				// lets delete them in case something goes wrong in this whole process
3837
				if ( 'application/zip' === $attachment->post_mime_type ) {
3838
					// Schedule a cleanup for 2 hours from now in case of failed install.
3839
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3840
				}
3841
			}
3842
		}
3843
		if ( ! is_null( $global_post ) ) {
3844
			$GLOBALS['post'] = $global_post;
3845
		}
3846
3847
		return $uploaded_files;
3848
	}
3849
3850
	/**
3851
	 * Add help to the Jetpack page
3852
	 *
3853
	 * @since Jetpack (1.2.3)
3854
	 * @return false if not the Jetpack page
3855
	 */
3856
	function admin_help() {
3857
		$current_screen = get_current_screen();
3858
3859
		// Overview
3860
		$current_screen->add_help_tab(
3861
			array(
3862
				'id'      => 'home',
3863
				'title'   => __( 'Home', 'jetpack' ),
3864
				'content' =>
3865
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3866
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3867
					'<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>',
3868
			)
3869
		);
3870
3871
		// Screen Content
3872
		if ( current_user_can( 'manage_options' ) ) {
3873
			$current_screen->add_help_tab(
3874
				array(
3875
					'id'      => 'settings',
3876
					'title'   => __( 'Settings', 'jetpack' ),
3877
					'content' =>
3878
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3879
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3880
						'<ol>' .
3881
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3882
							'<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>' .
3883
						'</ol>' .
3884
						'<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>',
3885
				)
3886
			);
3887
		}
3888
3889
		// Help Sidebar
3890
		$support_url = Redirect::get_url( 'jetpack-support' );
3891
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3892
		$current_screen->set_help_sidebar(
3893
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3894
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3895
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3896
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3897
		);
3898
	}
3899
3900
	function admin_menu_css() {
3901
		wp_enqueue_style( 'jetpack-icons' );
3902
	}
3903
3904
	function admin_menu_order() {
3905
		return true;
3906
	}
3907
3908 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3909
		$jp_menu_order = array();
3910
3911
		foreach ( $menu_order as $index => $item ) {
3912
			if ( $item != 'jetpack' ) {
3913
				$jp_menu_order[] = $item;
3914
			}
3915
3916
			if ( $index == 0 ) {
3917
				$jp_menu_order[] = 'jetpack';
3918
			}
3919
		}
3920
3921
		return $jp_menu_order;
3922
	}
3923
3924
	function admin_banner_styles() {
3925
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3926
3927 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3928
			wp_register_style(
3929
				'jetpack-dops-style',
3930
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3931
				array(),
3932
				JETPACK__VERSION
3933
			);
3934
		}
3935
3936
		wp_enqueue_style(
3937
			'jetpack',
3938
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3939
			array( 'jetpack-dops-style' ),
3940
			JETPACK__VERSION . '-20121016'
3941
		);
3942
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3943
		wp_style_add_data( 'jetpack', 'suffix', $min );
3944
	}
3945
3946
	function plugin_action_links( $actions ) {
3947
3948
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3949
3950
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3951
			return array_merge(
3952
				$jetpack_home,
3953
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3954
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3955
				$actions
3956
			);
3957
		}
3958
3959
		return array_merge( $jetpack_home, $actions );
3960
	}
3961
3962
	/**
3963
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3964
	 *
3965
	 * @param string $hook The current admin page.
3966
	 *
3967
	 * @return void
3968
	 */
3969
	public function deactivate_dialog( $hook ) {
3970
		if (
3971
			'plugins.php' === $hook
3972
			&& self::is_active()
3973
		) {
3974
3975
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
3976
3977
			if ( count( $active_plugins_using_connection ) > 1 ) {
3978
3979
				add_thickbox();
3980
3981
				wp_register_script(
3982
					'jp-tracks',
3983
					'//stats.wp.com/w.js',
3984
					array(),
3985
					gmdate( 'YW' ),
3986
					true
3987
				);
3988
3989
				wp_register_script(
3990
					'jp-tracks-functions',
3991
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
3992
					array( 'jp-tracks' ),
3993
					JETPACK__VERSION,
3994
					false
3995
				);
3996
3997
				wp_enqueue_script(
3998
					'jetpack-deactivate-dialog-js',
3999
					Assets::get_file_url_for_environment(
4000
						'_inc/build/jetpack-deactivate-dialog.min.js',
4001
						'_inc/jetpack-deactivate-dialog.js'
4002
					),
4003
					array( 'jquery', 'jp-tracks-functions' ),
4004
					JETPACK__VERSION,
4005
					true
4006
				);
4007
4008
				wp_localize_script(
4009
					'jetpack-deactivate-dialog-js',
4010
					'deactivate_dialog',
4011
					array(
4012
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4013
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4014
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4015
					)
4016
				);
4017
4018
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4019
4020
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4021
			}
4022
		}
4023
	}
4024
4025
	/**
4026
	 * Outputs the content of the deactivation modal
4027
	 *
4028
	 * @return void
4029
	 */
4030
	public function deactivate_dialog_content() {
4031
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4032
		unset( $active_plugins_using_connection['jetpack'] );
4033
		$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 4031 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...
4034
	}
4035
4036
	/**
4037
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4038
	 *
4039
	 * @param string $login_url The wp-login URL.
4040
	 * @param string $redirect  URL to redirect users after logging in.
4041
	 * @since Jetpack 8.4
4042
	 * @return string
4043
	 */
4044
	public function login_url( $login_url, $redirect ) {
4045
		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...
4046
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4047
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4048
		}
4049
		return $login_url;
4050
	}
4051
4052
	/**
4053
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4054
	 *
4055
	 * @since Jetpack 8.4
4056
	 */
4057
	public function login_init() {
4058
		// phpcs:ignore WordPress.Security.NonceVerification
4059
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4060
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4061
			wp_safe_redirect(
4062
				add_query_arg(
4063
					array(
4064
						'forceInstall' => 1,
4065
						'url'          => rawurlencode( get_site_url() ),
4066
					),
4067
					// @todo provide way to go to specific calypso env.
4068
					self::get_calypso_host() . 'jetpack/connect'
4069
				)
4070
			);
4071
			exit;
4072
		}
4073
	}
4074
4075
	/*
4076
	 * Registration flow:
4077
	 * 1 - ::admin_page_load() action=register
4078
	 * 2 - ::try_registration()
4079
	 * 3 - ::register()
4080
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4081
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4082
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4083
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4084
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4085
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4086
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4087
	 *       jetpack_id, jetpack_secret, jetpack_public
4088
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4089
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4090
	 * 5 - user logs in with WP.com account
4091
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4092
	 *		- Manager::authorize()
4093
	 *		- Manager::get_token()
4094
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4095
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4096
	 *			- which responds with access_token, token_type, scope
4097
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4098
	 *		- Jetpack::activate_default_modules()
4099
	 *     		- Deactivates deprecated plugins
4100
	 *     		- Activates all default modules
4101
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4102
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4103
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4104
	 *     Done!
4105
	 */
4106
4107
	/**
4108
	 * Handles the page load events for the Jetpack admin page
4109
	 */
4110
	function admin_page_load() {
4111
		$error = false;
4112
4113
		// Make sure we have the right body class to hook stylings for subpages off of.
4114
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4115
4116
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4117
			// Should only be used in intermediate redirects to preserve state across redirects
4118
			self::restate();
4119
		}
4120
4121
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4122
			// @todo: Add validation against a known allowed list.
4123
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4124
			// User clicked in the iframe to link their accounts
4125
			if ( ! self::is_user_connected() ) {
4126
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4127
4128
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4129
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4130
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4131
4132
				if ( isset( $_GET['notes_iframe'] ) ) {
4133
					$connect_url .= '&notes_iframe';
4134
				}
4135
				wp_redirect( $connect_url );
4136
				exit;
4137
			} else {
4138
				if ( ! isset( $_GET['calypso_env'] ) ) {
4139
					self::state( 'message', 'already_authorized' );
4140
					wp_safe_redirect( self::admin_url() );
4141
					exit;
4142
				} else {
4143
					$connect_url  = $this->build_connect_url( true, false, $from );
4144
					$connect_url .= '&already_authorized=true';
4145
					wp_redirect( $connect_url );
4146
					exit;
4147
				}
4148
			}
4149
		}
4150
4151
		if ( isset( $_GET['action'] ) ) {
4152
			switch ( $_GET['action'] ) {
4153
				case 'authorize':
4154
					if ( self::is_active() && self::is_user_connected() ) {
4155
						self::state( 'message', 'already_authorized' );
4156
						wp_safe_redirect( self::admin_url() );
4157
						exit;
4158
					}
4159
					self::log( 'authorize' );
4160
					$client_server = new Jetpack_Client_Server();
4161
					$client_server->client_authorize();
4162
					exit;
4163
				case 'register':
4164
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4165
						$error = 'cheatin';
4166
						break;
4167
					}
4168
					check_admin_referer( 'jetpack-register' );
4169
					self::log( 'register' );
4170
					self::maybe_set_version_option();
4171
					$registered = self::try_registration();
4172 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4173
						$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...
4174
						self::state( 'error', $error );
4175
						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...
4176
4177
						/**
4178
						 * Jetpack registration Error.
4179
						 *
4180
						 * @since 7.5.0
4181
						 *
4182
						 * @param string|int $error The error code.
4183
						 * @param \WP_Error $registered The error object.
4184
						 */
4185
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4186
						break;
4187
					}
4188
4189
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4190
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4191
4192
					/**
4193
					 * Jetpack registration Success.
4194
					 *
4195
					 * @since 7.5.0
4196
					 *
4197
					 * @param string $from 'from' GET parameter;
4198
					 */
4199
					do_action( 'jetpack_connection_register_success', $from );
4200
4201
					$url = $this->build_connect_url( true, $redirect, $from );
4202
4203
					if ( ! empty( $_GET['onboarding'] ) ) {
4204
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4205
					}
4206
4207
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4208
						$url = add_query_arg( 'auth_approved', 'true', $url );
4209
					}
4210
4211
					wp_redirect( $url );
4212
					exit;
4213
				case 'activate':
4214
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4215
						$error = 'cheatin';
4216
						break;
4217
					}
4218
4219
					$module = stripslashes( $_GET['module'] );
4220
					check_admin_referer( "jetpack_activate-$module" );
4221
					self::log( 'activate', $module );
4222
					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...
4223
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4224
					}
4225
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4226
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4227
					exit;
4228
				case 'activate_default_modules':
4229
					check_admin_referer( 'activate_default_modules' );
4230
					self::log( 'activate_default_modules' );
4231
					self::restate();
4232
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4233
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4234
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4235
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4236
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4237
					exit;
4238
				case 'disconnect':
4239
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4240
						$error = 'cheatin';
4241
						break;
4242
					}
4243
4244
					check_admin_referer( 'jetpack-disconnect' );
4245
					self::log( 'disconnect' );
4246
					self::disconnect();
4247
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4248
					exit;
4249
				case 'reconnect':
4250
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4251
						$error = 'cheatin';
4252
						break;
4253
					}
4254
4255
					check_admin_referer( 'jetpack-reconnect' );
4256
					self::log( 'reconnect' );
4257
					$this->disconnect();
4258
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4259
					exit;
4260 View Code Duplication
				case 'deactivate':
4261
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4262
						$error = 'cheatin';
4263
						break;
4264
					}
4265
4266
					$modules = stripslashes( $_GET['module'] );
4267
					check_admin_referer( "jetpack_deactivate-$modules" );
4268
					foreach ( explode( ',', $modules ) as $module ) {
4269
						self::log( 'deactivate', $module );
4270
						self::deactivate_module( $module );
4271
						self::state( 'message', 'module_deactivated' );
4272
					}
4273
					self::state( 'module', $modules );
4274
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4275
					exit;
4276
				case 'unlink':
4277
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4278
					check_admin_referer( 'jetpack-unlink' );
4279
					self::log( 'unlink' );
4280
					Connection_Manager::disconnect_user();
4281
					self::state( 'message', 'unlinked' );
4282
					if ( 'sub-unlink' == $redirect ) {
4283
						wp_safe_redirect( admin_url() );
4284
					} else {
4285
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4286
					}
4287
					exit;
4288
				case 'onboard':
4289
					if ( ! current_user_can( 'manage_options' ) ) {
4290
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4291
					} else {
4292
						self::create_onboarding_token();
4293
						$url = $this->build_connect_url( true );
4294
4295
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4296
							$url = add_query_arg( 'onboarding', $token, $url );
4297
						}
4298
4299
						$calypso_env = $this->get_calypso_env();
4300
						if ( ! empty( $calypso_env ) ) {
4301
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4302
						}
4303
4304
						wp_redirect( $url );
4305
						exit;
4306
					}
4307
					exit;
4308
				default:
4309
					/**
4310
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4311
					 *
4312
					 * @since 2.6.0
4313
					 *
4314
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4315
					 */
4316
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4317
			}
4318
		}
4319
4320
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4321
			self::activate_new_modules( true );
4322
		}
4323
4324
		$message_code = self::state( 'message' );
4325
		if ( self::state( 'optin-manage' ) ) {
4326
			$activated_manage = $message_code;
4327
			$message_code     = 'jetpack-manage';
4328
		}
4329
4330
		switch ( $message_code ) {
4331
			case 'jetpack-manage':
4332
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4333
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4334
				$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>';
4335
				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...
4336
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4337
				}
4338
				break;
4339
4340
		}
4341
4342
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4343
4344
		if ( ! empty( $deactivated_plugins ) ) {
4345
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4346
			$deactivated_titles  = array();
4347
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4348
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4349
					continue;
4350
				}
4351
4352
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4353
			}
4354
4355
			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...
4356
				if ( $this->message ) {
4357
					$this->message .= "<br /><br />\n";
4358
				}
4359
4360
				$this->message .= wp_sprintf(
4361
					_n(
4362
						'Jetpack contains the most recent version of the old %l plugin.',
4363
						'Jetpack contains the most recent versions of the old %l plugins.',
4364
						count( $deactivated_titles ),
4365
						'jetpack'
4366
					),
4367
					$deactivated_titles
4368
				);
4369
4370
				$this->message .= "<br />\n";
4371
4372
				$this->message .= _n(
4373
					'The old version has been deactivated and can be removed from your site.',
4374
					'The old versions have been deactivated and can be removed from your site.',
4375
					count( $deactivated_titles ),
4376
					'jetpack'
4377
				);
4378
			}
4379
		}
4380
4381
		$this->privacy_checks = self::state( 'privacy_checks' );
4382
4383
		if ( $this->message || $this->error || $this->privacy_checks ) {
4384
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4385
		}
4386
4387
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4388
	}
4389
4390
	function admin_notices() {
4391
4392
		if ( $this->error ) {
4393
			?>
4394
<div id="message" class="jetpack-message jetpack-err">
4395
	<div class="squeezer">
4396
		<h2>
4397
			<?php
4398
			echo wp_kses(
4399
				$this->error,
4400
				array(
4401
					'a'      => array( 'href' => array() ),
4402
					'small'  => true,
4403
					'code'   => true,
4404
					'strong' => true,
4405
					'br'     => true,
4406
					'b'      => true,
4407
				)
4408
			);
4409
			?>
4410
			</h2>
4411
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4412
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4413
<?php	endif; ?>
4414
	</div>
4415
</div>
4416
			<?php
4417
		}
4418
4419
		if ( $this->message ) {
4420
			?>
4421
<div id="message" class="jetpack-message">
4422
	<div class="squeezer">
4423
		<h2>
4424
			<?php
4425
			echo wp_kses(
4426
				$this->message,
4427
				array(
4428
					'strong' => array(),
4429
					'a'      => array( 'href' => true ),
4430
					'br'     => true,
4431
				)
4432
			);
4433
			?>
4434
			</h2>
4435
	</div>
4436
</div>
4437
			<?php
4438
		}
4439
4440
		if ( $this->privacy_checks ) :
4441
			$module_names = $module_slugs = array();
4442
4443
			$privacy_checks = explode( ',', $this->privacy_checks );
4444
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4445
			foreach ( $privacy_checks as $module_slug ) {
4446
				$module = self::get_module( $module_slug );
4447
				if ( ! $module ) {
4448
					continue;
4449
				}
4450
4451
				$module_slugs[] = $module_slug;
4452
				$module_names[] = "<strong>{$module['name']}</strong>";
4453
			}
4454
4455
			$module_slugs = join( ',', $module_slugs );
4456
			?>
4457
<div id="message" class="jetpack-message jetpack-err">
4458
	<div class="squeezer">
4459
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4460
		<p>
4461
			<?php
4462
			echo wp_kses(
4463
				wptexturize(
4464
					wp_sprintf(
4465
						_nx(
4466
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4467
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4468
							count( $privacy_checks ),
4469
							'%l = list of Jetpack module/feature names',
4470
							'jetpack'
4471
						),
4472
						$module_names
4473
					)
4474
				),
4475
				array( 'strong' => true )
4476
			);
4477
4478
			echo "\n<br />\n";
4479
4480
			echo wp_kses(
4481
				sprintf(
4482
					_nx(
4483
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4484
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4485
						count( $privacy_checks ),
4486
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4487
						'jetpack'
4488
					),
4489
					wp_nonce_url(
4490
						self::admin_url(
4491
							array(
4492
								'page'   => 'jetpack',
4493
								'action' => 'deactivate',
4494
								'module' => urlencode( $module_slugs ),
4495
							)
4496
						),
4497
						"jetpack_deactivate-$module_slugs"
4498
					),
4499
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4500
				),
4501
				array(
4502
					'a' => array(
4503
						'href'  => true,
4504
						'title' => true,
4505
					),
4506
				)
4507
			);
4508
			?>
4509
		</p>
4510
	</div>
4511
</div>
4512
			<?php
4513
endif;
4514
	}
4515
4516
	/**
4517
	 * We can't always respond to a signed XML-RPC request with a
4518
	 * helpful error message. In some circumstances, doing so could
4519
	 * leak information.
4520
	 *
4521
	 * Instead, track that the error occurred via a Jetpack_Option,
4522
	 * and send that data back in the heartbeat.
4523
	 * All this does is increment a number, but it's enough to find
4524
	 * trends.
4525
	 *
4526
	 * @param WP_Error $xmlrpc_error The error produced during
4527
	 *                               signature validation.
4528
	 */
4529
	function track_xmlrpc_error( $xmlrpc_error ) {
4530
		$code = is_wp_error( $xmlrpc_error )
4531
			? $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...
4532
			: 'should-not-happen';
4533
4534
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4535
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4536
			// No need to update the option if we already have
4537
			// this code stored.
4538
			return;
4539
		}
4540
		$xmlrpc_errors[ $code ] = true;
4541
4542
		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...
4543
	}
4544
4545
	/**
4546
	 * Initialize the jetpack stats instance only when needed
4547
	 *
4548
	 * @return void
4549
	 */
4550
	private function initialize_stats() {
4551
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4552
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4553
		}
4554
	}
4555
4556
	/**
4557
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4558
	 */
4559
	function stat( $group, $detail ) {
4560
		$this->initialize_stats();
4561
		$this->a8c_mc_stats_instance->add( $group, $detail );
4562
4563
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4564
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4565
	}
4566
4567
	/**
4568
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4569
	 */
4570
	function do_stats( $method = '' ) {
4571
		$this->initialize_stats();
4572
		if ( 'server_side' === $method ) {
4573
			$this->a8c_mc_stats_instance->do_server_side_stats();
4574
		} else {
4575
			$this->a8c_mc_stats_instance->do_stats();
4576
		}
4577
4578
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4579
		$this->stats = array();
4580
	}
4581
4582
	/**
4583
	 * Runs stats code for a one-off, server-side.
4584
	 *
4585
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4586
	 *
4587
	 * @return bool If it worked.
4588
	 */
4589
	static function do_server_side_stat( $args ) {
4590
		$url                   = self::build_stats_url( $args );
4591
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4592
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4593
	}
4594
4595
	/**
4596
	 * Builds the stats url.
4597
	 *
4598
	 * @param $args array|string The arguments to append to the URL.
4599
	 *
4600
	 * @return string The URL to be pinged.
4601
	 */
4602
	static function build_stats_url( $args ) {
4603
4604
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4605
		return $a8c_mc_stats_instance->build_stats_url( $args );
4606
4607
	}
4608
4609
	/**
4610
	 * Get the role of the current user.
4611
	 *
4612
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4613
	 *
4614
	 * @access public
4615
	 * @static
4616
	 *
4617
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4618
	 */
4619
	public static function translate_current_user_to_role() {
4620
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4621
4622
		$roles = new Roles();
4623
		return $roles->translate_current_user_to_role();
4624
	}
4625
4626
	/**
4627
	 * Get the role of a particular user.
4628
	 *
4629
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4630
	 *
4631
	 * @access public
4632
	 * @static
4633
	 *
4634
	 * @param \WP_User $user User object.
4635
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4636
	 */
4637
	public static function translate_user_to_role( $user ) {
4638
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4639
4640
		$roles = new Roles();
4641
		return $roles->translate_user_to_role( $user );
4642
	}
4643
4644
	/**
4645
	 * Get the minimum capability for a role.
4646
	 *
4647
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4648
	 *
4649
	 * @access public
4650
	 * @static
4651
	 *
4652
	 * @param string $role Role name.
4653
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4654
	 */
4655
	public static function translate_role_to_cap( $role ) {
4656
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4657
4658
		$roles = new Roles();
4659
		return $roles->translate_role_to_cap( $role );
4660
	}
4661
4662
	/**
4663
	 * Sign a user role with the master access token.
4664
	 * If not specified, will default to the current user.
4665
	 *
4666
	 * @deprecated since 7.7
4667
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4668
	 *
4669
	 * @access public
4670
	 * @static
4671
	 *
4672
	 * @param string $role    User role.
4673
	 * @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...
4674
	 * @return string Signed user role.
4675
	 */
4676
	public static function sign_role( $role, $user_id = null ) {
4677
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4678
		return self::connection()->sign_role( $role, $user_id );
4679
	}
4680
4681
	/**
4682
	 * Builds a URL to the Jetpack connection auth page
4683
	 *
4684
	 * @since 3.9.5
4685
	 *
4686
	 * @param bool        $raw If true, URL will not be escaped.
4687
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4688
	 *                              If string, will be a custom redirect.
4689
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4690
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4691
	 *
4692
	 * @return string Connect URL
4693
	 */
4694
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4695
		$site_id    = Jetpack_Options::get_option( 'id' );
4696
		$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...
4697
4698
		if ( $register || ! $blog_token || ! $site_id ) {
4699
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4700
4701
			if ( ! empty( $redirect ) ) {
4702
				$url = add_query_arg(
4703
					'redirect',
4704
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4705
					$url
4706
				);
4707
			}
4708
4709
			if ( is_network_admin() ) {
4710
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4711
			}
4712
4713
			$calypso_env = self::get_calypso_env();
4714
4715
			if ( ! empty( $calypso_env ) ) {
4716
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4717
			}
4718
		} else {
4719
4720
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4721
			// because otherwise this logic can get us in to a loop.
4722
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4723
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4724
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4725
4726
				$response = Client::wpcom_json_api_request_as_blog(
4727
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4728
					'1.1'
4729
				);
4730
4731
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4732
4733
					// Generating a register URL instead to refresh the existing token
4734
					return $this->build_connect_url( $raw, $redirect, $from, true );
4735
				}
4736
			}
4737
4738
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4694 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...
4739
		}
4740
4741
		if ( $from ) {
4742
			$url = add_query_arg( 'from', $from, $url );
4743
		}
4744
4745
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4746
		/**
4747
		 * Filter the URL used when connecting a user to a WordPress.com account.
4748
		 *
4749
		 * @since 8.1.0
4750
		 *
4751
		 * @param string $url Connection URL.
4752
		 * @param bool   $raw If true, URL will not be escaped.
4753
		 */
4754
		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...
4755
	}
4756
4757
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4758
4759
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4760
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4761
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4762
4763
		if ( $iframe ) {
4764
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4765
		}
4766
4767
		$c8n = self::connection();
4768
		$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...
4769
4770
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4771
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4772
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4773
4774
		if ( $iframe ) {
4775
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4776
		}
4777
4778
		return $url;
4779
	}
4780
4781
	/**
4782
	 * Filters the connection URL parameter array.
4783
	 *
4784
	 * @param array $args default URL parameters used by the package.
4785
	 * @return array the modified URL arguments array.
4786
	 */
4787
	public static function filter_connect_request_body( $args ) {
4788
		if (
4789
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4790
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4791
		) {
4792
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4793
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4794
				? $gp_locale->slug
4795
				: '';
4796
		}
4797
4798
		$tracking        = new Tracking();
4799
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4800
4801
		$args = array_merge(
4802
			$args,
4803
			array(
4804
				'_ui' => $tracks_identity['_ui'],
4805
				'_ut' => $tracks_identity['_ut'],
4806
			)
4807
		);
4808
4809
		$calypso_env = self::get_calypso_env();
4810
4811
		if ( ! empty( $calypso_env ) ) {
4812
			$args['calypso_env'] = $calypso_env;
4813
		}
4814
4815
		return $args;
4816
	}
4817
4818
	/**
4819
	 * Filters the URL that will process the connection data. It can be different from the URL
4820
	 * that we send the user to after everything is done.
4821
	 *
4822
	 * @param String $processing_url the default redirect URL used by the package.
4823
	 * @return String the modified URL.
4824
	 */
4825
	public static function filter_connect_processing_url( $processing_url ) {
4826
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4827
		return $processing_url;
4828
	}
4829
4830
	/**
4831
	 * Filters the redirection URL that is used for connect requests. The redirect
4832
	 * URL should return the user back to the Jetpack console.
4833
	 *
4834
	 * @param String $redirect the default redirect URL used by the package.
4835
	 * @return String the modified URL.
4836
	 */
4837
	public static function filter_connect_redirect_url( $redirect ) {
4838
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4839
		$redirect           = $redirect
4840
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4841
			: $jetpack_admin_page;
4842
4843
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4844
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4845
		}
4846
4847
		return $redirect;
4848
	}
4849
4850
	/**
4851
	 * This action fires at the beginning of the Manager::authorize method.
4852
	 */
4853
	public static function authorize_starting() {
4854
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4855
		// Checking if site has been active/connected previously before recording unique connection.
4856
		if ( ! $jetpack_unique_connection ) {
4857
			// jetpack_unique_connection option has never been set.
4858
			$jetpack_unique_connection = array(
4859
				'connected'    => 0,
4860
				'disconnected' => 0,
4861
				'version'      => '3.6.1',
4862
			);
4863
4864
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4865
4866
			// Track unique connection.
4867
			$jetpack = self::init();
4868
4869
			$jetpack->stat( 'connections', 'unique-connection' );
4870
			$jetpack->do_stats( 'server_side' );
4871
		}
4872
4873
		// Increment number of times connected.
4874
		$jetpack_unique_connection['connected'] += 1;
4875
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4876
	}
4877
4878
	/**
4879
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4880
	 * linked.
4881
	 */
4882
	public static function authorize_ending_linked() {
4883
		// Don't activate anything since we are just connecting a user.
4884
		self::state( 'message', 'linked' );
4885
	}
4886
4887
	/**
4888
	 * This action fires at the end of the Manager::authorize method when the master user is
4889
	 * authorized.
4890
	 *
4891
	 * @param array $data The request data.
4892
	 */
4893
	public static function authorize_ending_authorized( $data ) {
4894
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4895
		self::invalidate_onboarding_token();
4896
4897
		// If redirect_uri is SSO, ensure SSO module is enabled.
4898
		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...
4899
4900
		/** This filter is documented in class.jetpack-cli.php */
4901
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4902
4903
		$activate_sso = (
4904
			isset( $redirect_options['action'] ) &&
4905
			'jetpack-sso' === $redirect_options['action'] &&
4906
			$jetpack_start_enable_sso
4907
		);
4908
4909
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4910
4911
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4912
	}
4913
4914
	/**
4915
	 * Get our assumed site creation date.
4916
	 * Calculated based on the earlier date of either:
4917
	 * - Earliest admin user registration date.
4918
	 * - Earliest date of post of any post type.
4919
	 *
4920
	 * @since 7.2.0
4921
	 * @deprecated since 7.8.0
4922
	 *
4923
	 * @return string Assumed site creation date and time.
4924
	 */
4925
	public static function get_assumed_site_creation_date() {
4926
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4927
		return self::connection()->get_assumed_site_creation_date();
4928
	}
4929
4930 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4931
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4932
4933
		if ( $activation_source_name ) {
4934
			$args['_as'] = urlencode( $activation_source_name );
4935
		}
4936
4937
		if ( $activation_source_keyword ) {
4938
			$args['_ak'] = urlencode( $activation_source_keyword );
4939
		}
4940
	}
4941
4942
	function build_reconnect_url( $raw = false ) {
4943
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4944
		return $raw ? $url : esc_url( $url );
4945
	}
4946
4947
	public static function admin_url( $args = null ) {
4948
		$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...
4949
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4950
		return $url;
4951
	}
4952
4953
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4954
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4955
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4956
	}
4957
4958
	function dismiss_jetpack_notice() {
4959
4960
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4961
			return;
4962
		}
4963
4964
		switch ( $_GET['jetpack-notice'] ) {
4965
			case 'dismiss':
4966
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4967
4968
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4969
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4970
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4971
				}
4972
				break;
4973
		}
4974
	}
4975
4976
	public static function sort_modules( $a, $b ) {
4977
		if ( $a['sort'] == $b['sort'] ) {
4978
			return 0;
4979
		}
4980
4981
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4982
	}
4983
4984
	function ajax_recheck_ssl() {
4985
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4986
		$result = self::permit_ssl( true );
4987
		wp_send_json(
4988
			array(
4989
				'enabled' => $result,
4990
				'message' => get_transient( 'jetpack_https_test_message' ),
4991
			)
4992
		);
4993
	}
4994
4995
	/* Client API */
4996
4997
	/**
4998
	 * Returns the requested Jetpack API URL
4999
	 *
5000
	 * @deprecated since 7.7
5001
	 * @return string
5002
	 */
5003
	public static function api_url( $relative_url ) {
5004
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5005
		$connection = self::connection();
5006
		return $connection->api_url( $relative_url );
5007
	}
5008
5009
	/**
5010
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5011
	 *
5012
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5013
	 */
5014
	public static function fix_url_for_bad_hosts( $url ) {
5015
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5016
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5017
	}
5018
5019
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5020
		// Default to a blog token.
5021
		$token_type = 'blog';
5022
5023
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5024
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5025
			if ( ! empty( $_GET['onboarding'] ) ) {
5026
				$jpo = $_GET;
5027
			} else {
5028
				$jpo = json_decode( $request_data, true );
5029
			}
5030
5031
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5032
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5033
5034
			if (
5035
				isset( $jpo_user )
5036
				&& isset( $jpo_token )
5037
				&& is_email( $jpo_user )
5038
				&& ctype_alnum( $jpo_token )
5039
				&& isset( $_GET['rest_route'] )
5040
				&& self::validate_onboarding_token_action(
5041
					$jpo_token,
5042
					$_GET['rest_route']
5043
				)
5044
			) {
5045
				$jp_user = get_user_by( 'email', $jpo_user );
5046
				if ( is_a( $jp_user, 'WP_User' ) ) {
5047
					wp_set_current_user( $jp_user->ID );
5048
					$user_can = is_multisite()
5049
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5050
						: current_user_can( 'manage_options' );
5051
					if ( $user_can ) {
5052
						$token_type              = 'user';
5053
						$token->external_user_id = $jp_user->ID;
5054
					}
5055
				}
5056
			}
5057
5058
			$token_data['type']    = $token_type;
5059
			$token_data['user_id'] = $token->external_user_id;
5060
		}
5061
5062
		return $token_data;
5063
	}
5064
5065
	/**
5066
	 * Create a random secret for validating onboarding payload
5067
	 *
5068
	 * @return string Secret token
5069
	 */
5070
	public static function create_onboarding_token() {
5071
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5072
			$token = wp_generate_password( 32, false );
5073
			Jetpack_Options::update_option( 'onboarding', $token );
5074
		}
5075
5076
		return $token;
5077
	}
5078
5079
	/**
5080
	 * Remove the onboarding token
5081
	 *
5082
	 * @return bool True on success, false on failure
5083
	 */
5084
	public static function invalidate_onboarding_token() {
5085
		return Jetpack_Options::delete_option( 'onboarding' );
5086
	}
5087
5088
	/**
5089
	 * Validate an onboarding token for a specific action
5090
	 *
5091
	 * @return boolean True if token/action pair is accepted, false if not
5092
	 */
5093
	public static function validate_onboarding_token_action( $token, $action ) {
5094
		// Compare tokens, bail if tokens do not match
5095
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5096
			return false;
5097
		}
5098
5099
		// List of valid actions we can take
5100
		$valid_actions = array(
5101
			'/jetpack/v4/settings',
5102
		);
5103
5104
		// Only allow valid actions.
5105
		if ( ! in_array( $action, $valid_actions ) ) {
5106
			return false;
5107
		}
5108
5109
		return true;
5110
	}
5111
5112
	/**
5113
	 * Checks to see if the URL is using SSL to connect with Jetpack
5114
	 *
5115
	 * @since 2.3.3
5116
	 * @return boolean
5117
	 */
5118
	public static function permit_ssl( $force_recheck = false ) {
5119
		// Do some fancy tests to see if ssl is being supported
5120
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5121
			$message = '';
5122
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5123
				$ssl = 0;
5124
			} else {
5125
				switch ( JETPACK_CLIENT__HTTPS ) {
5126
					case 'NEVER':
5127
						$ssl     = 0;
5128
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5129
						break;
5130
					case 'ALWAYS':
5131
					case 'AUTO':
5132
					default:
5133
						$ssl = 1;
5134
						break;
5135
				}
5136
5137
				// If it's not 'NEVER', test to see
5138
				if ( $ssl ) {
5139
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5140
						$ssl     = 0;
5141
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5142
					} else {
5143
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5144
						if ( is_wp_error( $response ) ) {
5145
							$ssl     = 0;
5146
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5147
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5148
							$ssl     = 0;
5149
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5150
						}
5151
					}
5152
				}
5153
			}
5154
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5155
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5156
		}
5157
5158
		return (bool) $ssl;
5159
	}
5160
5161
	/*
5162
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5163
	 */
5164
	public function alert_auto_ssl_fail() {
5165
		if ( ! current_user_can( 'manage_options' ) ) {
5166
			return;
5167
		}
5168
5169
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5170
		?>
5171
5172
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5173
			<div class="jp-banner__content">
5174
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5175
				<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>
5176
				<p>
5177
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5178
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5179
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5180
				</p>
5181
				<p>
5182
					<?php
5183
					printf(
5184
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5185
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5186
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5187
					);
5188
					?>
5189
				</p>
5190
			</div>
5191
		</div>
5192
		<style>
5193
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5194
		</style>
5195
		<script type="text/javascript">
5196
			jQuery( document ).ready( function( $ ) {
5197
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5198
					var $this = $( this );
5199
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5200
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5201
					e.preventDefault();
5202
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5203
					$.post( ajaxurl, data )
5204
					  .done( function( response ) {
5205
						  if ( response.enabled ) {
5206
							  $( '#jetpack-ssl-warning' ).hide();
5207
						  } else {
5208
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5209
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5210
						  }
5211
					  }.bind( $this ) );
5212
				} );
5213
			} );
5214
		</script>
5215
5216
		<?php
5217
	}
5218
5219
	/**
5220
	 * Returns the Jetpack XML-RPC API
5221
	 *
5222
	 * @deprecated 8.0 Use Connection_Manager instead.
5223
	 * @return string
5224
	 */
5225
	public static function xmlrpc_api_url() {
5226
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5227
		return self::connection()->xmlrpc_api_url();
5228
	}
5229
5230
	/**
5231
	 * Returns the connection manager object.
5232
	 *
5233
	 * @return Automattic\Jetpack\Connection\Manager
5234
	 */
5235
	public static function connection() {
5236
		$jetpack = static::init();
5237
5238
		// If the connection manager hasn't been instantiated, do that now.
5239
		if ( ! $jetpack->connection_manager ) {
5240
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5241
		}
5242
5243
		return $jetpack->connection_manager;
5244
	}
5245
5246
	/**
5247
	 * Creates two secret tokens and the end of life timestamp for them.
5248
	 *
5249
	 * Note these tokens are unique per call, NOT static per site for connecting.
5250
	 *
5251
	 * @since 2.6
5252
	 * @param String  $action  The action name.
5253
	 * @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...
5254
	 * @param Integer $exp     Expiration time in seconds.
5255
	 * @return array
5256
	 */
5257
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5258
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5259
	}
5260
5261
	public static function get_secrets( $action, $user_id ) {
5262
		$secrets = self::connection()->get_secrets( $action, $user_id );
5263
5264
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5265
			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...
5266
		}
5267
5268
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5269
			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...
5270
		}
5271
5272
		return $secrets;
5273
	}
5274
5275
	/**
5276
	 * @deprecated 7.5 Use Connection_Manager instead.
5277
	 *
5278
	 * @param $action
5279
	 * @param $user_id
5280
	 */
5281
	public static function delete_secrets( $action, $user_id ) {
5282
		return self::connection()->delete_secrets( $action, $user_id );
5283
	}
5284
5285
	/**
5286
	 * Builds the timeout limit for queries talking with the wpcom servers.
5287
	 *
5288
	 * Based on local php max_execution_time in php.ini
5289
	 *
5290
	 * @since 2.6
5291
	 * @return int
5292
	 * @deprecated
5293
	 **/
5294
	public function get_remote_query_timeout_limit() {
5295
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5296
		return self::get_max_execution_time();
5297
	}
5298
5299
	/**
5300
	 * Builds the timeout limit for queries talking with the wpcom servers.
5301
	 *
5302
	 * Based on local php max_execution_time in php.ini
5303
	 *
5304
	 * @since 5.4
5305
	 * @return int
5306
	 **/
5307
	public static function get_max_execution_time() {
5308
		$timeout = (int) ini_get( 'max_execution_time' );
5309
5310
		// Ensure exec time set in php.ini
5311
		if ( ! $timeout ) {
5312
			$timeout = 30;
5313
		}
5314
		return $timeout;
5315
	}
5316
5317
	/**
5318
	 * Sets a minimum request timeout, and returns the current timeout
5319
	 *
5320
	 * @since 5.4
5321
	 **/
5322 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5323
		$timeout = self::get_max_execution_time();
5324
		if ( $timeout < $min_timeout ) {
5325
			$timeout = $min_timeout;
5326
			set_time_limit( $timeout );
5327
		}
5328
		return $timeout;
5329
	}
5330
5331
	/**
5332
	 * Takes the response from the Jetpack register new site endpoint and
5333
	 * verifies it worked properly.
5334
	 *
5335
	 * @since 2.6
5336
	 * @deprecated since 7.7.0
5337
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5338
	 **/
5339
	public function validate_remote_register_response() {
5340
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5341
	}
5342
5343
	/**
5344
	 * @return bool|WP_Error
5345
	 */
5346
	public static function register() {
5347
		$tracking = new Tracking();
5348
		$tracking->record_user_event( 'jpc_register_begin' );
5349
5350
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5351
5352
		$connection   = self::connection();
5353
		$registration = $connection->register();
5354
5355
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5356
5357
		if ( ! $registration || is_wp_error( $registration ) ) {
5358
			return $registration;
5359
		}
5360
5361
		return true;
5362
	}
5363
5364
	/**
5365
	 * Filters the registration request body to include tracking properties.
5366
	 *
5367
	 * @param array $properties
5368
	 * @return array amended properties.
5369
	 */
5370 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5371
		$tracking        = new Tracking();
5372
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5373
5374
		return array_merge(
5375
			$properties,
5376
			array(
5377
				'_ui' => $tracks_identity['_ui'],
5378
				'_ut' => $tracks_identity['_ut'],
5379
			)
5380
		);
5381
	}
5382
5383
	/**
5384
	 * Filters the token request body to include tracking properties.
5385
	 *
5386
	 * @param array $properties
5387
	 * @return array amended properties.
5388
	 */
5389 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5390
		$tracking        = new Tracking();
5391
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5392
5393
		return array_merge(
5394
			$properties,
5395
			array(
5396
				'_ui' => $tracks_identity['_ui'],
5397
				'_ut' => $tracks_identity['_ut'],
5398
			)
5399
		);
5400
	}
5401
5402
	/**
5403
	 * If the db version is showing something other that what we've got now, bump it to current.
5404
	 *
5405
	 * @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...
5406
	 */
5407
	public static function maybe_set_version_option() {
5408
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5409
		if ( JETPACK__VERSION != $version ) {
5410
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5411
5412
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5413
				/** This action is documented in class.jetpack.php */
5414
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5415
			}
5416
5417
			return true;
5418
		}
5419
		return false;
5420
	}
5421
5422
	/* Client Server API */
5423
5424
	/**
5425
	 * Loads the Jetpack XML-RPC client.
5426
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5427
	 *
5428
	 * @deprecated since 7.7.0
5429
	 */
5430
	public static function load_xml_rpc_client() {
5431
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5432
	}
5433
5434
	/**
5435
	 * Resets the saved authentication state in between testing requests.
5436
	 */
5437
	public function reset_saved_auth_state() {
5438
		$this->rest_authentication_status = null;
5439
5440
		if ( ! $this->connection_manager ) {
5441
			$this->connection_manager = new Connection_Manager();
5442
		}
5443
5444
		$this->connection_manager->reset_saved_auth_state();
5445
	}
5446
5447
	/**
5448
	 * Verifies the signature of the current request.
5449
	 *
5450
	 * @deprecated since 7.7.0
5451
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5452
	 *
5453
	 * @return false|array
5454
	 */
5455
	public function verify_xml_rpc_signature() {
5456
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5457
		return self::connection()->verify_xml_rpc_signature();
5458
	}
5459
5460
	/**
5461
	 * Verifies the signature of the current request.
5462
	 *
5463
	 * This function has side effects and should not be used. Instead,
5464
	 * use the memoized version `->verify_xml_rpc_signature()`.
5465
	 *
5466
	 * @deprecated since 7.7.0
5467
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5468
	 * @internal
5469
	 */
5470
	private function internal_verify_xml_rpc_signature() {
5471
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5472
	}
5473
5474
	/**
5475
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5476
	 *
5477
	 * @deprecated since 7.7.0
5478
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5479
	 *
5480
	 * @param \WP_User|mixed $user     User object if authenticated.
5481
	 * @param string         $username Username.
5482
	 * @param string         $password Password string.
5483
	 * @return \WP_User|mixed Authenticated user or error.
5484
	 */
5485 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5486
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5487
5488
		if ( ! $this->connection_manager ) {
5489
			$this->connection_manager = new Connection_Manager();
5490
		}
5491
5492
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5493
	}
5494
5495
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5496
	// Uses the existing XMLRPC request signing implementation.
5497
	function wp_rest_authenticate( $user ) {
5498
		if ( ! empty( $user ) ) {
5499
			// Another authentication method is in effect.
5500
			return $user;
5501
		}
5502
5503
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5504
			// Nothing to do for this authentication method.
5505
			return null;
5506
		}
5507
5508
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5509
			// Nothing to do for this authentication method.
5510
			return null;
5511
		}
5512
5513
		// Ensure that we always have the request body available.  At this
5514
		// point, the WP REST API code to determine the request body has not
5515
		// run yet.  That code may try to read from 'php://input' later, but
5516
		// this can only be done once per request in PHP versions prior to 5.6.
5517
		// So we will go ahead and perform this read now if needed, and save
5518
		// the request body where both the Jetpack signature verification code
5519
		// and the WP REST API code can see it.
5520
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5521
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5522
		}
5523
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5524
5525
		// Only support specific request parameters that have been tested and
5526
		// are known to work with signature verification.  A different method
5527
		// can be passed to the WP REST API via the '?_method=' parameter if
5528
		// needed.
5529
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5530
			$this->rest_authentication_status = new WP_Error(
5531
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5532
				__( 'This request method is not supported.', 'jetpack' ),
5533
				array( 'status' => 400 )
5534
			);
5535
			return null;
5536
		}
5537
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5538
			$this->rest_authentication_status = new WP_Error(
5539
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5540
				__( 'This request method does not support body parameters.', 'jetpack' ),
5541
				array( 'status' => 400 )
5542
			);
5543
			return null;
5544
		}
5545
5546
		if ( ! $this->connection_manager ) {
5547
			$this->connection_manager = new Connection_Manager();
5548
		}
5549
5550
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5551
5552
		if (
5553
			$verified &&
5554
			isset( $verified['type'] ) &&
5555
			'user' === $verified['type'] &&
5556
			! empty( $verified['user_id'] )
5557
		) {
5558
			// Authentication successful.
5559
			$this->rest_authentication_status = true;
5560
			return $verified['user_id'];
5561
		}
5562
5563
		// Something else went wrong.  Probably a signature error.
5564
		$this->rest_authentication_status = new WP_Error(
5565
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5566
			__( 'The request is not signed correctly.', 'jetpack' ),
5567
			array( 'status' => 400 )
5568
		);
5569
		return null;
5570
	}
5571
5572
	/**
5573
	 * Report authentication status to the WP REST API.
5574
	 *
5575
	 * @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...
5576
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5577
	 */
5578
	public function wp_rest_authentication_errors( $value ) {
5579
		if ( $value !== null ) {
5580
			return $value;
5581
		}
5582
		return $this->rest_authentication_status;
5583
	}
5584
5585
	/**
5586
	 * Add our nonce to this request.
5587
	 *
5588
	 * @deprecated since 7.7.0
5589
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5590
	 *
5591
	 * @param int    $timestamp Timestamp of the request.
5592
	 * @param string $nonce     Nonce string.
5593
	 */
5594 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5595
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5596
5597
		if ( ! $this->connection_manager ) {
5598
			$this->connection_manager = new Connection_Manager();
5599
		}
5600
5601
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5602
	}
5603
5604
	/**
5605
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5606
	 * Capture it here so we can verify the signature later.
5607
	 *
5608
	 * @deprecated since 7.7.0
5609
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5610
	 *
5611
	 * @param array $methods XMLRPC methods.
5612
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5613
	 */
5614 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5615
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5616
5617
		if ( ! $this->connection_manager ) {
5618
			$this->connection_manager = new Connection_Manager();
5619
		}
5620
5621
		return $this->connection_manager->xmlrpc_methods( $methods );
5622
	}
5623
5624
	/**
5625
	 * Register additional public XMLRPC methods.
5626
	 *
5627
	 * @deprecated since 7.7.0
5628
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5629
	 *
5630
	 * @param array $methods Public XMLRPC methods.
5631
	 * @return array Public XMLRPC methods, with the getOptions one.
5632
	 */
5633 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5634
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5635
5636
		if ( ! $this->connection_manager ) {
5637
			$this->connection_manager = new Connection_Manager();
5638
		}
5639
5640
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5641
	}
5642
5643
	/**
5644
	 * Handles a getOptions XMLRPC method call.
5645
	 *
5646
	 * @deprecated since 7.7.0
5647
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5648
	 *
5649
	 * @param array $args method call arguments.
5650
	 * @return array an amended XMLRPC server options array.
5651
	 */
5652 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5653
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5654
5655
		if ( ! $this->connection_manager ) {
5656
			$this->connection_manager = new Connection_Manager();
5657
		}
5658
5659
		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...
5660
	}
5661
5662
	/**
5663
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5664
	 *
5665
	 * @deprecated since 7.7.0
5666
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5667
	 *
5668
	 * @param array $options Standard Core options.
5669
	 * @return array Amended options.
5670
	 */
5671 View Code Duplication
	public function xmlrpc_options( $options ) {
5672
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5673
5674
		if ( ! $this->connection_manager ) {
5675
			$this->connection_manager = new Connection_Manager();
5676
		}
5677
5678
		return $this->connection_manager->xmlrpc_options( $options );
5679
	}
5680
5681
	/**
5682
	 * Cleans nonces that were saved when calling ::add_nonce.
5683
	 *
5684
	 * @deprecated since 7.7.0
5685
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5686
	 *
5687
	 * @param bool $all whether to clean even non-expired nonces.
5688
	 */
5689
	public static function clean_nonces( $all = false ) {
5690
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5691
		return self::connection()->clean_nonces( $all );
5692
	}
5693
5694
	/**
5695
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5696
	 * SET: state( $key, $value );
5697
	 * GET: $value = state( $key );
5698
	 *
5699
	 * @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...
5700
	 * @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...
5701
	 * @param bool   $restate private
5702
	 */
5703
	public static function state( $key = null, $value = null, $restate = false ) {
5704
		static $state = array();
5705
		static $path, $domain;
5706
		if ( ! isset( $path ) ) {
5707
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5708
			$admin_url = self::admin_url();
5709
			$bits      = wp_parse_url( $admin_url );
5710
5711
			if ( is_array( $bits ) ) {
5712
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5713
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5714
			} else {
5715
				$path = $domain = null;
5716
			}
5717
		}
5718
5719
		// Extract state from cookies and delete cookies
5720
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5721
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5722
			unset( $_COOKIE['jetpackState'] );
5723
			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...
5724
				if ( strlen( $v ) ) {
5725
					$state[ $k ] = $v;
5726
				}
5727
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5728
			}
5729
		}
5730
5731
		if ( $restate ) {
5732
			foreach ( $state as $k => $v ) {
5733
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5734
			}
5735
			return;
5736
		}
5737
5738
		// Get a state variable.
5739
		if ( isset( $key ) && ! isset( $value ) ) {
5740
			if ( array_key_exists( $key, $state ) ) {
5741
				return $state[ $key ];
5742
			}
5743
			return null;
5744
		}
5745
5746
		// Set a state variable.
5747
		if ( isset( $key ) && isset( $value ) ) {
5748
			if ( is_array( $value ) && isset( $value[0] ) ) {
5749
				$value = $value[0];
5750
			}
5751
			$state[ $key ] = $value;
5752
			if ( ! headers_sent() ) {
5753
				if ( self::should_set_cookie( $key ) ) {
5754
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5755
				}
5756
			}
5757
		}
5758
	}
5759
5760
	public static function restate() {
5761
		self::state( null, null, true );
5762
	}
5763
5764
	/**
5765
	 * Determines whether the jetpackState[$key] value should be added to the
5766
	 * cookie.
5767
	 *
5768
	 * @param string $key The state key.
5769
	 *
5770
	 * @return boolean Whether the value should be added to the cookie.
5771
	 */
5772
	public static function should_set_cookie( $key ) {
5773
		global $current_screen;
5774
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5775
5776
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5777
			return false;
5778
		}
5779
5780
		return true;
5781
	}
5782
5783
	public static function check_privacy( $file ) {
5784
		static $is_site_publicly_accessible = null;
5785
5786
		if ( is_null( $is_site_publicly_accessible ) ) {
5787
			$is_site_publicly_accessible = false;
5788
5789
			$rpc = new Jetpack_IXR_Client();
5790
5791
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5792
			if ( $success ) {
5793
				$response = $rpc->getResponse();
5794
				if ( $response ) {
5795
					$is_site_publicly_accessible = true;
5796
				}
5797
			}
5798
5799
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5800
		}
5801
5802
		if ( $is_site_publicly_accessible ) {
5803
			return;
5804
		}
5805
5806
		$module_slug = self::get_module_slug( $file );
5807
5808
		$privacy_checks = self::state( 'privacy_checks' );
5809
		if ( ! $privacy_checks ) {
5810
			$privacy_checks = $module_slug;
5811
		} else {
5812
			$privacy_checks .= ",$module_slug";
5813
		}
5814
5815
		self::state( 'privacy_checks', $privacy_checks );
5816
	}
5817
5818
	/**
5819
	 * Helper method for multicall XMLRPC.
5820
	 *
5821
	 * @param ...$args Args for the async_call.
5822
	 */
5823
	public static function xmlrpc_async_call( ...$args ) {
5824
		global $blog_id;
5825
		static $clients = array();
5826
5827
		$client_blog_id = is_multisite() ? $blog_id : 0;
5828
5829
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5830
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5831
			if ( function_exists( 'ignore_user_abort' ) ) {
5832
				ignore_user_abort( true );
5833
			}
5834
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5835
		}
5836
5837
		if ( ! empty( $args[0] ) ) {
5838
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5839
		} elseif ( is_multisite() ) {
5840
			foreach ( $clients as $client_blog_id => $client ) {
5841
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5842
					continue;
5843
				}
5844
5845
				$switch_success = switch_to_blog( $client_blog_id, true );
5846
				if ( ! $switch_success ) {
5847
					continue;
5848
				}
5849
5850
				flush();
5851
				$client->query();
5852
5853
				restore_current_blog();
5854
			}
5855
		} else {
5856
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5857
				flush();
5858
				$clients[0]->query();
5859
			}
5860
		}
5861
	}
5862
5863
	public static function staticize_subdomain( $url ) {
5864
5865
		// Extract hostname from URL
5866
		$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...
5867
5868
		// Explode hostname on '.'
5869
		$exploded_host = explode( '.', $host );
5870
5871
		// Retrieve the name and TLD
5872
		if ( count( $exploded_host ) > 1 ) {
5873
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5874
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5875
			// Rebuild domain excluding subdomains
5876
			$domain = $name . '.' . $tld;
5877
		} else {
5878
			$domain = $host;
5879
		}
5880
		// Array of Automattic domains.
5881
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5882
5883
		// Return $url if not an Automattic domain.
5884
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5885
			return $url;
5886
		}
5887
5888
		if ( is_ssl() ) {
5889
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5890
		}
5891
5892
		srand( crc32( basename( $url ) ) );
5893
		$static_counter = rand( 0, 2 );
5894
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5895
5896
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5897
	}
5898
5899
	/* JSON API Authorization */
5900
5901
	/**
5902
	 * Handles the login action for Authorizing the JSON API
5903
	 */
5904
	function login_form_json_api_authorization() {
5905
		$this->verify_json_api_authorization_request();
5906
5907
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5908
5909
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5910
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5911
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5912
	}
5913
5914
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5915
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5916
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5917
			return $url;
5918
		}
5919
5920
		$parsed_url = wp_parse_url( $url );
5921
		$url        = strtok( $url, '?' );
5922
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5923
		if ( ! empty( $parsed_url['query'] ) ) {
5924
			$url .= "&{$parsed_url['query']}";
5925
		}
5926
5927
		return $url;
5928
	}
5929
5930
	// Make sure the POSTed request is handled by the same action
5931
	function preserve_action_in_login_form_for_json_api_authorization() {
5932
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5933
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5934
	}
5935
5936
	// If someone logs in to approve API access, store the Access Code in usermeta
5937
	function store_json_api_authorization_token( $user_login, $user ) {
5938
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5939
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5940
		$token = wp_generate_password( 32, false );
5941
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5942
	}
5943
5944
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5945
	function allow_wpcom_public_api_domain( $domains ) {
5946
		$domains[] = 'public-api.wordpress.com';
5947
		return $domains;
5948
	}
5949
5950
	static function is_redirect_encoded( $redirect_url ) {
5951
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5952
	}
5953
5954
	// Add all wordpress.com environments to the safe redirect allowed list.
5955
	function allow_wpcom_environments( $domains ) {
5956
		$domains[] = 'wordpress.com';
5957
		$domains[] = 'wpcalypso.wordpress.com';
5958
		$domains[] = 'horizon.wordpress.com';
5959
		$domains[] = 'calypso.localhost';
5960
		return $domains;
5961
	}
5962
5963
	// Add the Access Code details to the public-api.wordpress.com redirect
5964
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5965
		return add_query_arg(
5966
			urlencode_deep(
5967
				array(
5968
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5969
					'jetpack-user-id' => (int) $user->ID,
5970
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5971
				)
5972
			),
5973
			$redirect_to
5974
		);
5975
	}
5976
5977
5978
	/**
5979
	 * Verifies the request by checking the signature
5980
	 *
5981
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5982
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5983
	 *
5984
	 * @param null|array $environment
5985
	 */
5986
	function verify_json_api_authorization_request( $environment = null ) {
5987
		$environment = is_null( $environment )
5988
			? $_REQUEST
5989
			: $environment;
5990
5991
		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...
5992
		$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...
5993
		if ( ! $token || empty( $token->secret ) ) {
5994
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5995
		}
5996
5997
		$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' );
5998
5999
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6000
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6001
			/**
6002
			 * Jetpack authorisation request Error.
6003
			 *
6004
			 * @since 7.5.0
6005
			 */
6006
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6007
			$die_error = sprintf(
6008
				/* translators: %s is a URL */
6009
				__( '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' ),
6010
				Redirect::get_url( 'jetpack-support-double-encoding' )
6011
			);
6012
		}
6013
6014
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6015
6016
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6017
			$signature = $jetpack_signature->sign_request(
6018
				$environment['token'],
6019
				$environment['timestamp'],
6020
				$environment['nonce'],
6021
				'',
6022
				'GET',
6023
				$environment['jetpack_json_api_original_query'],
6024
				null,
6025
				true
6026
			);
6027
		} else {
6028
			$signature = $jetpack_signature->sign_current_request(
6029
				array(
6030
					'body'   => null,
6031
					'method' => 'GET',
6032
				)
6033
			);
6034
		}
6035
6036
		if ( ! $signature ) {
6037
			wp_die( $die_error );
6038
		} elseif ( is_wp_error( $signature ) ) {
6039
			wp_die( $die_error );
6040
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6041
			if ( is_ssl() ) {
6042
				// 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
6043
				$signature = $jetpack_signature->sign_current_request(
6044
					array(
6045
						'scheme' => 'http',
6046
						'body'   => null,
6047
						'method' => 'GET',
6048
					)
6049
				);
6050
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6051
					wp_die( $die_error );
6052
				}
6053
			} else {
6054
				wp_die( $die_error );
6055
			}
6056
		}
6057
6058
		$timestamp = (int) $environment['timestamp'];
6059
		$nonce     = stripslashes( (string) $environment['nonce'] );
6060
6061
		if ( ! $this->connection_manager ) {
6062
			$this->connection_manager = new Connection_Manager();
6063
		}
6064
6065
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6066
			// De-nonce the nonce, at least for 5 minutes.
6067
			// 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)
6068
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6069
			if ( $old_nonce_time < time() - 300 ) {
6070
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6071
			}
6072
		}
6073
6074
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6075
		$data_filters = array(
6076
			'state'        => 'opaque',
6077
			'client_id'    => 'int',
6078
			'client_title' => 'string',
6079
			'client_image' => 'url',
6080
		);
6081
6082
		foreach ( $data_filters as $key => $sanitation ) {
6083
			if ( ! isset( $data->$key ) ) {
6084
				wp_die( $die_error );
6085
			}
6086
6087
			switch ( $sanitation ) {
6088
				case 'int':
6089
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6090
					break;
6091
				case 'opaque':
6092
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6093
					break;
6094
				case 'string':
6095
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6096
					break;
6097
				case 'url':
6098
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6099
					break;
6100
			}
6101
		}
6102
6103
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6104
			wp_die( $die_error );
6105
		}
6106
	}
6107
6108
	function login_message_json_api_authorization( $message ) {
6109
		return '<p class="message">' . sprintf(
6110
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6111
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6112
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6113
	}
6114
6115
	/**
6116
	 * Get $content_width, but with a <s>twist</s> filter.
6117
	 */
6118
	public static function get_content_width() {
6119
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6120
			? $GLOBALS['content_width']
6121
			: false;
6122
		/**
6123
		 * Filter the Content Width value.
6124
		 *
6125
		 * @since 2.2.3
6126
		 *
6127
		 * @param string $content_width Content Width value.
6128
		 */
6129
		return apply_filters( 'jetpack_content_width', $content_width );
6130
	}
6131
6132
	/**
6133
	 * Pings the WordPress.com Mirror Site for the specified options.
6134
	 *
6135
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6136
	 *
6137
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6138
	 */
6139
	public function get_cloud_site_options( $option_names ) {
6140
		$option_names = array_filter( (array) $option_names, 'is_string' );
6141
6142
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6143
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6144
		if ( $xml->isError() ) {
6145
			return array(
6146
				'error_code' => $xml->getErrorCode(),
6147
				'error_msg'  => $xml->getErrorMessage(),
6148
			);
6149
		}
6150
		$cloud_site_options = $xml->getResponse();
6151
6152
		return $cloud_site_options;
6153
	}
6154
6155
	/**
6156
	 * Checks if the site is currently in an identity crisis.
6157
	 *
6158
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6159
	 */
6160
	public static function check_identity_crisis() {
6161
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6162
			return false;
6163
		}
6164
6165
		return Jetpack_Options::get_option( 'sync_error_idc' );
6166
	}
6167
6168
	/**
6169
	 * Checks whether the home and siteurl specifically are allowed.
6170
	 * Written so that we don't have re-check $key and $value params every time
6171
	 * we want to check if this site is allowed, for example in footer.php
6172
	 *
6173
	 * @since  3.8.0
6174
	 * @return bool True = already allowed False = not on the allowed list.
6175
	 */
6176
	public static function is_staging_site() {
6177
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6178
		return ( new Status() )->is_staging_site();
6179
	}
6180
6181
	/**
6182
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6183
	 *
6184
	 * @since 4.4.0
6185
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6186
	 *
6187
	 * @return bool
6188
	 */
6189
	public static function validate_sync_error_idc_option() {
6190
		$is_valid = false;
6191
6192
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6193
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6194
		if ( $sync_error && self::sync_idc_optin() ) {
6195
			$local_options = self::get_sync_error_idc_option();
6196
			// Ensure all values are set.
6197
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6198
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6199
					$is_valid = true;
6200
				}
6201
			}
6202
		}
6203
6204
		/**
6205
		 * Filters whether the sync_error_idc option is valid.
6206
		 *
6207
		 * @since 4.4.0
6208
		 *
6209
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6210
		 */
6211
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6212
6213
		if ( ! $is_valid && $sync_error ) {
6214
			// Since the option exists, and did not validate, delete it
6215
			Jetpack_Options::delete_option( 'sync_error_idc' );
6216
		}
6217
6218
		return $is_valid;
6219
	}
6220
6221
	/**
6222
	 * Normalizes a url by doing three things:
6223
	 *  - Strips protocol
6224
	 *  - Strips www
6225
	 *  - Adds a trailing slash
6226
	 *
6227
	 * @since 4.4.0
6228
	 * @param string $url
6229
	 * @return WP_Error|string
6230
	 */
6231
	public static function normalize_url_protocol_agnostic( $url ) {
6232
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6233 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6234
			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...
6235
		}
6236
6237
		// Strip www and protocols
6238
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6239
		return $url;
6240
	}
6241
6242
	/**
6243
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6244
	 *
6245
	 * @since 4.4.0
6246
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6247
	 *
6248
	 * @param array $response
6249
	 * @return array Array of the local urls, wpcom urls, and error code
6250
	 */
6251
	public static function get_sync_error_idc_option( $response = array() ) {
6252
		// Since the local options will hit the database directly, store the values
6253
		// in a transient to allow for autoloading and caching on subsequent views.
6254
		$local_options = get_transient( 'jetpack_idc_local' );
6255
		if ( false === $local_options ) {
6256
			$local_options = array(
6257
				'home'    => Functions::home_url(),
6258
				'siteurl' => Functions::site_url(),
6259
			);
6260
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6261
		}
6262
6263
		$options = array_merge( $local_options, $response );
6264
6265
		$returned_values = array();
6266
		foreach ( $options as $key => $option ) {
6267
			if ( 'error_code' === $key ) {
6268
				$returned_values[ $key ] = $option;
6269
				continue;
6270
			}
6271
6272
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6273
				continue;
6274
			}
6275
6276
			$returned_values[ $key ] = $normalized_url;
6277
		}
6278
6279
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6280
6281
		return $returned_values;
6282
	}
6283
6284
	/**
6285
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6286
	 * If set to true, the site will be put into staging mode.
6287
	 *
6288
	 * @since 4.3.2
6289
	 * @return bool
6290
	 */
6291
	public static function sync_idc_optin() {
6292
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6293
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6294
		} else {
6295
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6296
		}
6297
6298
		/**
6299
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6300
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6301
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6302
		 *
6303
		 * @since 4.3.2
6304
		 *
6305
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6306
		 */
6307
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6308
	}
6309
6310
	/**
6311
	 * Maybe Use a .min.css stylesheet, maybe not.
6312
	 *
6313
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6314
	 */
6315
	public static function maybe_min_asset( $url, $path, $plugin ) {
6316
		// Short out on things trying to find actual paths.
6317
		if ( ! $path || empty( $plugin ) ) {
6318
			return $url;
6319
		}
6320
6321
		$path = ltrim( $path, '/' );
6322
6323
		// Strip out the abspath.
6324
		$base = dirname( plugin_basename( $plugin ) );
6325
6326
		// Short out on non-Jetpack assets.
6327
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6328
			return $url;
6329
		}
6330
6331
		// File name parsing.
6332
		$file              = "{$base}/{$path}";
6333
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6334
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6335
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6336
		$extension         = array_shift( $file_name_parts_r );
6337
6338
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6339
			// Already pointing at the minified version.
6340
			if ( 'min' === $file_name_parts_r[0] ) {
6341
				return $url;
6342
			}
6343
6344
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6345
			if ( file_exists( $min_full_path ) ) {
6346
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6347
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6348
				if ( 'css' === $extension ) {
6349
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6350
					self::$min_assets[ $key ] = $path;
6351
				}
6352
			}
6353
		}
6354
6355
		return $url;
6356
	}
6357
6358
	/**
6359
	 * If the asset is minified, let's flag .min as the suffix.
6360
	 *
6361
	 * Attached to `style_loader_src` filter.
6362
	 *
6363
	 * @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...
6364
	 * @param string $handle The registered handle of the script in question.
6365
	 * @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...
6366
	 */
6367
	public static function set_suffix_on_min( $src, $handle ) {
6368
		if ( false === strpos( $src, '.min.css' ) ) {
6369
			return $src;
6370
		}
6371
6372
		if ( ! empty( self::$min_assets ) ) {
6373
			foreach ( self::$min_assets as $file => $path ) {
6374
				if ( false !== strpos( $src, $file ) ) {
6375
					wp_style_add_data( $handle, 'suffix', '.min' );
6376
					return $src;
6377
				}
6378
			}
6379
		}
6380
6381
		return $src;
6382
	}
6383
6384
	/**
6385
	 * Maybe inlines a stylesheet.
6386
	 *
6387
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6388
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6389
	 *
6390
	 * Attached to `style_loader_tag` filter.
6391
	 *
6392
	 * @param string $tag The tag that would link to the external asset.
6393
	 * @param string $handle The registered handle of the script in question.
6394
	 *
6395
	 * @return string
6396
	 */
6397
	public static function maybe_inline_style( $tag, $handle ) {
6398
		global $wp_styles;
6399
		$item = $wp_styles->registered[ $handle ];
6400
6401
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6402
			return $tag;
6403
		}
6404
6405
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6406
			$href = $matches[1];
6407
			// Strip off query string
6408
			if ( $pos = strpos( $href, '?' ) ) {
6409
				$href = substr( $href, 0, $pos );
6410
			}
6411
			// Strip off fragment
6412
			if ( $pos = strpos( $href, '#' ) ) {
6413
				$href = substr( $href, 0, $pos );
6414
			}
6415
		} else {
6416
			return $tag;
6417
		}
6418
6419
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6420
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6421
			return $tag;
6422
		}
6423
6424
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6425
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6426
			// And this isn't the pass that actually deals with the RTL version...
6427
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6428
				// Short out, as the RTL version will deal with it in a moment.
6429
				return $tag;
6430
			}
6431
		}
6432
6433
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6434
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6435
		if ( $css ) {
6436
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6437
			if ( empty( $item->extra['after'] ) ) {
6438
				wp_add_inline_style( $handle, $css );
6439
			} else {
6440
				array_unshift( $item->extra['after'], $css );
6441
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6442
			}
6443
		}
6444
6445
		return $tag;
6446
	}
6447
6448
	/**
6449
	 * Loads a view file from the views
6450
	 *
6451
	 * Data passed in with the $data parameter will be available in the
6452
	 * template file as $data['value']
6453
	 *
6454
	 * @param string $template - Template file to load
6455
	 * @param array  $data - Any data to pass along to the template
6456
	 * @return boolean - If template file was found
6457
	 **/
6458
	public function load_view( $template, $data = array() ) {
6459
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6460
6461
		if ( file_exists( $views_dir . $template ) ) {
6462
			require_once $views_dir . $template;
6463
			return true;
6464
		}
6465
6466
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6467
		return false;
6468
	}
6469
6470
	/**
6471
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6472
	 *
6473
	 * @todo Convert these to use apply_filters_deprecated and do_action_deprecated and remove custom code.
6474
	 */
6475
	public function deprecated_hooks() {
6476
		global $wp_filter;
6477
6478
		/*
6479
		 * Format:
6480
		 * deprecated_filter_name => replacement_name
6481
		 *
6482
		 * If there is no replacement, use null for replacement_name
6483
		 */
6484
		$deprecated_list = array(
6485
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6486
			'wpl_sharing_2014_1'                           => null,
6487
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6488
			'jetpack_identity_crisis_options_to_check'     => null,
6489
			'update_option_jetpack_single_user_site'       => null,
6490
			'audio_player_default_colors'                  => null,
6491
			'add_option_jetpack_featured_images_enabled'   => null,
6492
			'add_option_jetpack_update_details'            => null,
6493
			'add_option_jetpack_updates'                   => null,
6494
			'add_option_jetpack_network_name'              => null,
6495
			'add_option_jetpack_network_allow_new_registrations' => null,
6496
			'add_option_jetpack_network_add_new_users'     => null,
6497
			'add_option_jetpack_network_site_upload_space' => null,
6498
			'add_option_jetpack_network_upload_file_types' => null,
6499
			'add_option_jetpack_network_enable_administration_menus' => null,
6500
			'add_option_jetpack_is_multi_site'             => null,
6501
			'add_option_jetpack_is_main_network'           => null,
6502
			'add_option_jetpack_main_network_site'         => null,
6503
			'jetpack_sync_all_registered_options'          => null,
6504
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6505
			'jetpack_is_post_mailable'                     => null,
6506
			'jetpack_seo_site_host'                        => null,
6507
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6508
			'jetpack_holiday_snow_option_name'             => null,
6509
			'jetpack_holiday_chance_of_snow'               => null,
6510
			'jetpack_holiday_snow_js_url'                  => null,
6511
			'jetpack_is_holiday_snow_season'               => null,
6512
			'jetpack_holiday_snow_option_updated'          => null,
6513
			'jetpack_holiday_snowing'                      => null,
6514
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6515
			'jetpack_cache_plans'                          => null,
6516
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6517
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6518
			'jetpack_enable_site_verification'             => null,
6519
			// Removed in Jetpack 7.3.0
6520
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6521
			// Removed in Jetpack 7.9.0
6522
			'jetpack_pwa_manifest'                         => null,
6523
			'jetpack_pwa_background_color'                 => null,
6524
			// Removed in Jetpack 8.3.0.
6525
			'jetpack_check_mobile'                         => null,
6526
			'jetpack_mobile_stylesheet'                    => null,
6527
			'jetpack_mobile_template'                      => null,
6528
			'mobile_reject_mobile'                         => null,
6529
			'mobile_force_mobile'                          => null,
6530
			'mobile_app_promo_download'                    => null,
6531
			'mobile_setup'                                 => null,
6532
			'jetpack_mobile_footer_before'                 => null,
6533
			'wp_mobile_theme_footer'                       => null,
6534
			'minileven_credits'                            => null,
6535
			'jetpack_mobile_header_before'                 => null,
6536
			'jetpack_mobile_header_after'                  => null,
6537
			'jetpack_mobile_theme_menu'                    => null,
6538
			'minileven_show_featured_images'               => null,
6539
			'minileven_attachment_size'                    => null,
6540
		);
6541
6542
		// This is a silly loop depth. Better way?
6543
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6544
			if ( has_action( $hook ) ) {
6545
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6546
					foreach ( $values as $hooked ) {
6547
						if ( is_callable( $hooked['function'] ) ) {
6548
							$function_name = $hooked['function'];
6549
						} else {
6550
							$function_name = 'an anonymous function';
6551
						}
6552
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6553
					}
6554
				}
6555
			}
6556
		}
6557
6558
		$filter_deprecated_list = array(
6559
			'can_display_jetpack_manage_notice' => array(
6560
				'replacement' => null,
6561
				'version'     => 'jetpack-7.3.0',
6562
			),
6563
			'atd_http_post_timeout'             => array(
6564
				'replacement' => null,
6565
				'version'     => 'jetpack-7.3.0',
6566
			),
6567
			'atd_service_domain'                => array(
6568
				'replacement' => null,
6569
				'version'     => 'jetpack-7.3.0',
6570
			),
6571
			'atd_load_scripts'                  => array(
6572
				'replacement' => null,
6573
				'version'     => 'jetpack-7.3.0',
6574
			),
6575
		);
6576
6577
		foreach ( $filter_deprecated_list as $tag => $args ) {
6578
			if ( has_filter( $tag ) ) {
6579
				apply_filters_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6580
			}
6581
		}
6582
6583
		$action_deprecated_list = array(
6584
			'atd_http_post_error' => array(
6585
				'replacement' => null,
6586
				'version'     => 'jetpack-7.3.0',
6587
			),
6588
		);
6589
6590
		foreach ( $action_deprecated_list as $tag => $args ) {
6591
			if ( has_action( $tag ) ) {
6592
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6593
			}
6594
		}
6595
	}
6596
6597
	/**
6598
	 * Converts any url in a stylesheet, to the correct absolute url.
6599
	 *
6600
	 * Considerations:
6601
	 *  - Normal, relative URLs     `feh.png`
6602
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6603
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6604
	 *  - Absolute URLs             `http://domain.com/feh.png`
6605
	 *  - Domain root relative URLs `/feh.png`
6606
	 *
6607
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6608
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6609
	 *
6610
	 * @return mixed|string
6611
	 */
6612
	public static function absolutize_css_urls( $css, $css_file_url ) {
6613
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6614
		$css_dir = dirname( $css_file_url );
6615
		$p       = wp_parse_url( $css_dir );
6616
		$domain  = sprintf(
6617
			'%1$s//%2$s%3$s%4$s',
6618
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6619
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6620
			$p['host'],
6621
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6622
		);
6623
6624
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6625
			$find = $replace = array();
6626
			foreach ( $matches as $match ) {
6627
				$url = trim( $match['path'], "'\" \t" );
6628
6629
				// If this is a data url, we don't want to mess with it.
6630
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6631
					continue;
6632
				}
6633
6634
				// If this is an absolute or protocol-agnostic url,
6635
				// we don't want to mess with it.
6636
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6637
					continue;
6638
				}
6639
6640
				switch ( substr( $url, 0, 1 ) ) {
6641
					case '/':
6642
						$absolute = $domain . $url;
6643
						break;
6644
					default:
6645
						$absolute = $css_dir . '/' . $url;
6646
				}
6647
6648
				$find[]    = $match[0];
6649
				$replace[] = sprintf( 'url("%s")', $absolute );
6650
			}
6651
			$css = str_replace( $find, $replace, $css );
6652
		}
6653
6654
		return $css;
6655
	}
6656
6657
	/**
6658
	 * This methods removes all of the registered css files on the front end
6659
	 * from Jetpack in favor of using a single file. In effect "imploding"
6660
	 * all the files into one file.
6661
	 *
6662
	 * Pros:
6663
	 * - Uses only ONE css asset connection instead of 15
6664
	 * - Saves a minimum of 56k
6665
	 * - Reduces server load
6666
	 * - Reduces time to first painted byte
6667
	 *
6668
	 * Cons:
6669
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6670
	 *      should not cause any issues with themes.
6671
	 * - Plugins/themes dequeuing styles no longer do anything. See
6672
	 *      jetpack_implode_frontend_css filter for a workaround
6673
	 *
6674
	 * For some situations developers may wish to disable css imploding and
6675
	 * instead operate in legacy mode where each file loads seperately and
6676
	 * can be edited individually or dequeued. This can be accomplished with
6677
	 * the following line:
6678
	 *
6679
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6680
	 *
6681
	 * @since 3.2
6682
	 **/
6683
	public function implode_frontend_css( $travis_test = false ) {
6684
		$do_implode = true;
6685
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6686
			$do_implode = false;
6687
		}
6688
6689
		// Do not implode CSS when the page loads via the AMP plugin.
6690
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6691
			$do_implode = false;
6692
		}
6693
6694
		/**
6695
		 * Allow CSS to be concatenated into a single jetpack.css file.
6696
		 *
6697
		 * @since 3.2.0
6698
		 *
6699
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6700
		 */
6701
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6702
6703
		// Do not use the imploded file when default behavior was altered through the filter
6704
		if ( ! $do_implode ) {
6705
			return;
6706
		}
6707
6708
		// We do not want to use the imploded file in dev mode, or if not connected
6709
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6710
			if ( ! $travis_test ) {
6711
				return;
6712
			}
6713
		}
6714
6715
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6716
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6717
			return;
6718
		}
6719
6720
		/*
6721
		 * Now we assume Jetpack is connected and able to serve the single
6722
		 * file.
6723
		 *
6724
		 * In the future there will be a check here to serve the file locally
6725
		 * or potentially from the Jetpack CDN
6726
		 *
6727
		 * For now:
6728
		 * - Enqueue a single imploded css file
6729
		 * - Zero out the style_loader_tag for the bundled ones
6730
		 * - Be happy, drink scotch
6731
		 */
6732
6733
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6734
6735
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6736
6737
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6738
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6739
	}
6740
6741
	function concat_remove_style_loader_tag( $tag, $handle ) {
6742
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6743
			$tag = '';
6744
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6745
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6746
			}
6747
		}
6748
6749
		return $tag;
6750
	}
6751
6752
	/**
6753
	 * @deprecated
6754
	 * @see Automattic\Jetpack\Assets\add_aync_script
6755
	 */
6756
	public function script_add_async( $tag, $handle, $src ) {
6757
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6758
	}
6759
6760
	/*
6761
	 * Check the heartbeat data
6762
	 *
6763
	 * Organizes the heartbeat data by severity.  For example, if the site
6764
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6765
	 *
6766
	 * Data will be added to "caution" array, if it either:
6767
	 *  - Out of date Jetpack version
6768
	 *  - Out of date WP version
6769
	 *  - Out of date PHP version
6770
	 *
6771
	 * $return array $filtered_data
6772
	 */
6773
	public static function jetpack_check_heartbeat_data() {
6774
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6775
6776
		$good    = array();
6777
		$caution = array();
6778
		$bad     = array();
6779
6780
		foreach ( $raw_data as $stat => $value ) {
6781
6782
			// Check jetpack version
6783
			if ( 'version' == $stat ) {
6784
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6785
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6786
					continue;
6787
				}
6788
			}
6789
6790
			// Check WP version
6791
			if ( 'wp-version' == $stat ) {
6792
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6793
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6794
					continue;
6795
				}
6796
			}
6797
6798
			// Check PHP version
6799
			if ( 'php-version' == $stat ) {
6800
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6801
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6802
					continue;
6803
				}
6804
			}
6805
6806
			// Check ID crisis
6807
			if ( 'identitycrisis' == $stat ) {
6808
				if ( 'yes' == $value ) {
6809
					$bad[ $stat ] = $value;
6810
					continue;
6811
				}
6812
			}
6813
6814
			// The rest are good :)
6815
			$good[ $stat ] = $value;
6816
		}
6817
6818
		$filtered_data = array(
6819
			'good'    => $good,
6820
			'caution' => $caution,
6821
			'bad'     => $bad,
6822
		);
6823
6824
		return $filtered_data;
6825
	}
6826
6827
6828
	/*
6829
	 * This method is used to organize all options that can be reset
6830
	 * without disconnecting Jetpack.
6831
	 *
6832
	 * It is used in class.jetpack-cli.php to reset options
6833
	 *
6834
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6835
	 *
6836
	 * @return array of options to delete.
6837
	 */
6838
	public static function get_jetpack_options_for_reset() {
6839
		return Jetpack_Options::get_options_for_reset();
6840
	}
6841
6842
	/*
6843
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6844
	 * so we can bring them directly to their site in calypso.
6845
	 *
6846
	 * @param string | url
6847
	 * @return string | url without the guff
6848
	 */
6849 View Code Duplication
	public static function build_raw_urls( $url ) {
6850
		$strip_http = '/.*?:\/\//i';
6851
		$url        = preg_replace( $strip_http, '', $url );
6852
		$url        = str_replace( '/', '::', $url );
6853
		return $url;
6854
	}
6855
6856
	/**
6857
	 * Stores and prints out domains to prefetch for page speed optimization.
6858
	 *
6859
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6860
	 *
6861
	 * @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...
6862
	 */
6863
	public static function dns_prefetch( $urls = null ) {
6864
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6865
		if ( $urls ) {
6866
			Assets::add_resource_hint( $urls );
6867
		}
6868
	}
6869
6870
	public function wp_dashboard_setup() {
6871
		if ( self::is_active() ) {
6872
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6873
		}
6874
6875
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6876
			$jetpack_logo = new Jetpack_Logo();
6877
			$widget_title = sprintf(
6878
				wp_kses(
6879
					/* translators: Placeholder is a Jetpack logo. */
6880
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6881
					array( 'span' => array() )
6882
				),
6883
				$jetpack_logo->get_jp_emblem( true )
6884
			);
6885
6886
			wp_add_dashboard_widget(
6887
				'jetpack_summary_widget',
6888
				$widget_title,
6889
				array( __CLASS__, 'dashboard_widget' )
6890
			);
6891
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6892
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6893
6894
			// If we're inactive and not in offline mode, sort our box to the top.
6895
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6896
				global $wp_meta_boxes;
6897
6898
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6899
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6900
6901
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6902
			}
6903
		}
6904
	}
6905
6906
	/**
6907
	 * @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...
6908
	 * @return mixed
6909
	 */
6910
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6911
		if ( ! is_array( $sorted ) ) {
6912
			return $sorted;
6913
		}
6914
6915
		foreach ( $sorted as $box_context => $ids ) {
6916
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6917
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6918
				continue;
6919
			}
6920
6921
			$ids_array = explode( ',', $ids );
6922
			$key       = array_search( 'dashboard_stats', $ids_array );
6923
6924
			if ( false !== $key ) {
6925
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6926
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6927
				$sorted[ $box_context ] = implode( ',', $ids_array );
6928
				// We've found it, stop searching, and just return.
6929
				break;
6930
			}
6931
		}
6932
6933
		return $sorted;
6934
	}
6935
6936
	public static function dashboard_widget() {
6937
		/**
6938
		 * Fires when the dashboard is loaded.
6939
		 *
6940
		 * @since 3.4.0
6941
		 */
6942
		do_action( 'jetpack_dashboard_widget' );
6943
	}
6944
6945
	public static function dashboard_widget_footer() {
6946
		?>
6947
		<footer>
6948
6949
		<div class="protect">
6950
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6951
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6952
				<p class="blocked-count">
6953
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6954
				</p>
6955
				<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>
6956
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
6957
				<a href="
6958
				<?php
6959
				echo esc_url(
6960
					wp_nonce_url(
6961
						self::admin_url(
6962
							array(
6963
								'action' => 'activate',
6964
								'module' => 'protect',
6965
							)
6966
						),
6967
						'jetpack_activate-protect'
6968
					)
6969
				);
6970
				?>
6971
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6972
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6973
				</a>
6974
			<?php else : ?>
6975
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6976
			<?php endif; ?>
6977
		</div>
6978
6979
		<div class="akismet">
6980
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6981
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6982
				<p class="blocked-count">
6983
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6984
				</p>
6985
				<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>
6986
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6987
				<a href="
6988
				<?php
6989
				echo esc_url(
6990
					wp_nonce_url(
6991
						add_query_arg(
6992
							array(
6993
								'action' => 'activate',
6994
								'plugin' => 'akismet/akismet.php',
6995
							),
6996
							admin_url( 'plugins.php' )
6997
						),
6998
						'activate-plugin_akismet/akismet.php'
6999
					)
7000
				);
7001
				?>
7002
							" class="button button-jetpack">
7003
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7004
				</a>
7005
			<?php else : ?>
7006
				<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>
7007
			<?php endif; ?>
7008
		</div>
7009
7010
		</footer>
7011
		<?php
7012
	}
7013
7014
	/*
7015
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7016
	 */
7017
	function jetpack_icon_user_connected( $columns ) {
7018
		$columns['user_jetpack'] = '';
7019
		return $columns;
7020
	}
7021
7022
	/*
7023
	 * Show Jetpack icon if the user is linked.
7024
	 */
7025
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7026
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7027
			$jetpack_logo = new Jetpack_Logo();
7028
			$emblem_html  = sprintf(
7029
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7030
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7031
				$jetpack_logo->get_jp_emblem()
7032
			);
7033
			return $emblem_html;
7034
		}
7035
7036
		return $val;
7037
	}
7038
7039
	/*
7040
	 * Style the Jetpack user column
7041
	 */
7042
	function jetpack_user_col_style() {
7043
		global $current_screen;
7044
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7045
			?>
7046
			<style>
7047
				.fixed .column-user_jetpack {
7048
					width: 21px;
7049
				}
7050
				.jp-emblem-user-admin svg {
7051
					width: 20px;
7052
					height: 20px;
7053
				}
7054
				.jp-emblem-user-admin path {
7055
					fill: #00BE28;
7056
				}
7057
			</style>
7058
			<?php
7059
		}
7060
	}
7061
7062
	/**
7063
	 * Checks if Akismet is active and working.
7064
	 *
7065
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7066
	 * that implied usage of methods present since more recent version.
7067
	 * See https://github.com/Automattic/jetpack/pull/9585
7068
	 *
7069
	 * @since  5.1.0
7070
	 *
7071
	 * @return bool True = Akismet available. False = Aksimet not available.
7072
	 */
7073
	public static function is_akismet_active() {
7074
		static $status = null;
7075
7076
		if ( ! is_null( $status ) ) {
7077
			return $status;
7078
		}
7079
7080
		// Check if a modern version of Akismet is active.
7081
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7082
			$status = false;
7083
			return $status;
7084
		}
7085
7086
		// Make sure there is a key known to Akismet at all before verifying key.
7087
		$akismet_key = Akismet::get_api_key();
7088
		if ( ! $akismet_key ) {
7089
			$status = false;
7090
			return $status;
7091
		}
7092
7093
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7094
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7095
7096
		// 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.
7097
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7098
		// We cache the result of the Akismet key verification for ten minutes.
7099
		if ( ! $akismet_key_state || $recheck ) {
7100
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7101
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7102
		}
7103
7104
		$status = 'valid' === $akismet_key_state;
7105
7106
		return $status;
7107
	}
7108
7109
	/**
7110
	 * @deprecated
7111
	 *
7112
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7113
	 */
7114
	public static function is_function_in_backtrace() {
7115
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7116
	}
7117
7118
	/**
7119
	 * Given a minified path, and a non-minified path, will return
7120
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7121
	 *
7122
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7123
	 * root Jetpack directory.
7124
	 *
7125
	 * @since 5.6.0
7126
	 *
7127
	 * @param string $min_path
7128
	 * @param string $non_min_path
7129
	 * @return string The URL to the file
7130
	 */
7131
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7132
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7133
	}
7134
7135
	/**
7136
	 * Checks for whether Jetpack Backup is enabled.
7137
	 * Will return true if the state of Backup is anything except "unavailable".
7138
	 *
7139
	 * @return bool|int|mixed
7140
	 */
7141
	public static function is_rewind_enabled() {
7142
		if ( ! self::is_active() ) {
7143
			return false;
7144
		}
7145
7146
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7147
		if ( false === $rewind_enabled ) {
7148
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7149
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7150
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7151
				&& ! empty( $rewind_data['state'] )
7152
				&& 'active' === $rewind_data['state'] )
7153
				? 1
7154
				: 0;
7155
7156
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7157
		}
7158
		return $rewind_enabled;
7159
	}
7160
7161
	/**
7162
	 * Return Calypso environment value; used for developing Jetpack and pairing
7163
	 * it with different Calypso enrionments, such as localhost.
7164
	 *
7165
	 * @since 7.4.0
7166
	 *
7167
	 * @return string Calypso environment
7168
	 */
7169
	public static function get_calypso_env() {
7170
		if ( isset( $_GET['calypso_env'] ) ) {
7171
			return sanitize_key( $_GET['calypso_env'] );
7172
		}
7173
7174
		if ( getenv( 'CALYPSO_ENV' ) ) {
7175
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7176
		}
7177
7178
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7179
			return sanitize_key( CALYPSO_ENV );
7180
		}
7181
7182
		return '';
7183
	}
7184
7185
	/**
7186
	 * Returns the hostname with protocol for Calypso.
7187
	 * Used for developing Jetpack with Calypso.
7188
	 *
7189
	 * @since 8.4.0
7190
	 *
7191
	 * @return string Calypso host.
7192
	 */
7193
	public static function get_calypso_host() {
7194
		$calypso_env = self::get_calypso_env();
7195
		switch ( $calypso_env ) {
7196
			case 'development':
7197
				return 'http://calypso.localhost:3000/';
7198
			case 'wpcalypso':
7199
				return 'https://wpcalypso.wordpress.com/';
7200
			case 'horizon':
7201
				return 'https://horizon.wordpress.com/';
7202
			default:
7203
				return 'https://wordpress.com/';
7204
		}
7205
	}
7206
7207
	/**
7208
	 * Checks whether or not TOS has been agreed upon.
7209
	 * Will return true if a user has clicked to register, or is already connected.
7210
	 */
7211
	public static function jetpack_tos_agreed() {
7212
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7213
7214
		$terms_of_service = new Terms_Of_Service();
7215
		return $terms_of_service->has_agreed();
7216
7217
	}
7218
7219
	/**
7220
	 * Handles activating default modules as well general cleanup for the new connection.
7221
	 *
7222
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7223
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7224
	 * @param boolean $send_state_messages          Whether to send state messages.
7225
	 * @return void
7226
	 */
7227
	public static function handle_post_authorization_actions(
7228
		$activate_sso = false,
7229
		$redirect_on_activation_error = false,
7230
		$send_state_messages = true
7231
	) {
7232
		$other_modules = $activate_sso
7233
			? array( 'sso' )
7234
			: array();
7235
7236
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7237
			self::delete_active_modules();
7238
7239
			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...
7240
		} else {
7241
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7242
		}
7243
7244
		// Since this is a fresh connection, be sure to clear out IDC options
7245
		Jetpack_IDC::clear_all_idc_options();
7246
7247
		if ( $send_state_messages ) {
7248
			self::state( 'message', 'authorized' );
7249
		}
7250
	}
7251
7252
	/**
7253
	 * Returns a boolean for whether backups UI should be displayed or not.
7254
	 *
7255
	 * @return bool Should backups UI be displayed?
7256
	 */
7257
	public static function show_backups_ui() {
7258
		/**
7259
		 * Whether UI for backups should be displayed.
7260
		 *
7261
		 * @since 6.5.0
7262
		 *
7263
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7264
		 */
7265
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7266
	}
7267
7268
	/*
7269
	 * Deprecated manage functions
7270
	 */
7271
	function prepare_manage_jetpack_notice() {
7272
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7273
	}
7274
	function manage_activate_screen() {
7275
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7276
	}
7277
	function admin_jetpack_manage_notice() {
7278
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7279
	}
7280
	function opt_out_jetpack_manage_url() {
7281
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7282
	}
7283
	function opt_in_jetpack_manage_url() {
7284
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7285
	}
7286
	function opt_in_jetpack_manage_notice() {
7287
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7288
	}
7289
	function can_display_jetpack_manage_notice() {
7290
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7291
	}
7292
7293
	/**
7294
	 * Clean leftoveruser meta.
7295
	 *
7296
	 * Delete Jetpack-related user meta when it is no longer needed.
7297
	 *
7298
	 * @since 7.3.0
7299
	 *
7300
	 * @param int $user_id User ID being updated.
7301
	 */
7302
	public static function user_meta_cleanup( $user_id ) {
7303
		$meta_keys = array(
7304
			// AtD removed from Jetpack 7.3
7305
			'AtD_options',
7306
			'AtD_check_when',
7307
			'AtD_guess_lang',
7308
			'AtD_ignored_phrases',
7309
		);
7310
7311
		foreach ( $meta_keys as $meta_key ) {
7312
			if ( get_user_meta( $user_id, $meta_key ) ) {
7313
				delete_user_meta( $user_id, $meta_key );
7314
			}
7315
		}
7316
	}
7317
7318
	/**
7319
	 * Checks if a Jetpack site is both active and not in offline mode.
7320
	 *
7321
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7322
	 *
7323
	 * @deprecated 8.8.0
7324
	 *
7325
	 * @return bool True if Jetpack is active and not in offline mode.
7326
	 */
7327
	public static function is_active_and_not_development_mode() {
7328
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7329
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7330
			return false;
7331
		}
7332
		return true;
7333
	}
7334
7335
	/**
7336
	 * Checks if a Jetpack site is both active and not in offline mode.
7337
	 *
7338
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7339
	 *
7340
	 * @since 8.8.0
7341
	 *
7342
	 * @return bool True if Jetpack is active and not in offline mode.
7343
	 */
7344
	public static function is_active_and_not_offline_mode() {
7345
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7346
			return false;
7347
		}
7348
		return true;
7349
	}
7350
7351
	/**
7352
	 * Returns the list of products that we have available for purchase.
7353
	 */
7354
	public static function get_products_for_purchase() {
7355
		$products = array();
7356
		if ( ! is_multisite() ) {
7357
			$products[] = array(
7358
				'key'               => 'backup',
7359
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7360
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7361
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7362
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7363
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7364
				'options'           => array(
7365
					array(
7366
						'type'        => 'daily',
7367
						'slug'        => 'jetpack-backup-daily',
7368
						'key'         => 'jetpack_backup_daily',
7369
						'name'        => __( 'Daily Backups', 'jetpack' ),
7370
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7371
					),
7372
					array(
7373
						'type'        => 'realtime',
7374
						'slug'        => 'jetpack-backup-realtime',
7375
						'key'         => 'jetpack_backup_realtime',
7376
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7377
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7378
					),
7379
				),
7380
				'default_option'    => 'realtime',
7381
				'show_promotion'    => true,
7382
				'discount_percent'  => 70,
7383
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7384
			);
7385
7386
			$products[] = array(
7387
				'key'               => 'scan',
7388
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7389
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7390
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7391
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7392
				'show_promotion'    => true,
7393
				'discount_percent'  => 30,
7394
				'options'           => array(
7395
					array(
7396
						'type'      => 'scan',
7397
						'slug'      => 'jetpack-scan',
7398
						'key'       => 'jetpack_scan',
7399
						'name'      => __( 'Daily Scan', 'jetpack' ),
7400
					),
7401
				),
7402
				'default_option'    => 'scan',
7403
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7404
			);
7405
		}
7406
7407
		$products[] = array(
7408
			'key'               => 'search',
7409
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7410
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7411
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7412
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7413
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7414
			'options'           => array(
7415
				array(
7416
					'type'      => 'search',
7417
					'slug'      => 'jetpack-search',
7418
					'key'       => 'jetpack_search',
7419
					'name'      => __( 'Search', 'jetpack' ),
7420
				),
7421
			),
7422
			'tears'             => array(),
7423
			'default_option'    => 'search',
7424
			'show_promotion'    => false,
7425
			'included_in_plans' => array( 'search-plan' ),
7426
		);
7427
7428
		$products[] = array(
7429
			'key'               => 'anti-spam',
7430
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7431
			'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' ),
7432
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7433
			'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' ),
7434
			'options'           => array(
7435
				array(
7436
					'type'      => 'anti-spam',
7437
					'slug'      => 'jetpack-anti-spam',
7438
					'key'       => 'jetpack_anti_spam',
7439
					'name'      => __( 'Anti-Spam', 'jetpack' ),
7440
				),
7441
			),
7442
			'default_option'    => 'anti-spam',
7443
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7444
		);
7445
7446
		return $products;
7447
	}
7448
}
7449