Completed
Push — add/partial-reconnect ( ffa9f4...dfe562 )
by
unknown
07:36
created

Jetpack::do_stats()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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