Completed
Push — update/meta-descriptions-clean... ( 6da2f0 )
by Jeremy
09:26
created

class.jetpack.php (83 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Health;
15
use Automattic\Jetpack\Sync\Sender;
16
use Automattic\Jetpack\Sync\Users;
17
use Automattic\Jetpack\Terms_Of_Service;
18
use Automattic\Jetpack\Tracking;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
22
23
/*
24
Options:
25
jetpack_options (array)
26
	An array of options.
27
	@see Jetpack_Options::get_option_names()
28
29
jetpack_register (string)
30
	Temporary verification secrets.
31
32
jetpack_activated (int)
33
	1: the plugin was activated normally
34
	2: the plugin was activated on this site because of a network-wide activation
35
	3: the plugin was auto-installed
36
	4: the plugin was manually disconnected (but is still installed)
37
38
jetpack_active_modules (array)
39
	Array of active module slugs.
40
41
jetpack_do_activate (bool)
42
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
43
*/
44
45
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
46
47
class Jetpack {
48
	public $xmlrpc_server = null;
49
50
	private $rest_authentication_status = null;
51
52
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
53
54
	/**
55
	 * @var array The handles of styles that are concatenated into jetpack.css.
56
	 *
57
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
58
	 */
59
	public $concatenated_style_handles = array(
60
		'jetpack-carousel',
61
		'grunion.css',
62
		'the-neverending-homepage',
63
		'jetpack_likes',
64
		'jetpack_related-posts',
65
		'sharedaddy',
66
		'jetpack-slideshow',
67
		'presentations',
68
		'quiz',
69
		'jetpack-subscriptions',
70
		'jetpack-responsive-videos-style',
71
		'jetpack-social-menu',
72
		'tiled-gallery',
73
		'jetpack_display_posts_widget',
74
		'gravatar-profile-widget',
75
		'goodreads-widget',
76
		'jetpack_social_media_icons_widget',
77
		'jetpack-top-posts-widget',
78
		'jetpack_image_widget',
79
		'jetpack-my-community-widget',
80
		'jetpack-authors-widget',
81
		'wordads',
82
		'eu-cookie-law-style',
83
		'flickr-widget-style',
84
		'jetpack-search-widget',
85
		'jetpack-simple-payments-widget-style',
86
		'jetpack-widget-social-icons-styles',
87
	);
88
89
	/**
90
	 * Contains all assets that have had their URL rewritten to minified versions.
91
	 *
92
	 * @var array
93
	 */
94
	static $min_assets = array();
95
96
	public $plugins_to_deactivate = array(
97
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
98
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
99
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
100
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
101
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
102
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
103
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
104
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
105
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
106
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
107
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
108
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
109
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
110
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
111
	);
112
113
	/**
114
	 * Map of roles we care about, and their corresponding minimum capabilities.
115
	 *
116
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
117
	 *
118
	 * @access public
119
	 * @static
120
	 *
121
	 * @var array
122
	 */
123
	public static $capability_translations = array(
124
		'administrator' => 'manage_options',
125
		'editor'        => 'edit_others_posts',
126
		'author'        => 'publish_posts',
127
		'contributor'   => 'edit_posts',
128
		'subscriber'    => 'read',
129
	);
130
131
	/**
132
	 * Map of modules that have conflicts with plugins and should not be auto-activated
133
	 * if the plugins are active.  Used by filter_default_modules
134
	 *
135
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
136
	 * change `module-slug` and add this to your plugin:
137
	 *
138
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
139
	 * function my_jetpack_get_default_modules( $modules ) {
140
	 *     return array_diff( $modules, array( 'module-slug' ) );
141
	 * }
142
	 *
143
	 * @var array
144
	 */
145
	private $conflicting_plugins = array(
146
		'comments'           => array(
147
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
148
			'Disqus'                         => 'disqus-comment-system/disqus.php',
149
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
150
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
151
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
152
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
153
		),
154
		'comment-likes'      => array(
155
			'Epoch' => 'epoch/plugincore.php',
156
		),
157
		'contact-form'       => array(
158
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
159
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
160
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
161
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
162
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
163
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
164
		),
165
		'latex'              => array(
166
			'LaTeX for WordPress'     => 'latex/latex.php',
167
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
168
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
169
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
170
			'Enable Latex'            => 'enable-latex/enable-latex.php',
171
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
172
		),
173
		'protect'            => array(
174
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
175
			'Captcha'                           => 'captcha/captcha.php',
176
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
177
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
178
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
179
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
180
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
181
			'Security-protection'               => 'security-protection/security-protection.php',
182
			'Login Security'                    => 'login-security/login-security.php',
183
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
184
			'Wordfence Security'                => 'wordfence/wordfence.php',
185
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
186
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
187
		),
188
		'random-redirect'    => array(
189
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
190
		),
191
		'related-posts'      => array(
192
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
193
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
194
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
195
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
196
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
197
			'outbrain'                    => 'outbrain/outbrain.php',
198
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
199
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
200
		),
201
		'sharedaddy'         => array(
202
			'AddThis'     => 'addthis/addthis_social_widget.php',
203
			'Add To Any'  => 'add-to-any/add-to-any.php',
204
			'ShareThis'   => 'share-this/sharethis.php',
205
			'Shareaholic' => 'shareaholic/shareaholic.php',
206
		),
207
		'seo-tools'          => array(
208
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
209
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
210
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
211
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
212
			'The SEO Framework'              => 'autodescription/autodescription.php',
213
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
214
		),
215
		'verification-tools' => array(
216
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
217
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
218
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
219
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
220
			'The SEO Framework'              => 'autodescription/autodescription.php',
221
			'Rank Math'                      => 'seo-by-rank-math/rank-math.php',
222
		),
223
		'widget-visibility'  => array(
224
			'Widget Logic'    => 'widget-logic/widget_logic.php',
225
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
226
		),
227
		'sitemaps'           => array(
228
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
229
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
230
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
231
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
232
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
233
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
234
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
235
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
236
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
237
			'The SEO Framework'                    => 'autodescription/autodescription.php',
238
			'Sitemap'                              => 'sitemap/sitemap.php',
239
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
240
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
241
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
242
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
243
			'Rank Math'                            => 'seo-by-rank-math/rank-math.php',
244
		),
245
		'lazy-images'        => array(
246
			'Lazy Load'              => 'lazy-load/lazy-load.php',
247
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
248
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
249
		),
250
	);
251
252
	/**
253
	 * Plugins for which we turn off our Facebook OG Tags implementation.
254
	 *
255
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
256
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
257
	 *
258
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
259
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
260
	 */
261
	private $open_graph_conflicting_plugins = array(
262
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
263
		// 2 Click Social Media Buttons
264
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
265
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
266
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
267
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
268
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
269
		// Open Graph Meta Tags by Heateor
270
		'facebook/facebook.php',                                 // Facebook (official plugin)
271
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
272
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
273
		// Facebook Featured Image & OG Meta Tags
274
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
275
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
276
		// Facebook Open Graph Meta Tags for WordPress
277
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
278
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
279
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
280
		// Fedmich's Facebook Open Graph Meta
281
		'network-publisher/networkpub.php',                      // Network Publisher
282
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
283
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
284
		// NextScripts SNAP
285
		'og-tags/og-tags.php',                                   // OG Tags
286
		'opengraph/opengraph.php',                               // Open Graph
287
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
288
		// Open Graph Protocol Framework
289
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
290
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
291
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
292
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
293
		'sharepress/sharepress.php',                             // SharePress
294
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
295
		'social-discussions/social-discussions.php',             // Social Discussions
296
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
297
		'socialize/socialize.php',                               // Socialize
298
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
299
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
300
		// Tweet, Like, Google +1 and Share
301
		'wordbooker/wordbooker.php',                             // Wordbooker
302
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
303
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
304
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
305
		// WP Facebook Like Send & Open Graph Meta
306
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
307
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
308
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
309
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
310
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
311
		'seo-by-rank-math/rank-math.php',                        // Rank Math.
312
	);
313
314
	/**
315
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
316
	 */
317
	private $twitter_cards_conflicting_plugins = array(
318
		// 'twitter/twitter.php',                       // The official one handles this on its own.
319
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
320
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
321
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
322
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
323
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
324
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
325
		'twitter-cards/twitter-cards.php',           // Twitter Cards
326
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
327
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
328
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
329
		'seo-by-rank-math/rank-math.php',            // Rank Math.
330
	);
331
332
	/**
333
	 * Message to display in admin_notice
334
	 *
335
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 *
342
	 * @var string
343
	 */
344
	public $error = '';
345
346
	/**
347
	 * Modules that need more privacy description.
348
	 *
349
	 * @var string
350
	 */
351
	public $privacy_checks = '';
352
353
	/**
354
	 * Stats to record once the page loads
355
	 *
356
	 * @var array
357
	 */
358
	public $stats = array();
359
360
	/**
361
	 * Jetpack_Sync object
362
	 */
363
	public $sync;
364
365
	/**
366
	 * Verified data for JSON authorization request
367
	 */
368
	public $json_api_authorization_request = array();
369
370
	/**
371
	 * @var Automattic\Jetpack\Connection\Manager
372
	 */
373
	protected $connection_manager;
374
375
	/**
376
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
377
	 */
378
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
379
380
	/**
381
	 * Constant for login redirect key.
382
	 *
383
	 * @var string
384
	 * @since 8.4.0
385
	 */
386
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
387
388
	/**
389
	 * Holds the singleton instance of this class
390
	 *
391
	 * @since 2.3.3
392
	 * @var Jetpack
393
	 */
394
	static $instance = false;
395
396
	/**
397
	 * Singleton
398
	 *
399
	 * @static
400
	 */
401
	public static function init() {
402
		if ( ! self::$instance ) {
403
			self::$instance = new Jetpack();
404
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
405
		}
406
407
		return self::$instance;
408
	}
409
410
	/**
411
	 * Must never be called statically
412
	 */
413
	function plugin_upgrade() {
414
		if ( self::is_active() ) {
415
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
416
			if ( JETPACK__VERSION != $version ) {
417
				// Prevent multiple upgrades at once - only a single process should trigger
418
				// an upgrade to avoid stampedes
419
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
420
					return;
421
				}
422
423
				// Set a short lock to prevent multiple instances of the upgrade
424
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
425
426
				// check which active modules actually exist and remove others from active_modules list
427
				$unfiltered_modules = self::get_active_modules();
428
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
429
				if ( array_diff( $unfiltered_modules, $modules ) ) {
430
					self::update_active_modules( $modules );
431
				}
432
433
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
434
435
				// Upgrade to 4.3.0
436
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
437
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
438
				}
439
440
				// Make sure Markdown for posts gets turned back on
441
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
442
					update_option( 'wpcom_publish_posts_with_markdown', true );
443
				}
444
445
				/*
446
				 * Minileven deprecation. 8.3.0.
447
				 * Only delete options if not using
448
				 * the replacement standalone Minileven plugin.
449
				 */
450
				if (
451
					! self::is_plugin_active( 'minileven-master/minileven.php' )
452
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
453
				) {
454
					if ( get_option( 'wp_mobile_custom_css' ) ) {
455
						delete_option( 'wp_mobile_custom_css' );
456
					}
457
					if ( get_option( 'wp_mobile_excerpt' ) ) {
458
						delete_option( 'wp_mobile_excerpt' );
459
					}
460
					if ( get_option( 'wp_mobile_featured_images' ) ) {
461
						delete_option( 'wp_mobile_featured_images' );
462
					}
463
					if ( get_option( 'wp_mobile_app_promos' ) ) {
464
						delete_option( 'wp_mobile_app_promos' );
465
					}
466
				}
467
468
				// Upgrade to 8.4.0.
469
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
470
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
471
				}
472
473
				if ( did_action( 'wp_loaded' ) ) {
474
					self::upgrade_on_load();
475
				} else {
476
					add_action(
477
						'wp_loaded',
478
						array( __CLASS__, 'upgrade_on_load' )
479
					);
480
				}
481
			}
482
		}
483
	}
484
485
	/**
486
	 * Runs upgrade routines that need to have modules loaded.
487
	 */
488
	static function upgrade_on_load() {
489
490
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
491
		// This can happen in case Jetpack has been just upgraded and is
492
		// being initialized late during the page load. In this case we wait
493
		// until the next proper admin page load with Jetpack active.
494
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
495
			delete_transient( self::$plugin_upgrade_lock_key );
496
497
			return;
498
		}
499
500
		self::maybe_set_version_option();
501
502
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
503
			Jetpack_Widget_Conditions::migrate_post_type_rules();
504
		}
505
506
		if (
507
			class_exists( 'Jetpack_Sitemap_Manager' )
508
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
509
		) {
510
			do_action( 'jetpack_sitemaps_purge_data' );
511
		}
512
513
		// Delete old stats cache
514
		delete_option( 'jetpack_restapi_stats_cache' );
515
516
		delete_transient( self::$plugin_upgrade_lock_key );
517
	}
518
519
	/**
520
	 * Saves all the currently active modules to options.
521
	 * Also fires Action hooks for each newly activated and deactivated module.
522
	 *
523
	 * @param $modules Array Array of active modules to be saved in options.
524
	 *
525
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
526
	 */
527
	static function update_active_modules( $modules ) {
528
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
529
		$active_modules       = self::get_active_modules();
530
		$new_active_modules   = array_diff( $modules, $current_modules );
531
		$new_inactive_modules = array_diff( $active_modules, $modules );
532
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
533
		$reindexed_modules    = array_values( $new_current_modules );
534
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
535
536
		foreach ( $new_active_modules as $module ) {
537
			/**
538
			 * Fires when a specific module is activated.
539
			 *
540
			 * @since 1.9.0
541
			 *
542
			 * @param string $module Module slug.
543
			 * @param boolean $success whether the module was activated. @since 4.2
544
			 */
545
			do_action( 'jetpack_activate_module', $module, $success );
546
			/**
547
			 * Fires when a module is activated.
548
			 * The dynamic part of the filter, $module, is the module slug.
549
			 *
550
			 * @since 1.9.0
551
			 *
552
			 * @param string $module Module slug.
553
			 */
554
			do_action( "jetpack_activate_module_$module", $module );
555
		}
556
557
		foreach ( $new_inactive_modules as $module ) {
558
			/**
559
			 * Fired after a module has been deactivated.
560
			 *
561
			 * @since 4.2.0
562
			 *
563
			 * @param string $module Module slug.
564
			 * @param boolean $success whether the module was deactivated.
565
			 */
566
			do_action( 'jetpack_deactivate_module', $module, $success );
567
			/**
568
			 * Fires when a module is deactivated.
569
			 * The dynamic part of the filter, $module, is the module slug.
570
			 *
571
			 * @since 1.9.0
572
			 *
573
			 * @param string $module Module slug.
574
			 */
575
			do_action( "jetpack_deactivate_module_$module", $module );
576
		}
577
578
		return $success;
579
	}
580
581
	static function delete_active_modules() {
582
		self::update_active_modules( array() );
583
	}
584
585
	/**
586
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
587
	 * available.
588
	 */
589
	public function add_configure_hook() {
590
		global $wp_filter;
591
592
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
593
		if ( false !== $current_priority ) {
594
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
595
		}
596
597
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
598
		sort( $taken_priorities );
599
600
		$first_priority = array_shift( $taken_priorities );
601
602
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
603
			$new_priority = - PHP_INT_MAX;
604
		} else {
605
			$new_priority = $first_priority - 1;
606
		}
607
608
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
609
	}
610
611
	/**
612
	 * Constructor.  Initializes WordPress hooks
613
	 */
614
	private function __construct() {
615
		/*
616
		 * Check for and alert any deprecated hooks
617
		 */
618
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
619
620
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
621
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
622
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
623
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
624
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
625
626
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
627
628
		add_filter(
629
			'jetpack_signature_check_token',
630
			array( __CLASS__, 'verify_onboarding_token' ),
631
			10,
632
			3
633
		);
634
635
		/**
636
		 * Prepare Gutenberg Editor functionality
637
		 */
638
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
639
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
640
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
641
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
642
643
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
644
645
		// Unlink user before deleting the user from WP.com.
646
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
647
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
648
649
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
650
651
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
652
		add_action( 'login_init', array( $this, 'login_init' ) );
653
654
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
655
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
656
657
		add_action( 'admin_init', array( $this, 'admin_init' ) );
658
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
659
660
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
661
662
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
663
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
664
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
665
666
		// returns HTTPS support status
667
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
668
669
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
670
671
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
672
673
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
674
675
		/**
676
		 * These actions run checks to load additional files.
677
		 * They check for external files or plugins, so they need to run as late as possible.
678
		 */
679
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
680
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
681
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
682
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
683
684
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
685
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
686
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
687
688
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
689
690
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
691
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
692
693
		// A filter to control all just in time messages
694
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
695
696
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
697
698
		/*
699
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
700
		 * We should make sure to only do this for front end links.
701
		 */
702
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
703
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
704
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
705
706
			/*
707
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
708
			 * so they point moderation links on emails to Calypso.
709
			 */
710
			jetpack_require_lib( 'functions.wp-notify' );
711
		}
712
713
		add_action(
714
			'plugins_loaded',
715
			function() {
716
				if ( User_Agent_Info::is_mobile_app() ) {
717
					add_filter( 'get_edit_post_link', '__return_empty_string' );
718
				}
719
			}
720
		);
721
722
		// Update the Jetpack plan from API on heartbeats.
723
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
724
725
		/**
726
		 * This is the hack to concatenate all css files into one.
727
		 * For description and reasoning see the implode_frontend_css method.
728
		 *
729
		 * Super late priority so we catch all the registered styles.
730
		 */
731
		if ( ! is_admin() ) {
732
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
733
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
734
		}
735
736
		/**
737
		 * These are sync actions that we need to keep track of for jitms
738
		 */
739
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
740
741
		// Actually push the stats on shutdown.
742
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
743
			add_action( 'shutdown', array( $this, 'push_stats' ) );
744
		}
745
746
		// Actions for Manager::authorize().
747
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
748
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
749
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
750
751
		// Filters for the Manager::get_token() urls and request body.
752
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
753
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
754
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
755
	}
756
757
	/**
758
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
759
	 * Config object.
760
	 */
761
	public function configure() {
762
		$config = new Config();
763
764
		foreach (
765
			array(
766
				'sync',
767
				'tracking',
768
				'tos',
769
			)
770
			as $feature
771
		) {
772
			$config->ensure( $feature );
773
		}
774
775
		$config->ensure(
776
			'connection',
777
			array(
778
				'slug' => 'jetpack',
779
				'name' => 'Jetpack',
780
			)
781
		);
782
783
		if ( is_admin() ) {
784
			$config->ensure( 'jitm' );
785
		}
786
787
		if ( ! $this->connection_manager ) {
788
			$this->connection_manager = new Connection_Manager( 'jetpack' );
789
		}
790
791
		/*
792
		 * Load things that should only be in Network Admin.
793
		 *
794
		 * For now blow away everything else until a more full
795
		 * understanding of what is needed at the network level is
796
		 * available
797
		 */
798
		if ( is_multisite() ) {
799
			$network = Jetpack_Network::init();
800
			$network->set_connection( $this->connection_manager );
801
		}
802
803
		if ( $this->connection_manager->is_active() ) {
804
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
805
806
			Jetpack_Heartbeat::init();
807
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
808
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
809
				Jetpack_Search_Performance_Logger::init();
810
			}
811
		}
812
813
		// Initialize remote file upload request handlers.
814
		$this->add_remote_request_handlers();
815
816
		/*
817
		 * Enable enhanced handling of previewing sites in Calypso
818
		 */
819
		if ( self::is_active() ) {
820
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
821
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
822
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
823
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
824
		}
825
	}
826
827
	/**
828
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
829
	 * initialization code.
830
	 *
831
	 * @action plugins_loaded
832
	 */
833
	public function late_initialization() {
834
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
835
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
836
837
		Partner::init();
838
839
		/**
840
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
841
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
842
		 *
843
		 * @since 8.1.0
844
		 *
845
		 * @param Jetpack $jetpack the main plugin class object.
846
		 */
847
		do_action( 'jetpack_loaded', $this );
848
849
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
850
	}
851
852
	/**
853
	 * Sets up the XMLRPC request handlers.
854
	 *
855
	 * @deprecated since 7.7.0
856
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
857
	 *
858
	 * @param array                 $request_params Incoming request parameters.
859
	 * @param Boolean               $is_active      Whether the connection is currently active.
860
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
861
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
862
	 */
863 View Code Duplication
	public function setup_xmlrpc_handlers(
864
		$request_params,
865
		$is_active,
866
		$is_signed,
867
		Jetpack_XMLRPC_Server $xmlrpc_server = null
868
	) {
869
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
870
871
		if ( ! $this->connection_manager ) {
872
			$this->connection_manager = new Connection_Manager();
873
		}
874
875
		return $this->connection_manager->setup_xmlrpc_handlers(
876
			$request_params,
877
			$is_active,
878
			$is_signed,
879
			$xmlrpc_server
880
		);
881
	}
882
883
	/**
884
	 * Initialize REST API registration connector.
885
	 *
886
	 * @deprecated since 7.7.0
887
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
888
	 */
889 View Code Duplication
	public function initialize_rest_api_registration_connector() {
890
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
891
892
		if ( ! $this->connection_manager ) {
893
			$this->connection_manager = new Connection_Manager();
894
		}
895
896
		$this->connection_manager->initialize_rest_api_registration_connector();
897
	}
898
899
	/**
900
	 * This is ported over from the manage module, which has been deprecated and baked in here.
901
	 *
902
	 * @param $domains
903
	 */
904
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
905
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
906
	}
907
908
	/**
909
	 * Return $domains, with 'wordpress.com' appended.
910
	 * This is ported over from the manage module, which has been deprecated and baked in here.
911
	 *
912
	 * @param $domains
913
	 * @return array
914
	 */
915
	function allow_wpcom_domain( $domains ) {
916
		if ( empty( $domains ) ) {
917
			$domains = array();
918
		}
919
		$domains[] = 'wordpress.com';
920
		return array_unique( $domains );
921
	}
922
923
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
924
		$post = get_post( $post_id );
925
926
		if ( empty( $post ) ) {
927
			return $default_url;
928
		}
929
930
		$post_type = $post->post_type;
931
932
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
933
		// https://en.support.wordpress.com/custom-post-types/
934
		$allowed_post_types = array(
935
			'post',
936
			'page',
937
			'jetpack-portfolio',
938
			'jetpack-testimonial',
939
		);
940
941
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
942
			return $default_url;
943
		}
944
945
		return esc_url(
946
			Redirect::get_url(
947
				'calypso-edit-' . $post_type,
948
				array(
949
					'path' => $post_id,
950
				)
951
			)
952
		);
953
	}
954
955
	function point_edit_comment_links_to_calypso( $url ) {
956
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
957
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
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...
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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

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

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

Loading history...
958
959
		return esc_url(
960
			Redirect::get_url(
961
				'calypso-edit-comment',
962
				array(
963
					'path' => $query_args['amp;c'],
964
				)
965
			)
966
		);
967
968
	}
969
970
	function jetpack_track_last_sync_callback( $params ) {
971
		/**
972
		 * Filter to turn off jitm caching
973
		 *
974
		 * @since 5.4.0
975
		 *
976
		 * @param bool false Whether to cache just in time messages
977
		 */
978
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
979
			return $params;
980
		}
981
982
		if ( is_array( $params ) && isset( $params[0] ) ) {
983
			$option = $params[0];
984
			if ( 'active_plugins' === $option ) {
985
				// use the cache if we can, but not terribly important if it gets evicted
986
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
987
			}
988
		}
989
990
		return $params;
991
	}
992
993
	function jetpack_connection_banner_callback() {
994
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
995
996
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
997
		if (
998
			isset( $_REQUEST['dismissBanner'] ) &&
999
			! Jetpack_Connection_Banner::force_display()
1000
		) {
1001
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1002
			wp_send_json_success();
1003
		}
1004
1005
		wp_die();
1006
	}
1007
1008
	/**
1009
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1010
	 * Only used in our alternate XML-RPC endpoint, where we want to
1011
	 * ensure that Core and other plugins' methods are not exposed.
1012
	 *
1013
	 * @deprecated since 7.7.0
1014
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1015
	 *
1016
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1017
	 * @return array Filtered $methods
1018
	 */
1019 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1020
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1021
1022
		if ( ! $this->connection_manager ) {
1023
			$this->connection_manager = new Connection_Manager();
1024
		}
1025
1026
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1027
	}
1028
1029
	/**
1030
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1031
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1032
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1033
	 * which is accessible via a different URI. Most of the below is copied directly
1034
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1035
	 *
1036
	 * @deprecated since 7.7.0
1037
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1038
	 */
1039 View Code Duplication
	public function alternate_xmlrpc() {
1040
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1041
1042
		if ( ! $this->connection_manager ) {
1043
			$this->connection_manager = new Connection_Manager();
1044
		}
1045
1046
		$this->connection_manager->alternate_xmlrpc();
1047
	}
1048
1049
	/**
1050
	 * The callback for the JITM ajax requests.
1051
	 *
1052
	 * @deprecated since 7.9.0
1053
	 */
1054
	function jetpack_jitm_ajax_callback() {
1055
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1056
	}
1057
1058
	/**
1059
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1060
	 */
1061
	function push_stats() {
1062
		if ( ! empty( $this->stats ) ) {
1063
			$this->do_stats( 'server_side' );
1064
		}
1065
	}
1066
1067
	/**
1068
	 * Sets the Jetpack custom capabilities.
1069
	 *
1070
	 * @param string[] $caps    Array of the user's capabilities.
1071
	 * @param string   $cap     Capability name.
1072
	 * @param int      $user_id The user ID.
1073
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1074
	 */
1075
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1076
		$is_development_mode = ( new Status() )->is_development_mode();
1077
		switch ( $cap ) {
1078
			case 'jetpack_connect':
1079
			case 'jetpack_reconnect':
1080
				if ( $is_development_mode ) {
1081
					$caps = array( 'do_not_allow' );
1082
					break;
1083
				}
1084
				// Pass through. If it's not development mode, these should match disconnect.
1085
				// Let users disconnect if it's development mode, just in case things glitch.
1086
			case 'jetpack_disconnect':
1087
				/**
1088
				 * Filters the jetpack_disconnect capability.
1089
				 *
1090
				 * @since 8.7.0
1091
				 *
1092
				 * @param array An array containing the capability name.
1093
				 */
1094
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1095
				break;
1096
			case 'jetpack_manage_modules':
1097
			case 'jetpack_activate_modules':
1098
			case 'jetpack_deactivate_modules':
1099
				$caps = array( 'manage_options' );
1100
				break;
1101
			case 'jetpack_configure_modules':
1102
				$caps = array( 'manage_options' );
1103
				break;
1104
			case 'jetpack_manage_autoupdates':
1105
				$caps = array(
1106
					'manage_options',
1107
					'update_plugins',
1108
				);
1109
				break;
1110
			case 'jetpack_network_admin_page':
1111
			case 'jetpack_network_settings_page':
1112
				$caps = array( 'manage_network_plugins' );
1113
				break;
1114
			case 'jetpack_network_sites_page':
1115
				$caps = array( 'manage_sites' );
1116
				break;
1117
			case 'jetpack_admin_page':
1118
				if ( $is_development_mode ) {
1119
					$caps = array( 'manage_options' );
1120
					break;
1121
				} else {
1122
					$caps = array( 'read' );
1123
				}
1124
				break;
1125
			case 'jetpack_connect_user':
1126
				if ( $is_development_mode ) {
1127
					$caps = array( 'do_not_allow' );
1128
					break;
1129
				}
1130
				$caps = array( 'read' );
1131
				break;
1132
		}
1133
		return $caps;
1134
	}
1135
1136
	/**
1137
	 * Require a Jetpack authentication.
1138
	 *
1139
	 * @deprecated since 7.7.0
1140
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1141
	 */
1142 View Code Duplication
	public function require_jetpack_authentication() {
1143
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1144
1145
		if ( ! $this->connection_manager ) {
1146
			$this->connection_manager = new Connection_Manager();
1147
		}
1148
1149
		$this->connection_manager->require_jetpack_authentication();
1150
	}
1151
1152
	/**
1153
	 * Load language files
1154
	 *
1155
	 * @action plugins_loaded
1156
	 */
1157
	public static function plugin_textdomain() {
1158
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1159
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1160
	}
1161
1162
	/**
1163
	 * Register assets for use in various modules and the Jetpack admin page.
1164
	 *
1165
	 * @uses wp_script_is, wp_register_script, plugins_url
1166
	 * @action wp_loaded
1167
	 * @return null
1168
	 */
1169
	public function register_assets() {
1170 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1171
			wp_register_script(
1172
				'jetpack-gallery-settings',
1173
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1174
				array( 'media-views' ),
1175
				'20121225'
1176
			);
1177
		}
1178
1179
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1180
			wp_register_script(
1181
				'jetpack-twitter-timeline',
1182
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1183
				array( 'jquery' ),
1184
				'4.0.0',
1185
				true
1186
			);
1187
		}
1188
1189
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1190
			wp_register_script(
1191
				'jetpack-facebook-embed',
1192
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1193
				array(),
1194
				null,
1195
				true
1196
			);
1197
1198
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1199
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1200
			if ( ! is_numeric( $fb_app_id ) ) {
1201
				$fb_app_id = '';
1202
			}
1203
			wp_localize_script(
1204
				'jetpack-facebook-embed',
1205
				'jpfbembed',
1206
				array(
1207
					'appid'  => $fb_app_id,
1208
					'locale' => $this->get_locale(),
1209
				)
1210
			);
1211
		}
1212
1213
		/**
1214
		 * As jetpack_register_genericons is by default fired off a hook,
1215
		 * the hook may have already fired by this point.
1216
		 * So, let's just trigger it manually.
1217
		 */
1218
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1219
		jetpack_register_genericons();
1220
1221
		/**
1222
		 * Register the social logos
1223
		 */
1224
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1225
		jetpack_register_social_logos();
1226
1227 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1228
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1229
		}
1230
	}
1231
1232
	/**
1233
	 * Guess locale from language code.
1234
	 *
1235
	 * @param string $lang Language code.
1236
	 * @return string|bool
1237
	 */
1238 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1239
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1240
			return 'en_US';
1241
		}
1242
1243
		if ( ! class_exists( 'GP_Locales' ) ) {
1244
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1245
				return false;
1246
			}
1247
1248
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1249
		}
1250
1251
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1252
			// WP.com: get_locale() returns 'it'
1253
			$locale = GP_Locales::by_slug( $lang );
1254
		} else {
1255
			// Jetpack: get_locale() returns 'it_IT';
1256
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1257
		}
1258
1259
		if ( ! $locale ) {
1260
			return false;
1261
		}
1262
1263
		if ( empty( $locale->facebook_locale ) ) {
1264
			if ( empty( $locale->wp_locale ) ) {
1265
				return false;
1266
			} else {
1267
				// Facebook SDK is smart enough to fall back to en_US if a
1268
				// locale isn't supported. Since supported Facebook locales
1269
				// can fall out of sync, we'll attempt to use the known
1270
				// wp_locale value and rely on said fallback.
1271
				return $locale->wp_locale;
1272
			}
1273
		}
1274
1275
		return $locale->facebook_locale;
1276
	}
1277
1278
	/**
1279
	 * Get the locale.
1280
	 *
1281
	 * @return string|bool
1282
	 */
1283
	function get_locale() {
1284
		$locale = $this->guess_locale_from_lang( get_locale() );
1285
1286
		if ( ! $locale ) {
1287
			$locale = 'en_US';
1288
		}
1289
1290
		return $locale;
1291
	}
1292
1293
	/**
1294
	 * Return the network_site_url so that .com knows what network this site is a part of.
1295
	 *
1296
	 * @param  bool $option
1297
	 * @return string
1298
	 */
1299
	public function jetpack_main_network_site_option( $option ) {
1300
		return network_site_url();
1301
	}
1302
	/**
1303
	 * Network Name.
1304
	 */
1305
	static function network_name( $option = null ) {
1306
		global $current_site;
1307
		return $current_site->site_name;
1308
	}
1309
	/**
1310
	 * Does the network allow new user and site registrations.
1311
	 *
1312
	 * @return string
1313
	 */
1314
	static function network_allow_new_registrations( $option = null ) {
1315
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1316
	}
1317
	/**
1318
	 * Does the network allow admins to add new users.
1319
	 *
1320
	 * @return boolian
1321
	 */
1322
	static function network_add_new_users( $option = null ) {
1323
		return (bool) get_site_option( 'add_new_users' );
1324
	}
1325
	/**
1326
	 * File upload psace left per site in MB.
1327
	 *  -1 means NO LIMIT.
1328
	 *
1329
	 * @return number
1330
	 */
1331
	static function network_site_upload_space( $option = null ) {
1332
		// value in MB
1333
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1334
	}
1335
1336
	/**
1337
	 * Network allowed file types.
1338
	 *
1339
	 * @return string
1340
	 */
1341
	static function network_upload_file_types( $option = null ) {
1342
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1343
	}
1344
1345
	/**
1346
	 * Maximum file upload size set by the network.
1347
	 *
1348
	 * @return number
1349
	 */
1350
	static function network_max_upload_file_size( $option = null ) {
1351
		// value in KB
1352
		return get_site_option( 'fileupload_maxk', 300 );
1353
	}
1354
1355
	/**
1356
	 * Lets us know if a site allows admins to manage the network.
1357
	 *
1358
	 * @return array
1359
	 */
1360
	static function network_enable_administration_menus( $option = null ) {
1361
		return get_site_option( 'menu_items' );
1362
	}
1363
1364
	/**
1365
	 * If a user has been promoted to or demoted from admin, we need to clear the
1366
	 * jetpack_other_linked_admins transient.
1367
	 *
1368
	 * @since 4.3.2
1369
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1370
	 *
1371
	 * @param int    $user_id   The user ID whose role changed.
1372
	 * @param string $role      The new role.
1373
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
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...
1374
	 */
1375
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1376
		if ( 'administrator' == $role
1377
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1378
			|| is_null( $old_roles )
1379
		) {
1380
			delete_transient( 'jetpack_other_linked_admins' );
1381
		}
1382
	}
1383
1384
	/**
1385
	 * Checks to see if there are any other users available to become primary
1386
	 * Users must both:
1387
	 * - Be linked to wpcom
1388
	 * - Be an admin
1389
	 *
1390
	 * @return mixed False if no other users are linked, Int if there are.
1391
	 */
1392
	static function get_other_linked_admins() {
1393
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1394
1395
		if ( false === $other_linked_users ) {
1396
			$admins = get_users( array( 'role' => 'administrator' ) );
1397
			if ( count( $admins ) > 1 ) {
1398
				$available = array();
1399
				foreach ( $admins as $admin ) {
1400
					if ( self::is_user_connected( $admin->ID ) ) {
1401
						$available[] = $admin->ID;
1402
					}
1403
				}
1404
1405
				$count_connected_admins = count( $available );
1406
				if ( count( $available ) > 1 ) {
1407
					$other_linked_users = $count_connected_admins;
1408
				} else {
1409
					$other_linked_users = 0;
1410
				}
1411
			} else {
1412
				$other_linked_users = 0;
1413
			}
1414
1415
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1416
		}
1417
1418
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1419
	}
1420
1421
	/**
1422
	 * Return whether we are dealing with a multi network setup or not.
1423
	 * The reason we are type casting this is because we want to avoid the situation where
1424
	 * the result is false since when is_main_network_option return false it cases
1425
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1426
	 * database which could be set to anything as opposed to what this function returns.
1427
	 *
1428
	 * @param  bool $option
1429
	 *
1430
	 * @return boolean
1431
	 */
1432
	public function is_main_network_option( $option ) {
1433
		// return '1' or ''
1434
		return (string) (bool) self::is_multi_network();
1435
	}
1436
1437
	/**
1438
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1439
	 *
1440
	 * @param  string $option
1441
	 * @return boolean
1442
	 */
1443
	public function is_multisite( $option ) {
1444
		return (string) (bool) is_multisite();
1445
	}
1446
1447
	/**
1448
	 * Implemented since there is no core is multi network function
1449
	 * Right now there is no way to tell if we which network is the dominant network on the system
1450
	 *
1451
	 * @since  3.3
1452
	 * @return boolean
1453
	 */
1454 View Code Duplication
	public static function is_multi_network() {
1455
		global  $wpdb;
1456
1457
		// if we don't have a multi site setup no need to do any more
1458
		if ( ! is_multisite() ) {
1459
			return false;
1460
		}
1461
1462
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1463
		if ( $num_sites > 1 ) {
1464
			return true;
1465
		} else {
1466
			return false;
1467
		}
1468
	}
1469
1470
	/**
1471
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1472
	 *
1473
	 * @return null
1474
	 */
1475
	function update_jetpack_main_network_site_option() {
1476
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1477
	}
1478
	/**
1479
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1480
	 */
1481
	function update_jetpack_network_settings() {
1482
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1483
		// Only sync this info for the main network site.
1484
	}
1485
1486
	/**
1487
	 * Get back if the current site is single user site.
1488
	 *
1489
	 * @return bool
1490
	 */
1491 View Code Duplication
	public static function is_single_user_site() {
1492
		global $wpdb;
1493
1494
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1495
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1496
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1497
		}
1498
		return 1 === (int) $some_users;
1499
	}
1500
1501
	/**
1502
	 * Returns true if the site has file write access false otherwise.
1503
	 *
1504
	 * @return string ( '1' | '0' )
1505
	 **/
1506
	public static function file_system_write_access() {
1507
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1508
			require_once ABSPATH . 'wp-admin/includes/file.php';
1509
		}
1510
1511
		require_once ABSPATH . 'wp-admin/includes/template.php';
1512
1513
		$filesystem_method = get_filesystem_method();
1514
		if ( $filesystem_method === 'direct' ) {
1515
			return 1;
1516
		}
1517
1518
		ob_start();
1519
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1520
		ob_end_clean();
1521
		if ( $filesystem_credentials_are_stored ) {
1522
			return 1;
1523
		}
1524
		return 0;
1525
	}
1526
1527
	/**
1528
	 * Finds out if a site is using a version control system.
1529
	 *
1530
	 * @return string ( '1' | '0' )
1531
	 **/
1532
	public static function is_version_controlled() {
1533
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1534
		return (string) (int) Functions::is_version_controlled();
1535
	}
1536
1537
	/**
1538
	 * Determines whether the current theme supports featured images or not.
1539
	 *
1540
	 * @return string ( '1' | '0' )
1541
	 */
1542
	public static function featured_images_enabled() {
1543
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1544
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1545
	}
1546
1547
	/**
1548
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1549
	 *
1550
	 * @deprecated 4.7 use get_avatar_url instead.
1551
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1552
	 * @param int               $size Size of the avatar image
1553
	 * @param string            $default URL to a default image to use if no avatar is available
1554
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1555
	 *
1556
	 * @return array
1557
	 */
1558
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1559
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1560
		return get_avatar_url(
1561
			$id_or_email,
1562
			array(
1563
				'size'          => $size,
1564
				'default'       => $default,
1565
				'force_default' => $force_display,
1566
			)
1567
		);
1568
	}
1569
1570
	/**
1571
	 * jetpack_updates is saved in the following schema:
1572
	 *
1573
	 * array (
1574
	 *      'plugins'                       => (int) Number of plugin updates available.
1575
	 *      'themes'                        => (int) Number of theme updates available.
1576
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1577
	 *      'translations'                  => (int) Number of translation updates available.
1578
	 *      'total'                         => (int) Total of all available updates.
1579
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1580
	 * )
1581
	 *
1582
	 * @return array
1583
	 */
1584
	public static function get_updates() {
1585
		$update_data = wp_get_update_data();
1586
1587
		// Stores the individual update counts as well as the total count.
1588
		if ( isset( $update_data['counts'] ) ) {
1589
			$updates = $update_data['counts'];
1590
		}
1591
1592
		// If we need to update WordPress core, let's find the latest version number.
1593 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1594
			$cur = get_preferred_from_update_core();
1595
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1596
				$updates['wp_update_version'] = $cur->current;
1597
			}
1598
		}
1599
		return isset( $updates ) ? $updates : array();
1600
	}
1601
1602
	public static function get_update_details() {
1603
		$update_details = array(
1604
			'update_core'    => get_site_transient( 'update_core' ),
1605
			'update_plugins' => get_site_transient( 'update_plugins' ),
1606
			'update_themes'  => get_site_transient( 'update_themes' ),
1607
		);
1608
		return $update_details;
1609
	}
1610
1611
	public static function refresh_update_data() {
1612
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1613
1614
	}
1615
1616
	public static function refresh_theme_data() {
1617
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1618
	}
1619
1620
	/**
1621
	 * Is Jetpack active?
1622
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1623
	 *
1624
	 * @return bool
1625
	 */
1626
	public static function is_active() {
1627
		return self::connection()->is_active();
1628
	}
1629
1630
	/**
1631
	 * Make an API call to WordPress.com for plan status
1632
	 *
1633
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1634
	 *
1635
	 * @return bool True if plan is updated, false if no update
1636
	 */
1637
	public static function refresh_active_plan_from_wpcom() {
1638
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1639
		return Jetpack_Plan::refresh_from_wpcom();
1640
	}
1641
1642
	/**
1643
	 * Get the plan that this Jetpack site is currently using
1644
	 *
1645
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1646
	 * @return array Active Jetpack plan details.
1647
	 */
1648
	public static function get_active_plan() {
1649
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1650
		return Jetpack_Plan::get();
1651
	}
1652
1653
	/**
1654
	 * Determine whether the active plan supports a particular feature
1655
	 *
1656
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1657
	 * @return bool True if plan supports feature, false if not.
1658
	 */
1659
	public static function active_plan_supports( $feature ) {
1660
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1661
		return Jetpack_Plan::supports( $feature );
1662
	}
1663
1664
	/**
1665
	 * Deprecated: Is Jetpack in development (offline) mode?
1666
	 *
1667
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1668
	 * and themes still use it, and we do not want to flood them with notices.
1669
	 *
1670
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1671
	 *
1672
	 * @deprecated since 8.0.
1673
	 */
1674
	public static function is_development_mode() {
1675
		return ( new Status() )->is_development_mode();
1676
	}
1677
1678
	/**
1679
	 * Whether the site is currently onboarding or not.
1680
	 * A site is considered as being onboarded if it currently has an onboarding token.
1681
	 *
1682
	 * @since 5.8
1683
	 *
1684
	 * @access public
1685
	 * @static
1686
	 *
1687
	 * @return bool True if the site is currently onboarding, false otherwise
1688
	 */
1689
	public static function is_onboarding() {
1690
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1691
	}
1692
1693
	/**
1694
	 * Determines reason for Jetpack development mode.
1695
	 */
1696
	public static function development_mode_trigger_text() {
1697
		if ( ! ( new Status() )->is_development_mode() ) {
1698
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1699
		}
1700
1701
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1702
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1703
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1704
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1705
		} else {
1706
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1707
		}
1708
1709
		return $notice;
1710
1711
	}
1712
	/**
1713
	 * Get Jetpack development mode notice text and notice class.
1714
	 *
1715
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1716
	 */
1717
	public static function show_development_mode_notice() {
1718 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1719
			$notice = sprintf(
1720
				/* translators: %s is a URL */
1721
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1722
				Redirect::get_url( 'jetpack-support-development-mode' )
1723
			);
1724
1725
			$notice .= ' ' . self::development_mode_trigger_text();
1726
1727
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1728
		}
1729
1730
		// Throw up a notice if using a development version and as for feedback.
1731
		if ( self::is_development_version() ) {
1732
			/* translators: %s is a URL */
1733
			$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' ) );
1734
1735
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1736
		}
1737
		// Throw up a notice if using staging mode
1738 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1739
			/* translators: %s is a URL */
1740
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1741
1742
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1743
		}
1744
	}
1745
1746
	/**
1747
	 * Whether Jetpack's version maps to a public release, or a development version.
1748
	 */
1749
	public static function is_development_version() {
1750
		/**
1751
		 * Allows filtering whether this is a development version of Jetpack.
1752
		 *
1753
		 * This filter is especially useful for tests.
1754
		 *
1755
		 * @since 4.3.0
1756
		 *
1757
		 * @param bool $development_version Is this a develoment version of Jetpack?
1758
		 */
1759
		return (bool) apply_filters(
1760
			'jetpack_development_version',
1761
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1762
		);
1763
	}
1764
1765
	/**
1766
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1767
	 */
1768
	public static function is_user_connected( $user_id = false ) {
1769
		return self::connection()->is_user_connected( $user_id );
1770
	}
1771
1772
	/**
1773
	 * Get the wpcom user data of the current|specified connected user.
1774
	 */
1775 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1776
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1777
		if ( ! $user_id ) {
1778
			$user_id = get_current_user_id();
1779
		}
1780
1781
		$transient_key = "jetpack_connected_user_data_$user_id";
1782
1783
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1784
			return $cached_user_data;
1785
		}
1786
1787
		$xml = new Jetpack_IXR_Client(
1788
			array(
1789
				'user_id' => $user_id,
1790
			)
1791
		);
1792
		$xml->query( 'wpcom.getUser' );
1793
		if ( ! $xml->isError() ) {
1794
			$user_data = $xml->getResponse();
1795
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1796
			return $user_data;
1797
		}
1798
1799
		return false;
1800
	}
1801
1802
	/**
1803
	 * Get the wpcom email of the current|specified connected user.
1804
	 */
1805
	public static function get_connected_user_email( $user_id = null ) {
1806
		if ( ! $user_id ) {
1807
			$user_id = get_current_user_id();
1808
		}
1809
1810
		$xml = new Jetpack_IXR_Client(
1811
			array(
1812
				'user_id' => $user_id,
1813
			)
1814
		);
1815
		$xml->query( 'wpcom.getUserEmail' );
1816
		if ( ! $xml->isError() ) {
1817
			return $xml->getResponse();
1818
		}
1819
		return false;
1820
	}
1821
1822
	/**
1823
	 * Get the wpcom email of the master user.
1824
	 */
1825
	public static function get_master_user_email() {
1826
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1827
		if ( $master_user_id ) {
1828
			return self::get_connected_user_email( $master_user_id );
1829
		}
1830
		return '';
1831
	}
1832
1833
	/**
1834
	 * Whether the current user is the connection owner.
1835
	 *
1836
	 * @deprecated since 7.7
1837
	 *
1838
	 * @return bool Whether the current user is the connection owner.
1839
	 */
1840
	public function current_user_is_connection_owner() {
1841
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1842
		return self::connection()->is_connection_owner();
1843
	}
1844
1845
	/**
1846
	 * Gets current user IP address.
1847
	 *
1848
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1849
	 *
1850
	 * @return string                  Current user IP address.
1851
	 */
1852
	public static function current_user_ip( $check_all_headers = false ) {
1853
		if ( $check_all_headers ) {
1854
			foreach ( array(
1855
				'HTTP_CF_CONNECTING_IP',
1856
				'HTTP_CLIENT_IP',
1857
				'HTTP_X_FORWARDED_FOR',
1858
				'HTTP_X_FORWARDED',
1859
				'HTTP_X_CLUSTER_CLIENT_IP',
1860
				'HTTP_FORWARDED_FOR',
1861
				'HTTP_FORWARDED',
1862
				'HTTP_VIA',
1863
			) as $key ) {
1864
				if ( ! empty( $_SERVER[ $key ] ) ) {
1865
					return $_SERVER[ $key ];
1866
				}
1867
			}
1868
		}
1869
1870
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1871
	}
1872
1873
	/**
1874
	 * Synchronize connected user role changes
1875
	 */
1876
	function user_role_change( $user_id ) {
1877
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1878
		Users::user_role_change( $user_id );
1879
	}
1880
1881
	/**
1882
	 * Loads the currently active modules.
1883
	 */
1884
	public static function load_modules() {
1885
		$is_development_mode = ( new Status() )->is_development_mode();
1886
		if (
1887
			! self::is_active()
1888
			&& ! $is_development_mode
1889
			&& ! self::is_onboarding()
1890
			&& (
1891
				! is_multisite()
1892
				|| ! get_site_option( 'jetpack_protect_active' )
1893
			)
1894
		) {
1895
			return;
1896
		}
1897
1898
		$version = Jetpack_Options::get_option( 'version' );
1899 View Code Duplication
		if ( ! $version ) {
1900
			$version = $old_version = JETPACK__VERSION . ':' . time();
1901
			/** This action is documented in class.jetpack.php */
1902
			do_action( 'updating_jetpack_version', $version, false );
1903
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1904
		}
1905
		list( $version ) = explode( ':', $version );
1906
1907
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1908
1909
		$modules_data = array();
1910
1911
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1912
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1913
			$updated_modules = array();
1914
			foreach ( $modules as $module ) {
1915
				$modules_data[ $module ] = self::get_module( $module );
1916
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1917
					continue;
1918
				}
1919
1920
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1921
					continue;
1922
				}
1923
1924
				$updated_modules[] = $module;
1925
			}
1926
1927
			$modules = array_diff( $modules, $updated_modules );
1928
		}
1929
1930
		foreach ( $modules as $index => $module ) {
1931
			// If we're in dev mode, disable modules requiring a connection
1932
			if ( $is_development_mode ) {
1933
				// Prime the pump if we need to
1934
				if ( empty( $modules_data[ $module ] ) ) {
1935
					$modules_data[ $module ] = self::get_module( $module );
1936
				}
1937
				// If the module requires a connection, but we're in local mode, don't include it.
1938
				if ( $modules_data[ $module ]['requires_connection'] ) {
1939
					continue;
1940
				}
1941
			}
1942
1943
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1944
				continue;
1945
			}
1946
1947
			if ( ! include_once self::get_module_path( $module ) ) {
1948
				unset( $modules[ $index ] );
1949
				self::update_active_modules( array_values( $modules ) );
1950
				continue;
1951
			}
1952
1953
			/**
1954
			 * Fires when a specific module is loaded.
1955
			 * The dynamic part of the hook, $module, is the module slug.
1956
			 *
1957
			 * @since 1.1.0
1958
			 */
1959
			do_action( 'jetpack_module_loaded_' . $module );
1960
		}
1961
1962
		/**
1963
		 * Fires when all the modules are loaded.
1964
		 *
1965
		 * @since 1.1.0
1966
		 */
1967
		do_action( 'jetpack_modules_loaded' );
1968
1969
		// 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.
1970
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1971
	}
1972
1973
	/**
1974
	 * Check if Jetpack's REST API compat file should be included
1975
	 *
1976
	 * @action plugins_loaded
1977
	 * @return null
1978
	 */
1979
	public function check_rest_api_compat() {
1980
		/**
1981
		 * Filters the list of REST API compat files to be included.
1982
		 *
1983
		 * @since 2.2.5
1984
		 *
1985
		 * @param array $args Array of REST API compat files to include.
1986
		 */
1987
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1988
1989
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1990
			require_once $_jetpack_rest_api_compat_include;
1991
		}
1992
	}
1993
1994
	/**
1995
	 * Gets all plugins currently active in values, regardless of whether they're
1996
	 * traditionally activated or network activated.
1997
	 *
1998
	 * @todo Store the result in core's object cache maybe?
1999
	 */
2000
	public static function get_active_plugins() {
2001
		$active_plugins = (array) get_option( 'active_plugins', array() );
2002
2003
		if ( is_multisite() ) {
2004
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2005
			// whereas active_plugins stores them in the values.
2006
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2007
			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...
2008
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2009
			}
2010
		}
2011
2012
		sort( $active_plugins );
2013
2014
		return array_unique( $active_plugins );
2015
	}
2016
2017
	/**
2018
	 * Gets and parses additional plugin data to send with the heartbeat data
2019
	 *
2020
	 * @since 3.8.1
2021
	 *
2022
	 * @return array Array of plugin data
2023
	 */
2024
	public static function get_parsed_plugin_data() {
2025
		if ( ! function_exists( 'get_plugins' ) ) {
2026
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2027
		}
2028
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2029
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2030
		$active_plugins = self::get_active_plugins();
2031
2032
		$plugins = array();
2033
		foreach ( $all_plugins as $path => $plugin_data ) {
2034
			$plugins[ $path ] = array(
2035
				'is_active' => in_array( $path, $active_plugins ),
2036
				'file'      => $path,
2037
				'name'      => $plugin_data['Name'],
2038
				'version'   => $plugin_data['Version'],
2039
				'author'    => $plugin_data['Author'],
2040
			);
2041
		}
2042
2043
		return $plugins;
2044
	}
2045
2046
	/**
2047
	 * Gets and parses theme data to send with the heartbeat data
2048
	 *
2049
	 * @since 3.8.1
2050
	 *
2051
	 * @return array Array of theme data
2052
	 */
2053
	public static function get_parsed_theme_data() {
2054
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2055
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2056
2057
		$themes = array();
2058
		foreach ( $all_themes as $slug => $theme_data ) {
2059
			$theme_headers = array();
2060
			foreach ( $header_keys as $header_key ) {
2061
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2062
			}
2063
2064
			$themes[ $slug ] = array(
2065
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2066
				'slug'            => $slug,
2067
				'theme_root'      => $theme_data->get_theme_root_uri(),
2068
				'parent'          => $theme_data->parent(),
2069
				'headers'         => $theme_headers,
2070
			);
2071
		}
2072
2073
		return $themes;
2074
	}
2075
2076
	/**
2077
	 * Checks whether a specific plugin is active.
2078
	 *
2079
	 * We don't want to store these in a static variable, in case
2080
	 * there are switch_to_blog() calls involved.
2081
	 */
2082
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2083
		return in_array( $plugin, self::get_active_plugins() );
2084
	}
2085
2086
	/**
2087
	 * Check if Jetpack's Open Graph tags should be used.
2088
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2089
	 *
2090
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2091
	 * @action plugins_loaded
2092
	 * @return null
2093
	 */
2094
	public function check_open_graph() {
2095
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2096
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2097
		}
2098
2099
		$active_plugins = self::get_active_plugins();
2100
2101
		if ( ! empty( $active_plugins ) ) {
2102
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2103
				if ( in_array( $plugin, $active_plugins ) ) {
2104
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2105
					break;
2106
				}
2107
			}
2108
		}
2109
2110
		/**
2111
		 * Allow the addition of Open Graph Meta Tags to all pages.
2112
		 *
2113
		 * @since 2.0.3
2114
		 *
2115
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2116
		 */
2117
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2118
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2119
		}
2120
	}
2121
2122
	/**
2123
	 * Check if Jetpack's Twitter tags should be used.
2124
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2125
	 *
2126
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2127
	 * @action plugins_loaded
2128
	 * @return null
2129
	 */
2130
	public function check_twitter_tags() {
2131
2132
		$active_plugins = self::get_active_plugins();
2133
2134
		if ( ! empty( $active_plugins ) ) {
2135
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2136
				if ( in_array( $plugin, $active_plugins ) ) {
2137
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2138
					break;
2139
				}
2140
			}
2141
		}
2142
2143
		/**
2144
		 * Allow Twitter Card Meta tags to be disabled.
2145
		 *
2146
		 * @since 2.6.0
2147
		 *
2148
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2149
		 */
2150
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2151
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2152
		}
2153
	}
2154
2155
	/**
2156
	 * Allows plugins to submit security reports.
2157
	 *
2158
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2159
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2160
	 * @param array  $args         See definitions above
2161
	 */
2162
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2163
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2164
	}
2165
2166
	/* Jetpack Options API */
2167
2168
	public static function get_option_names( $type = 'compact' ) {
2169
		return Jetpack_Options::get_option_names( $type );
2170
	}
2171
2172
	/**
2173
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2174
	 *
2175
	 * @param string $name    Option name
2176
	 * @param mixed  $default (optional)
2177
	 */
2178
	public static function get_option( $name, $default = false ) {
2179
		return Jetpack_Options::get_option( $name, $default );
2180
	}
2181
2182
	/**
2183
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2184
	 *
2185
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2186
	 * @param string $name  Option name
2187
	 * @param mixed  $value Option value
2188
	 */
2189
	public static function update_option( $name, $value ) {
2190
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2191
		return Jetpack_Options::update_option( $name, $value );
2192
	}
2193
2194
	/**
2195
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2196
	 *
2197
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2198
	 * @param array $array array( option name => option value, ... )
2199
	 */
2200
	public static function update_options( $array ) {
2201
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2202
		return Jetpack_Options::update_options( $array );
2203
	}
2204
2205
	/**
2206
	 * Deletes the given option.  May be passed multiple option names as an array.
2207
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2208
	 *
2209
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2210
	 * @param string|array $names
2211
	 */
2212
	public static function delete_option( $names ) {
2213
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2214
		return Jetpack_Options::delete_option( $names );
2215
	}
2216
2217
	/**
2218
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2219
	 *
2220
	 * Enters a user token into the user_tokens option
2221
	 *
2222
	 * @param int    $user_id The user id.
2223
	 * @param string $token The user token.
2224
	 * @param bool   $is_master_user Whether the user is the master user.
2225
	 * @return bool
2226
	 */
2227
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2228
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2229
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2230
	}
2231
2232
	/**
2233
	 * Returns an array of all PHP files in the specified absolute path.
2234
	 * Equivalent to glob( "$absolute_path/*.php" ).
2235
	 *
2236
	 * @param string $absolute_path The absolute path of the directory to search.
2237
	 * @return array Array of absolute paths to the PHP files.
2238
	 */
2239
	public static function glob_php( $absolute_path ) {
2240
		if ( function_exists( 'glob' ) ) {
2241
			return glob( "$absolute_path/*.php" );
2242
		}
2243
2244
		$absolute_path = untrailingslashit( $absolute_path );
2245
		$files         = array();
2246
		if ( ! $dir = @opendir( $absolute_path ) ) {
2247
			return $files;
2248
		}
2249
2250
		while ( false !== $file = readdir( $dir ) ) {
2251
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2252
				continue;
2253
			}
2254
2255
			$file = "$absolute_path/$file";
2256
2257
			if ( ! is_file( $file ) ) {
2258
				continue;
2259
			}
2260
2261
			$files[] = $file;
2262
		}
2263
2264
		closedir( $dir );
2265
2266
		return $files;
2267
	}
2268
2269
	public static function activate_new_modules( $redirect = false ) {
2270
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2271
			return;
2272
		}
2273
2274
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2275 View Code Duplication
		if ( ! $jetpack_old_version ) {
2276
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2277
			/** This action is documented in class.jetpack.php */
2278
			do_action( 'updating_jetpack_version', $version, false );
2279
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2280
		}
2281
2282
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2283
2284
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2285
			return;
2286
		}
2287
2288
		$active_modules     = self::get_active_modules();
2289
		$reactivate_modules = array();
2290
		foreach ( $active_modules as $active_module ) {
2291
			$module = self::get_module( $active_module );
2292
			if ( ! isset( $module['changed'] ) ) {
2293
				continue;
2294
			}
2295
2296
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2297
				continue;
2298
			}
2299
2300
			$reactivate_modules[] = $active_module;
2301
			self::deactivate_module( $active_module );
2302
		}
2303
2304
		$new_version = JETPACK__VERSION . ':' . time();
2305
		/** This action is documented in class.jetpack.php */
2306
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2307
		Jetpack_Options::update_options(
2308
			array(
2309
				'version'     => $new_version,
2310
				'old_version' => $jetpack_old_version,
2311
			)
2312
		);
2313
2314
		self::state( 'message', 'modules_activated' );
2315
2316
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
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...
2317
2318
		if ( $redirect ) {
2319
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2320
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2321
				$page = $_GET['page'];
2322
			}
2323
2324
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2325
			exit;
2326
		}
2327
	}
2328
2329
	/**
2330
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2331
	 * Make sure to tuck away module "library" files in a sub-directory.
2332
	 */
2333
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2334
		static $modules = null;
2335
2336
		if ( ! isset( $modules ) ) {
2337
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2338
			// Use the cache if we're on the front-end and it's available...
2339
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2340
				$modules = $available_modules_option[ JETPACK__VERSION ];
2341
			} else {
2342
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2343
2344
				$modules = array();
2345
2346
				foreach ( $files as $file ) {
2347
					if ( ! $headers = self::get_module( $file ) ) {
2348
						continue;
2349
					}
2350
2351
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2352
				}
2353
2354
				Jetpack_Options::update_option(
2355
					'available_modules',
2356
					array(
2357
						JETPACK__VERSION => $modules,
2358
					)
2359
				);
2360
			}
2361
		}
2362
2363
		/**
2364
		 * Filters the array of modules available to be activated.
2365
		 *
2366
		 * @since 2.4.0
2367
		 *
2368
		 * @param array $modules Array of available modules.
2369
		 * @param string $min_version Minimum version number required to use modules.
2370
		 * @param string $max_version Maximum version number required to use modules.
2371
		 */
2372
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
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...
2373
2374
		if ( ! $min_version && ! $max_version ) {
2375
			return array_keys( $mods );
2376
		}
2377
2378
		$r = array();
2379
		foreach ( $mods as $slug => $introduced ) {
2380
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2381
				continue;
2382
			}
2383
2384
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2385
				continue;
2386
			}
2387
2388
			$r[] = $slug;
2389
		}
2390
2391
		return $r;
2392
	}
2393
2394
	/**
2395
	 * Default modules loaded on activation.
2396
	 */
2397
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2398
		$return = array();
2399
2400
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2401
			$module_data = self::get_module( $module );
2402
2403
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2404
				case 'yes':
2405
					$return[] = $module;
2406
					break;
2407
				case 'public':
2408
					if ( Jetpack_Options::get_option( 'public' ) ) {
2409
						$return[] = $module;
2410
					}
2411
					break;
2412
				case 'no':
2413
				default:
2414
					break;
2415
			}
2416
		}
2417
		/**
2418
		 * Filters the array of default modules.
2419
		 *
2420
		 * @since 2.5.0
2421
		 *
2422
		 * @param array $return Array of default modules.
2423
		 * @param string $min_version Minimum version number required to use modules.
2424
		 * @param string $max_version Maximum version number required to use modules.
2425
		 */
2426
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
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...
2427
	}
2428
2429
	/**
2430
	 * Checks activated modules during auto-activation to determine
2431
	 * if any of those modules are being deprecated.  If so, close
2432
	 * them out, and add any replacement modules.
2433
	 *
2434
	 * Runs at priority 99 by default.
2435
	 *
2436
	 * This is run late, so that it can still activate a module if
2437
	 * the new module is a replacement for another that the user
2438
	 * currently has active, even if something at the normal priority
2439
	 * would kibosh everything.
2440
	 *
2441
	 * @since 2.6
2442
	 * @uses jetpack_get_default_modules filter
2443
	 * @param array $modules
2444
	 * @return array
2445
	 */
2446
	function handle_deprecated_modules( $modules ) {
2447
		$deprecated_modules = array(
2448
			'debug'            => null,  // Closed out and moved to the debugger library.
2449
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2450
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2451
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2452
		);
2453
2454
		// Don't activate SSO if they never completed activating WPCC.
2455
		if ( self::is_module_active( 'wpcc' ) ) {
2456
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2457
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2458
				$deprecated_modules['wpcc'] = null;
2459
			}
2460
		}
2461
2462
		foreach ( $deprecated_modules as $module => $replacement ) {
2463
			if ( self::is_module_active( $module ) ) {
2464
				self::deactivate_module( $module );
2465
				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...
2466
					$modules[] = $replacement;
2467
				}
2468
			}
2469
		}
2470
2471
		return array_unique( $modules );
2472
	}
2473
2474
	/**
2475
	 * Checks activated plugins during auto-activation to determine
2476
	 * if any of those plugins are in the list with a corresponding module
2477
	 * that is not compatible with the plugin. The module will not be allowed
2478
	 * to auto-activate.
2479
	 *
2480
	 * @since 2.6
2481
	 * @uses jetpack_get_default_modules filter
2482
	 * @param array $modules
2483
	 * @return array
2484
	 */
2485
	function filter_default_modules( $modules ) {
2486
2487
		$active_plugins = self::get_active_plugins();
2488
2489
		if ( ! empty( $active_plugins ) ) {
2490
2491
			// For each module we'd like to auto-activate...
2492
			foreach ( $modules as $key => $module ) {
2493
				// If there are potential conflicts for it...
2494
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2495
					// For each potential conflict...
2496
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2497
						// If that conflicting plugin is active...
2498
						if ( in_array( $plugin, $active_plugins ) ) {
2499
							// Remove that item from being auto-activated.
2500
							unset( $modules[ $key ] );
2501
						}
2502
					}
2503
				}
2504
			}
2505
		}
2506
2507
		return $modules;
2508
	}
2509
2510
	/**
2511
	 * Extract a module's slug from its full path.
2512
	 */
2513
	public static function get_module_slug( $file ) {
2514
		return str_replace( '.php', '', basename( $file ) );
2515
	}
2516
2517
	/**
2518
	 * Generate a module's path from its slug.
2519
	 */
2520
	public static function get_module_path( $slug ) {
2521
		/**
2522
		 * Filters the path of a modules.
2523
		 *
2524
		 * @since 7.4.0
2525
		 *
2526
		 * @param array $return The absolute path to a module's root php file
2527
		 * @param string $slug The module slug
2528
		 */
2529
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
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...
2530
	}
2531
2532
	/**
2533
	 * Load module data from module file. Headers differ from WordPress
2534
	 * plugin headers to avoid them being identified as standalone
2535
	 * plugins on the WordPress plugins page.
2536
	 */
2537
	public static function get_module( $module ) {
2538
		$headers = array(
2539
			'name'                      => 'Module Name',
2540
			'description'               => 'Module Description',
2541
			'sort'                      => 'Sort Order',
2542
			'recommendation_order'      => 'Recommendation Order',
2543
			'introduced'                => 'First Introduced',
2544
			'changed'                   => 'Major Changes In',
2545
			'deactivate'                => 'Deactivate',
2546
			'free'                      => 'Free',
2547
			'requires_connection'       => 'Requires Connection',
2548
			'auto_activate'             => 'Auto Activate',
2549
			'module_tags'               => 'Module Tags',
2550
			'feature'                   => 'Feature',
2551
			'additional_search_queries' => 'Additional Search Queries',
2552
			'plan_classes'              => 'Plans',
2553
		);
2554
2555
		$file = self::get_module_path( self::get_module_slug( $module ) );
2556
2557
		$mod = self::get_file_data( $file, $headers );
2558
		if ( empty( $mod['name'] ) ) {
2559
			return false;
2560
		}
2561
2562
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2563
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2564
		$mod['deactivate']           = empty( $mod['deactivate'] );
2565
		$mod['free']                 = empty( $mod['free'] );
2566
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2567
2568
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2569
			$mod['auto_activate'] = 'No';
2570
		} else {
2571
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2572
		}
2573
2574
		if ( $mod['module_tags'] ) {
2575
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2576
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2577
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2578
		} else {
2579
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2580
		}
2581
2582 View Code Duplication
		if ( $mod['plan_classes'] ) {
2583
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2584
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2585
		} else {
2586
			$mod['plan_classes'] = array( 'free' );
2587
		}
2588
2589 View Code Duplication
		if ( $mod['feature'] ) {
2590
			$mod['feature'] = explode( ',', $mod['feature'] );
2591
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2592
		} else {
2593
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2594
		}
2595
2596
		/**
2597
		 * Filters the feature array on a module.
2598
		 *
2599
		 * This filter allows you to control where each module is filtered: Recommended,
2600
		 * and the default "Other" listing.
2601
		 *
2602
		 * @since 3.5.0
2603
		 *
2604
		 * @param array   $mod['feature'] The areas to feature this module:
2605
		 *     'Recommended' shows on the main Jetpack admin screen.
2606
		 *     'Other' should be the default if no other value is in the array.
2607
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2608
		 * @param array   $mod All the currently assembled module data.
2609
		 */
2610
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
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...
2611
2612
		/**
2613
		 * Filter the returned data about a module.
2614
		 *
2615
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2616
		 * so please be careful.
2617
		 *
2618
		 * @since 3.6.0
2619
		 *
2620
		 * @param array   $mod    The details of the requested module.
2621
		 * @param string  $module The slug of the module, e.g. sharedaddy
2622
		 * @param string  $file   The path to the module source file.
2623
		 */
2624
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
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...
2625
	}
2626
2627
	/**
2628
	 * Like core's get_file_data implementation, but caches the result.
2629
	 */
2630
	public static function get_file_data( $file, $headers ) {
2631
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2632
		$file_name = basename( $file );
2633
2634
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2635
2636
		$file_data_option = get_transient( $cache_key );
2637
2638
		if ( ! is_array( $file_data_option ) ) {
2639
			delete_transient( $cache_key );
2640
			$file_data_option = false;
2641
		}
2642
2643
		if ( false === $file_data_option ) {
2644
			$file_data_option = array();
2645
		}
2646
2647
		$key           = md5( $file_name . serialize( $headers ) );
2648
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2649
2650
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2651
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2652
			return $file_data_option[ $key ];
2653
		}
2654
2655
		$data = get_file_data( $file, $headers );
2656
2657
		$file_data_option[ $key ] = $data;
2658
2659
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2660
2661
		return $data;
2662
	}
2663
2664
2665
	/**
2666
	 * Return translated module tag.
2667
	 *
2668
	 * @param string $tag Tag as it appears in each module heading.
2669
	 *
2670
	 * @return mixed
2671
	 */
2672
	public static function translate_module_tag( $tag ) {
2673
		return jetpack_get_module_i18n_tag( $tag );
2674
	}
2675
2676
	/**
2677
	 * Get i18n strings as a JSON-encoded string
2678
	 *
2679
	 * @return string The locale as JSON
2680
	 */
2681
	public static function get_i18n_data_json() {
2682
2683
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2684
		// JSON files with the file they should be included for. This is an md5
2685
		// of '_inc/build/admin.js'.
2686
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2687
2688
		$i18n_json =
2689
				   JETPACK__PLUGIN_DIR
2690
				   . 'languages/json/jetpack-'
2691
				   . get_user_locale()
2692
				   . '-'
2693
				   . $path_md5
2694
				   . '.json';
2695
2696
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2697
			$locale_data = @file_get_contents( $i18n_json );
2698
			if ( $locale_data ) {
2699
				return $locale_data;
2700
			}
2701
		}
2702
2703
		// Return valid empty Jed locale
2704
		return '{ "locale_data": { "messages": { "": {} } } }';
2705
	}
2706
2707
	/**
2708
	 * Add locale data setup to wp-i18n
2709
	 *
2710
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2711
	 *
2712
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2713
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2714
	 *
2715
	 * This method provides a safe way to request the setup multiple times but add the script at
2716
	 * most once.
2717
	 *
2718
	 * @since 6.7.0
2719
	 *
2720
	 * @return void
2721
	 */
2722
	public static function setup_wp_i18n_locale_data() {
2723
		static $script_added = false;
2724
		if ( ! $script_added ) {
2725
			$script_added = true;
2726
			wp_add_inline_script(
2727
				'wp-i18n',
2728
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2729
			);
2730
		}
2731
	}
2732
2733
	/**
2734
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2735
	 *
2736
	 * @since 3.9.2
2737
	 *
2738
	 * @param array $modules
2739
	 *
2740
	 * @return string|void
2741
	 */
2742
	public static function get_translated_modules( $modules ) {
2743
		foreach ( $modules as $index => $module ) {
2744
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2745
			if ( isset( $module['name'] ) ) {
2746
				$modules[ $index ]['name'] = $i18n_module['name'];
2747
			}
2748
			if ( isset( $module['description'] ) ) {
2749
				$modules[ $index ]['description']       = $i18n_module['description'];
2750
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2751
			}
2752
		}
2753
		return $modules;
2754
	}
2755
2756
	/**
2757
	 * Get a list of activated modules as an array of module slugs.
2758
	 */
2759
	public static function get_active_modules() {
2760
		$active = Jetpack_Options::get_option( 'active_modules' );
2761
2762
		if ( ! is_array( $active ) ) {
2763
			$active = array();
2764
		}
2765
2766
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2767
			$active[] = 'vaultpress';
2768
		} else {
2769
			$active = array_diff( $active, array( 'vaultpress' ) );
2770
		}
2771
2772
		// If protect is active on the main site of a multisite, it should be active on all sites.
2773
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2774
			$active[] = 'protect';
2775
		}
2776
2777
		/**
2778
		 * Allow filtering of the active modules.
2779
		 *
2780
		 * Gives theme and plugin developers the power to alter the modules that
2781
		 * are activated on the fly.
2782
		 *
2783
		 * @since 5.8.0
2784
		 *
2785
		 * @param array $active Array of active module slugs.
2786
		 */
2787
		$active = apply_filters( 'jetpack_active_modules', $active );
2788
2789
		return array_unique( $active );
2790
	}
2791
2792
	/**
2793
	 * Check whether or not a Jetpack module is active.
2794
	 *
2795
	 * @param string $module The slug of a Jetpack module.
2796
	 * @return bool
2797
	 *
2798
	 * @static
2799
	 */
2800
	public static function is_module_active( $module ) {
2801
		return in_array( $module, self::get_active_modules() );
2802
	}
2803
2804
	public static function is_module( $module ) {
2805
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2806
	}
2807
2808
	/**
2809
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2810
	 *
2811
	 * @param bool $catch True to start catching, False to stop.
2812
	 *
2813
	 * @static
2814
	 */
2815
	public static function catch_errors( $catch ) {
2816
		static $display_errors, $error_reporting;
2817
2818
		if ( $catch ) {
2819
			$display_errors  = @ini_set( 'display_errors', 1 );
2820
			$error_reporting = @error_reporting( E_ALL );
2821
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2822
		} else {
2823
			@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...
2824
			@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...
2825
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2826
		}
2827
	}
2828
2829
	/**
2830
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2831
	 */
2832
	public static function catch_errors_on_shutdown() {
2833
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2834
	}
2835
2836
	/**
2837
	 * Rewrite any string to make paths easier to read.
2838
	 *
2839
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2840
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2841
	 *
2842
	 * @param $string
2843
	 * @return mixed
2844
	 */
2845
	public static function alias_directories( $string ) {
2846
		// ABSPATH has a trailing slash.
2847
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2848
		// WP_CONTENT_DIR does not have a trailing slash.
2849
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2850
2851
		return $string;
2852
	}
2853
2854
	public static function activate_default_modules(
2855
		$min_version = false,
2856
		$max_version = false,
2857
		$other_modules = array(),
2858
		$redirect = null,
2859
		$send_state_messages = null
2860
	) {
2861
		$jetpack = self::init();
2862
2863
		if ( is_null( $redirect ) ) {
2864
			if (
2865
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2866
			||
2867
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2868
			||
2869
				( defined( 'WP_CLI' ) && WP_CLI )
2870
			||
2871
				( defined( 'DOING_CRON' ) && DOING_CRON )
2872
			||
2873
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2874
			) {
2875
				$redirect = false;
2876
			} elseif ( is_admin() ) {
2877
				$redirect = true;
2878
			} else {
2879
				$redirect = false;
2880
			}
2881
		}
2882
2883
		if ( is_null( $send_state_messages ) ) {
2884
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2885
		}
2886
2887
		$modules = self::get_default_modules( $min_version, $max_version );
2888
		$modules = array_merge( $other_modules, $modules );
2889
2890
		// Look for standalone plugins and disable if active.
2891
2892
		$to_deactivate = array();
2893
		foreach ( $modules as $module ) {
2894
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2895
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2896
			}
2897
		}
2898
2899
		$deactivated = array();
2900
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2901
			list( $probable_file, $probable_title ) = $deactivate_me;
2902
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2903
				$deactivated[] = $module;
2904
			}
2905
		}
2906
2907
		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...
2908
			if ( $send_state_messages ) {
2909
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2910
			}
2911
2912
			if ( $redirect ) {
2913
				$url = add_query_arg(
2914
					array(
2915
						'action'   => 'activate_default_modules',
2916
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2917
					),
2918
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2919
				);
2920
				wp_safe_redirect( $url );
2921
				exit;
2922
			}
2923
		}
2924
2925
		/**
2926
		 * Fires before default modules are activated.
2927
		 *
2928
		 * @since 1.9.0
2929
		 *
2930
		 * @param string $min_version Minimum version number required to use modules.
2931
		 * @param string $max_version Maximum version number required to use modules.
2932
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2933
		 */
2934
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2935
2936
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2937
		if ( $send_state_messages ) {
2938
			self::restate();
2939
			self::catch_errors( true );
2940
		}
2941
2942
		$active = self::get_active_modules();
2943
2944
		foreach ( $modules as $module ) {
2945
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2946
				$active[] = $module;
2947
				self::update_active_modules( $active );
2948
				continue;
2949
			}
2950
2951
			if ( $send_state_messages && in_array( $module, $active ) ) {
2952
				$module_info = self::get_module( $module );
2953 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2954
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2955
					if ( $active_state = self::state( $state ) ) {
2956
						$active_state = explode( ',', $active_state );
2957
					} else {
2958
						$active_state = array();
2959
					}
2960
					$active_state[] = $module;
2961
					self::state( $state, implode( ',', $active_state ) );
2962
				}
2963
				continue;
2964
			}
2965
2966
			$file = self::get_module_path( $module );
2967
			if ( ! file_exists( $file ) ) {
2968
				continue;
2969
			}
2970
2971
			// we'll override this later if the plugin can be included without fatal error
2972
			if ( $redirect ) {
2973
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2974
			}
2975
2976
			if ( $send_state_messages ) {
2977
				self::state( 'error', 'module_activation_failed' );
2978
				self::state( 'module', $module );
2979
			}
2980
2981
			ob_start();
2982
			require_once $file;
2983
2984
			$active[] = $module;
2985
2986 View Code Duplication
			if ( $send_state_messages ) {
2987
2988
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2989
				if ( $active_state = self::state( $state ) ) {
2990
					$active_state = explode( ',', $active_state );
2991
				} else {
2992
					$active_state = array();
2993
				}
2994
				$active_state[] = $module;
2995
				self::state( $state, implode( ',', $active_state ) );
2996
			}
2997
2998
			self::update_active_modules( $active );
2999
3000
			ob_end_clean();
3001
		}
3002
3003
		if ( $send_state_messages ) {
3004
			self::state( 'error', false );
0 ignored issues
show
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...
3005
			self::state( 'module', false );
0 ignored issues
show
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...
3006
		}
3007
3008
		self::catch_errors( false );
3009
		/**
3010
		 * Fires when default modules are activated.
3011
		 *
3012
		 * @since 1.9.0
3013
		 *
3014
		 * @param string $min_version Minimum version number required to use modules.
3015
		 * @param string $max_version Maximum version number required to use modules.
3016
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3017
		 */
3018
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3019
	}
3020
3021
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3022
		/**
3023
		 * Fires before a module is activated.
3024
		 *
3025
		 * @since 2.6.0
3026
		 *
3027
		 * @param string $module Module slug.
3028
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3029
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3030
		 */
3031
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3032
3033
		$jetpack = self::init();
3034
3035
		if ( ! strlen( $module ) ) {
3036
			return false;
3037
		}
3038
3039
		if ( ! self::is_module( $module ) ) {
3040
			return false;
3041
		}
3042
3043
		// If it's already active, then don't do it again
3044
		$active = self::get_active_modules();
3045
		foreach ( $active as $act ) {
3046
			if ( $act == $module ) {
3047
				return true;
3048
			}
3049
		}
3050
3051
		$module_data = self::get_module( $module );
3052
3053
		$is_development_mode = ( new Status() )->is_development_mode();
3054
		if ( ! self::is_active() ) {
3055
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3056
				return false;
3057
			}
3058
3059
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3060
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3061
				return false;
3062
			}
3063
		}
3064
3065
		// Check and see if the old plugin is active
3066
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3067
			// Deactivate the old plugin
3068
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3069
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3070
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3071
				self::state( 'deactivated_plugins', $module );
3072
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3073
				exit;
3074
			}
3075
		}
3076
3077
		// Protect won't work with mis-configured IPs
3078
		if ( 'protect' === $module ) {
3079
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3080
			if ( ! jetpack_protect_get_ip() ) {
3081
				self::state( 'message', 'protect_misconfigured_ip' );
3082
				return false;
3083
			}
3084
		}
3085
3086
		if ( ! Jetpack_Plan::supports( $module ) ) {
3087
			return false;
3088
		}
3089
3090
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3091
		self::state( 'module', $module );
3092
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3093
3094
		self::catch_errors( true );
3095
		ob_start();
3096
		require self::get_module_path( $module );
3097
		/** This action is documented in class.jetpack.php */
3098
		do_action( 'jetpack_activate_module', $module );
3099
		$active[] = $module;
3100
		self::update_active_modules( $active );
3101
3102
		self::state( 'error', false ); // the override
0 ignored issues
show
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...
3103
		ob_end_clean();
3104
		self::catch_errors( false );
3105
3106
		if ( $redirect ) {
3107
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3108
		}
3109
		if ( $exit ) {
3110
			exit;
3111
		}
3112
		return true;
3113
	}
3114
3115
	function activate_module_actions( $module ) {
3116
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3117
	}
3118
3119
	public static function deactivate_module( $module ) {
3120
		/**
3121
		 * Fires when a module is deactivated.
3122
		 *
3123
		 * @since 1.9.0
3124
		 *
3125
		 * @param string $module Module slug.
3126
		 */
3127
		do_action( 'jetpack_pre_deactivate_module', $module );
3128
3129
		$jetpack = self::init();
0 ignored issues
show
$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...
3130
3131
		$active = self::get_active_modules();
3132
		$new    = array_filter( array_diff( $active, (array) $module ) );
3133
3134
		return self::update_active_modules( $new );
3135
	}
3136
3137
	public static function enable_module_configurable( $module ) {
3138
		$module = self::get_module_slug( $module );
3139
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3140
	}
3141
3142
	/**
3143
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3144
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3145
	 *
3146
	 * @param string $module Module slug
3147
	 * @return string $url module configuration URL
3148
	 */
3149
	public static function module_configuration_url( $module ) {
3150
		$module      = self::get_module_slug( $module );
3151
		$default_url = self::admin_url() . "#/settings?term=$module";
3152
		/**
3153
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3154
		 *
3155
		 * @since 6.9.0
3156
		 *
3157
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3158
		 */
3159
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3160
3161
		return $url;
3162
	}
3163
3164
	/* Installation */
3165
	public static function bail_on_activation( $message, $deactivate = true ) {
3166
		?>
3167
<!doctype html>
3168
<html>
3169
<head>
3170
<meta charset="<?php bloginfo( 'charset' ); ?>">
3171
<style>
3172
* {
3173
	text-align: center;
3174
	margin: 0;
3175
	padding: 0;
3176
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3177
}
3178
p {
3179
	margin-top: 1em;
3180
	font-size: 18px;
3181
}
3182
</style>
3183
<body>
3184
<p><?php echo esc_html( $message ); ?></p>
3185
</body>
3186
</html>
3187
		<?php
3188
		if ( $deactivate ) {
3189
			$plugins = get_option( 'active_plugins' );
3190
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3191
			$update  = false;
3192
			foreach ( $plugins as $i => $plugin ) {
3193
				if ( $plugin === $jetpack ) {
3194
					$plugins[ $i ] = false;
3195
					$update        = true;
3196
				}
3197
			}
3198
3199
			if ( $update ) {
3200
				update_option( 'active_plugins', array_filter( $plugins ) );
3201
			}
3202
		}
3203
		exit;
3204
	}
3205
3206
	/**
3207
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3208
	 *
3209
	 * @static
3210
	 */
3211
	public static function plugin_activation( $network_wide ) {
3212
		Jetpack_Options::update_option( 'activated', 1 );
3213
3214
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3215
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3216
		}
3217
3218
		if ( $network_wide ) {
3219
			self::state( 'network_nag', true );
0 ignored issues
show
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...
3220
		}
3221
3222
		// For firing one-off events (notices) immediately after activation
3223
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3224
3225
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3226
3227
		Health::on_jetpack_activated();
3228
3229
		self::plugin_initialize();
3230
	}
3231
3232
	public static function get_activation_source( $referer_url ) {
3233
3234
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3235
			return array( 'wp-cli', null );
3236
		}
3237
3238
		$referer = wp_parse_url( $referer_url );
3239
3240
		$source_type  = 'unknown';
3241
		$source_query = null;
3242
3243
		if ( ! is_array( $referer ) ) {
3244
			return array( $source_type, $source_query );
3245
		}
3246
3247
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
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...
3248
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
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...
3249
3250
		if ( isset( $referer['query'] ) ) {
3251
			parse_str( $referer['query'], $query_parts );
3252
		} else {
3253
			$query_parts = array();
3254
		}
3255
3256
		if ( $plugins_path === $referer['path'] ) {
3257
			$source_type = 'list';
3258
		} elseif ( $plugins_install_path === $referer['path'] ) {
3259
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3260
			switch ( $tab ) {
3261
				case 'popular':
3262
					$source_type = 'popular';
3263
					break;
3264
				case 'recommended':
3265
					$source_type = 'recommended';
3266
					break;
3267
				case 'favorites':
3268
					$source_type = 'favorites';
3269
					break;
3270
				case 'search':
3271
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3272
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3273
					break;
3274
				default:
3275
					$source_type = 'featured';
3276
			}
3277
		}
3278
3279
		return array( $source_type, $source_query );
3280
	}
3281
3282
	/**
3283
	 * Runs before bumping version numbers up to a new version
3284
	 *
3285
	 * @param string $version    Version:timestamp.
3286
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3287
	 */
3288
	public static function do_version_bump( $version, $old_version ) {
3289
		if ( $old_version ) { // For existing Jetpack installations.
3290
3291
			// If a front end page is visited after the update, the 'wp' action will fire.
3292
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3293
3294
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3295
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3296
		}
3297
	}
3298
3299
	/**
3300
	 * Sets the display_update_modal state.
3301
	 */
3302
	public static function set_update_modal_display() {
3303
		self::state( 'display_update_modal', true );
0 ignored issues
show
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...
3304
	}
3305
3306
	/**
3307
	 * Sets the internal version number and activation state.
3308
	 *
3309
	 * @static
3310
	 */
3311
	public static function plugin_initialize() {
3312
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3313
			Jetpack_Options::update_option( 'activated', 2 );
3314
		}
3315
3316 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3317
			$version = $old_version = JETPACK__VERSION . ':' . time();
3318
			/** This action is documented in class.jetpack.php */
3319
			do_action( 'updating_jetpack_version', $version, false );
3320
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3321
		}
3322
3323
		self::load_modules();
3324
3325
		Jetpack_Options::delete_option( 'do_activate' );
3326
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3327
	}
3328
3329
	/**
3330
	 * Removes all connection options
3331
	 *
3332
	 * @static
3333
	 */
3334
	public static function plugin_deactivation() {
3335
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3336
		$tracking = new Tracking();
3337
		$tracking->record_user_event( 'deactivate_plugin', array() );
3338
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3339
			Jetpack_Network::init()->deactivate();
3340
		} else {
3341
			self::disconnect( false );
3342
			// Jetpack_Heartbeat::init()->deactivate();
3343
		}
3344
	}
3345
3346
	/**
3347
	 * Disconnects from the Jetpack servers.
3348
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3349
	 *
3350
	 * @static
3351
	 */
3352
	public static function disconnect( $update_activated_state = true ) {
3353
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3354
		$connection = self::connection();
3355
		$connection->clean_nonces( true );
3356
3357
		// If the site is in an IDC because sync is not allowed,
3358
		// let's make sure to not disconnect the production site.
3359
		if ( ! self::validate_sync_error_idc_option() ) {
3360
			$tracking = new Tracking();
3361
			$tracking->record_user_event( 'disconnect_site', array() );
3362
3363
			$connection->disconnect_site_wpcom( true );
3364
		}
3365
3366
		$connection->delete_all_connection_tokens( true );
3367
		Jetpack_IDC::clear_all_idc_options();
3368
3369
		if ( $update_activated_state ) {
3370
			Jetpack_Options::update_option( 'activated', 4 );
3371
		}
3372
3373
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3374
			// Check then record unique disconnection if site has never been disconnected previously
3375
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3376
				$jetpack_unique_connection['disconnected'] = 1;
3377
			} else {
3378
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3379
					// track unique disconnect
3380
					$jetpack = self::init();
3381
3382
					$jetpack->stat( 'connections', 'unique-disconnect' );
3383
					$jetpack->do_stats( 'server_side' );
3384
				}
3385
				// increment number of times disconnected
3386
				$jetpack_unique_connection['disconnected'] += 1;
3387
			}
3388
3389
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3390
		}
3391
3392
		// Delete all the sync related data. Since it could be taking up space.
3393
		Sender::get_instance()->uninstall();
3394
3395
		// Disable the Heartbeat cron
3396
		Jetpack_Heartbeat::init()->deactivate();
3397
	}
3398
3399
	/**
3400
	 * Unlinks the current user from the linked WordPress.com user.
3401
	 *
3402
	 * @deprecated since 7.7
3403
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3404
	 *
3405
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
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...
3406
	 * @return Boolean Whether the disconnection of the user was successful.
3407
	 */
3408
	public static function unlink_user( $user_id = null ) {
3409
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3410
		return Connection_Manager::disconnect_user( $user_id );
3411
	}
3412
3413
	/**
3414
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3415
	 */
3416
	public static function try_registration() {
3417
		$terms_of_service = new Terms_Of_Service();
3418
		// The user has agreed to the TOS at some point by now.
3419
		$terms_of_service->agree();
3420
3421
		// Let's get some testing in beta versions and such.
3422
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3423
			// Before attempting to connect, let's make sure that the domains are viable.
3424
			$domains_to_check = array_unique(
3425
				array(
3426
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
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...
3427
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
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...
3428
				)
3429
			);
3430
			foreach ( $domains_to_check as $domain ) {
3431
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
$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...
3432
				if ( is_wp_error( $result ) ) {
3433
					return $result;
3434
				}
3435
			}
3436
		}
3437
3438
		$result = self::register();
3439
3440
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3441
		if ( ! $result || is_wp_error( $result ) ) {
3442
			return $result;
3443
		} else {
3444
			return true;
3445
		}
3446
	}
3447
3448
	/**
3449
	 * Tracking an internal event log. Try not to put too much chaff in here.
3450
	 *
3451
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3452
	 */
3453
	public static function log( $code, $data = null ) {
3454
		// only grab the latest 200 entries
3455
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3456
3457
		// Append our event to the log
3458
		$log_entry = array(
3459
			'time'    => time(),
3460
			'user_id' => get_current_user_id(),
3461
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3462
			'code'    => $code,
3463
		);
3464
		// Don't bother storing it unless we've got some.
3465
		if ( ! is_null( $data ) ) {
3466
			$log_entry['data'] = $data;
3467
		}
3468
		$log[] = $log_entry;
3469
3470
		// Try add_option first, to make sure it's not autoloaded.
3471
		// @todo: Add an add_option method to Jetpack_Options
3472
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3473
			Jetpack_Options::update_option( 'log', $log );
3474
		}
3475
3476
		/**
3477
		 * Fires when Jetpack logs an internal event.
3478
		 *
3479
		 * @since 3.0.0
3480
		 *
3481
		 * @param array $log_entry {
3482
		 *  Array of details about the log entry.
3483
		 *
3484
		 *  @param string time Time of the event.
3485
		 *  @param int user_id ID of the user who trigerred the event.
3486
		 *  @param int blog_id Jetpack Blog ID.
3487
		 *  @param string code Unique name for the event.
3488
		 *  @param string data Data about the event.
3489
		 * }
3490
		 */
3491
		do_action( 'jetpack_log_entry', $log_entry );
3492
	}
3493
3494
	/**
3495
	 * Get the internal event log.
3496
	 *
3497
	 * @param $event (string) - only return the specific log events
3498
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3499
	 *
3500
	 * @return array of log events || WP_Error for invalid params
3501
	 */
3502
	public static function get_log( $event = false, $num = false ) {
3503
		if ( $event && ! is_string( $event ) ) {
3504
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
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...
3505
		}
3506
3507
		if ( $num && ! is_numeric( $num ) ) {
3508
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
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...
3509
		}
3510
3511
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3512
3513
		// If nothing set - act as it did before, otherwise let's start customizing the output
3514
		if ( ! $num && ! $event ) {
3515
			return $entire_log;
3516
		} else {
3517
			$entire_log = array_reverse( $entire_log );
3518
		}
3519
3520
		$custom_log_output = array();
3521
3522
		if ( $event ) {
3523
			foreach ( $entire_log as $log_event ) {
3524
				if ( $event == $log_event['code'] ) {
3525
					$custom_log_output[] = $log_event;
3526
				}
3527
			}
3528
		} else {
3529
			$custom_log_output = $entire_log;
3530
		}
3531
3532
		if ( $num ) {
3533
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3534
		}
3535
3536
		return $custom_log_output;
3537
	}
3538
3539
	/**
3540
	 * Log modification of important settings.
3541
	 */
3542
	public static function log_settings_change( $option, $old_value, $value ) {
3543
		switch ( $option ) {
3544
			case 'jetpack_sync_non_public_post_stati':
3545
				self::log( $option, $value );
3546
				break;
3547
		}
3548
	}
3549
3550
	/**
3551
	 * Return stat data for WPCOM sync
3552
	 */
3553
	public static function get_stat_data( $encode = true, $extended = true ) {
3554
		$data = Jetpack_Heartbeat::generate_stats_array();
3555
3556
		if ( $extended ) {
3557
			$additional_data = self::get_additional_stat_data();
3558
			$data            = array_merge( $data, $additional_data );
3559
		}
3560
3561
		if ( $encode ) {
3562
			return json_encode( $data );
3563
		}
3564
3565
		return $data;
3566
	}
3567
3568
	/**
3569
	 * Get additional stat data to sync to WPCOM
3570
	 */
3571
	public static function get_additional_stat_data( $prefix = '' ) {
3572
		$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...
3573
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3574
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3575
		$return[ "{$prefix}site-count" ]    = 0;
3576
3577
		if ( function_exists( 'get_blog_count' ) ) {
3578
			$return[ "{$prefix}site-count" ] = get_blog_count();
3579
		}
3580
		return $return;
3581
	}
3582
3583
	private static function get_site_user_count() {
3584
		global $wpdb;
3585
3586
		if ( function_exists( 'wp_is_large_network' ) ) {
3587
			if ( wp_is_large_network( 'users' ) ) {
3588
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3589
			}
3590
		}
3591
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3592
			// It wasn't there, so regenerate the data and save the transient
3593
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3594
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3595
		}
3596
		return $user_count;
3597
	}
3598
3599
	/* Admin Pages */
3600
3601
	function admin_init() {
3602
		// If the plugin is not connected, display a connect message.
3603
		if (
3604
			// the plugin was auto-activated and needs its candy
3605
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3606
		||
3607
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3608
			! Jetpack_Options::get_option( 'activated' )
3609
		) {
3610
			self::plugin_initialize();
3611
		}
3612
3613
		$is_development_mode = ( new Status() )->is_development_mode();
3614
		if ( ! self::is_active() && ! $is_development_mode ) {
3615
			Jetpack_Connection_Banner::init();
3616
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3617
			// Upgrade: 1.1 -> 1.1.1
3618
			// Check and see if host can verify the Jetpack servers' SSL certificate
3619
			$args       = array();
3620
			$connection = self::connection();
3621
			Client::_wp_remote_request(
3622
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3623
				$args,
3624
				true
3625
			);
3626
		}
3627
3628
		Jetpack_Wizard_Banner::init();
3629
3630
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3631
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3632
		}
3633
3634
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3635
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3636
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3637
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3638
3639
		if ( self::is_active() || $is_development_mode ) {
3640
			// Artificially throw errors in certain specific cases during plugin activation.
3641
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3642
		}
3643
3644
		// Add custom column in wp-admin/users.php to show whether user is linked.
3645
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3646
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3647
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3648
	}
3649
3650
	function admin_body_class( $admin_body_class = '' ) {
3651
		$classes = explode( ' ', trim( $admin_body_class ) );
3652
3653
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3654
3655
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3656
		return " $admin_body_class ";
3657
	}
3658
3659
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3660
		return $admin_body_class . ' jetpack-pagestyles ';
3661
	}
3662
3663
	/**
3664
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3665
	 * This function artificially throws errors for such cases (per a specific list).
3666
	 *
3667
	 * @param string $plugin The activated plugin.
3668
	 */
3669
	function throw_error_on_activate_plugin( $plugin ) {
3670
		$active_modules = self::get_active_modules();
3671
3672
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3673
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3674
			$throw = false;
3675
3676
			// Try and make sure it really was the stats plugin
3677
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3678
				if ( 'stats.php' == basename( $plugin ) ) {
3679
					$throw = true;
3680
				}
3681
			} else {
3682
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3683
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3684
					$throw = true;
3685
				}
3686
			}
3687
3688
			if ( $throw ) {
3689
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3690
			}
3691
		}
3692
	}
3693
3694
	function intercept_plugin_error_scrape_init() {
3695
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3696
	}
3697
3698
	function intercept_plugin_error_scrape( $action, $result ) {
3699
		if ( ! $result ) {
3700
			return;
3701
		}
3702
3703
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3704
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3705
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3706
			}
3707
		}
3708
	}
3709
3710
	/**
3711
	 * Register the remote file upload request handlers, if needed.
3712
	 *
3713
	 * @access public
3714
	 */
3715
	public function add_remote_request_handlers() {
3716
		// Remote file uploads are allowed only via AJAX requests.
3717
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3718
			return;
3719
		}
3720
3721
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3722
		$remote_request_actions = array(
3723
			'jetpack_upload_file',
3724
			'jetpack_update_file',
3725
		);
3726
3727
		// phpcs:ignore WordPress.Security.NonceVerification
3728
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3729
			return;
3730
		}
3731
3732
		// Require Jetpack authentication for the remote file upload AJAX requests.
3733
		if ( ! $this->connection_manager ) {
3734
			$this->connection_manager = new Connection_Manager();
3735
		}
3736
3737
		$this->connection_manager->require_jetpack_authentication();
3738
3739
		// Register the remote file upload AJAX handlers.
3740
		foreach ( $remote_request_actions as $action ) {
3741
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3742
		}
3743
	}
3744
3745
	/**
3746
	 * Handler for Jetpack remote file uploads.
3747
	 *
3748
	 * @access public
3749
	 */
3750
	public function remote_request_handlers() {
3751
		$action = current_filter();
0 ignored issues
show
$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...
3752
3753
		switch ( current_filter() ) {
3754
			case 'wp_ajax_nopriv_jetpack_upload_file':
3755
				$response = $this->upload_handler();
3756
				break;
3757
3758
			case 'wp_ajax_nopriv_jetpack_update_file':
3759
				$response = $this->upload_handler( true );
3760
				break;
3761
			default:
3762
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
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...
3763
				break;
3764
		}
3765
3766
		if ( ! $response ) {
3767
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
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...
3768
		}
3769
3770
		if ( is_wp_error( $response ) ) {
3771
			$status_code       = $response->get_error_data();
0 ignored issues
show
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...
3772
			$error             = $response->get_error_code();
0 ignored issues
show
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...
3773
			$error_description = $response->get_error_message();
0 ignored issues
show
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...
3774
3775
			if ( ! is_int( $status_code ) ) {
3776
				$status_code = 400;
3777
			}
3778
3779
			status_header( $status_code );
3780
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3781
		}
3782
3783
		status_header( 200 );
3784
		if ( true === $response ) {
3785
			exit;
3786
		}
3787
3788
		die( json_encode( (object) $response ) );
3789
	}
3790
3791
	/**
3792
	 * Uploads a file gotten from the global $_FILES.
3793
	 * If `$update_media_item` is true and `post_id` is defined
3794
	 * the attachment file of the media item (gotten through of the post_id)
3795
	 * will be updated instead of add a new one.
3796
	 *
3797
	 * @param  boolean $update_media_item - update media attachment
3798
	 * @return array - An array describing the uploadind files process
3799
	 */
3800
	function upload_handler( $update_media_item = false ) {
3801
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3802
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
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...
3803
		}
3804
3805
		$user = wp_authenticate( '', '' );
3806
		if ( ! $user || is_wp_error( $user ) ) {
3807
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
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...
3808
		}
3809
3810
		wp_set_current_user( $user->ID );
3811
3812
		if ( ! current_user_can( 'upload_files' ) ) {
3813
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
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...
3814
		}
3815
3816
		if ( empty( $_FILES ) ) {
3817
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
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...
3818
		}
3819
3820
		foreach ( array_keys( $_FILES ) as $files_key ) {
3821
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3822
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
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...
3823
			}
3824
		}
3825
3826
		$media_keys = array_keys( $_FILES['media'] );
3827
3828
		$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...
3829
		if ( ! $token || is_wp_error( $token ) ) {
3830
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
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...
3831
		}
3832
3833
		$uploaded_files = array();
3834
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3835
		unset( $GLOBALS['post'] );
3836
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3837
			$file = array();
3838
			foreach ( $media_keys as $media_key ) {
3839
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3840
			}
3841
3842
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3843
3844
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3845
			if ( $hmac_provided !== $hmac_file ) {
3846
				$uploaded_files[ $index ] = (object) array(
3847
					'error'             => 'invalid_hmac',
3848
					'error_description' => 'The corresponding HMAC for this file does not match',
3849
				);
3850
				continue;
3851
			}
3852
3853
			$_FILES['.jetpack.upload.'] = $file;
3854
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3855
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3856
				$post_id = 0;
3857
			}
3858
3859
			if ( $update_media_item ) {
3860
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3861
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
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...
3862
				}
3863
3864
				$media_array = $_FILES['media'];
3865
3866
				$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...
3867
				$file_array['type']     = $media_array['type'][0];
3868
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3869
				$file_array['error']    = $media_array['error'][0];
3870
				$file_array['size']     = $media_array['size'][0];
3871
3872
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3873
3874
				if ( is_wp_error( $edited_media_item ) ) {
3875
					return $edited_media_item;
3876
				}
3877
3878
				$response = (object) array(
3879
					'id'   => (string) $post_id,
3880
					'file' => (string) $edited_media_item->post_title,
3881
					'url'  => (string) wp_get_attachment_url( $post_id ),
3882
					'type' => (string) $edited_media_item->post_mime_type,
3883
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3884
				);
3885
3886
				return (array) array( $response );
3887
			}
3888
3889
			$attachment_id = media_handle_upload(
3890
				'.jetpack.upload.',
3891
				$post_id,
3892
				array(),
3893
				array(
3894
					'action' => 'jetpack_upload_file',
3895
				)
3896
			);
3897
3898
			if ( ! $attachment_id ) {
3899
				$uploaded_files[ $index ] = (object) array(
3900
					'error'             => 'unknown',
3901
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3902
				);
3903
			} elseif ( is_wp_error( $attachment_id ) ) {
3904
				$uploaded_files[ $index ] = (object) array(
3905
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3906
					'error_description' => $attachment_id->get_error_message(),
3907
				);
3908
			} else {
3909
				$attachment               = get_post( $attachment_id );
3910
				$uploaded_files[ $index ] = (object) array(
3911
					'id'   => (string) $attachment_id,
3912
					'file' => $attachment->post_title,
3913
					'url'  => wp_get_attachment_url( $attachment_id ),
3914
					'type' => $attachment->post_mime_type,
3915
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3916
				);
3917
				// Zip files uploads are not supported unless they are done for installation purposed
3918
				// lets delete them in case something goes wrong in this whole process
3919
				if ( 'application/zip' === $attachment->post_mime_type ) {
3920
					// Schedule a cleanup for 2 hours from now in case of failed install.
3921
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3922
				}
3923
			}
3924
		}
3925
		if ( ! is_null( $global_post ) ) {
3926
			$GLOBALS['post'] = $global_post;
3927
		}
3928
3929
		return $uploaded_files;
3930
	}
3931
3932
	/**
3933
	 * Add help to the Jetpack page
3934
	 *
3935
	 * @since Jetpack (1.2.3)
3936
	 * @return false if not the Jetpack page
3937
	 */
3938
	function admin_help() {
3939
		$current_screen = get_current_screen();
3940
3941
		// Overview
3942
		$current_screen->add_help_tab(
3943
			array(
3944
				'id'      => 'home',
3945
				'title'   => __( 'Home', 'jetpack' ),
3946
				'content' =>
3947
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3948
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3949
					'<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>',
3950
			)
3951
		);
3952
3953
		// Screen Content
3954
		if ( current_user_can( 'manage_options' ) ) {
3955
			$current_screen->add_help_tab(
3956
				array(
3957
					'id'      => 'settings',
3958
					'title'   => __( 'Settings', 'jetpack' ),
3959
					'content' =>
3960
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3961
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3962
						'<ol>' .
3963
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3964
							'<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>' .
3965
						'</ol>' .
3966
						'<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>',
3967
				)
3968
			);
3969
		}
3970
3971
		// Help Sidebar
3972
		$support_url = Redirect::get_url( 'jetpack-support' );
3973
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3974
		$current_screen->set_help_sidebar(
3975
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3976
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3977
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3978
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3979
		);
3980
	}
3981
3982
	function admin_menu_css() {
3983
		wp_enqueue_style( 'jetpack-icons' );
3984
	}
3985
3986
	function admin_menu_order() {
3987
		return true;
3988
	}
3989
3990 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3991
		$jp_menu_order = array();
3992
3993
		foreach ( $menu_order as $index => $item ) {
3994
			if ( $item != 'jetpack' ) {
3995
				$jp_menu_order[] = $item;
3996
			}
3997
3998
			if ( $index == 0 ) {
3999
				$jp_menu_order[] = 'jetpack';
4000
			}
4001
		}
4002
4003
		return $jp_menu_order;
4004
	}
4005
4006
	function admin_banner_styles() {
4007
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4008
4009 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4010
			wp_register_style(
4011
				'jetpack-dops-style',
4012
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4013
				array(),
4014
				JETPACK__VERSION
4015
			);
4016
		}
4017
4018
		wp_enqueue_style(
4019
			'jetpack',
4020
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4021
			array( 'jetpack-dops-style' ),
4022
			JETPACK__VERSION . '-20121016'
4023
		);
4024
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4025
		wp_style_add_data( 'jetpack', 'suffix', $min );
4026
	}
4027
4028
	function plugin_action_links( $actions ) {
4029
4030
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4031
4032
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4033
			return array_merge(
4034
				$jetpack_home,
4035
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4036
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4037
				$actions
4038
			);
4039
		}
4040
4041
		return array_merge( $jetpack_home, $actions );
4042
	}
4043
4044
	/**
4045
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4046
	 *
4047
	 * @param string $hook The current admin page.
4048
	 *
4049
	 * @return void
4050
	 */
4051
	public function deactivate_dialog( $hook ) {
4052
		if (
4053
			'plugins.php' === $hook
4054
			&& self::is_active()
4055
		) {
4056
4057
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4058
4059
			if ( count( $active_plugins_using_connection ) > 1 ) {
4060
4061
				add_thickbox();
4062
4063
				wp_register_script(
4064
					'jp-tracks',
4065
					'//stats.wp.com/w.js',
4066
					array(),
4067
					gmdate( 'YW' ),
4068
					true
4069
				);
4070
4071
				wp_register_script(
4072
					'jp-tracks-functions',
4073
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4074
					array( 'jp-tracks' ),
4075
					JETPACK__VERSION,
4076
					false
4077
				);
4078
4079
				wp_enqueue_script(
4080
					'jetpack-deactivate-dialog-js',
4081
					Assets::get_file_url_for_environment(
4082
						'_inc/build/jetpack-deactivate-dialog.min.js',
4083
						'_inc/jetpack-deactivate-dialog.js'
4084
					),
4085
					array( 'jquery', 'jp-tracks-functions' ),
4086
					JETPACK__VERSION,
4087
					true
4088
				);
4089
4090
				wp_localize_script(
4091
					'jetpack-deactivate-dialog-js',
4092
					'deactivate_dialog',
4093
					array(
4094
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4095
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4096
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4097
					)
4098
				);
4099
4100
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4101
4102
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4103
			}
4104
		}
4105
	}
4106
4107
	/**
4108
	 * Outputs the content of the deactivation modal
4109
	 *
4110
	 * @return void
4111
	 */
4112
	public function deactivate_dialog_content() {
4113
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4114
		unset( $active_plugins_using_connection['jetpack'] );
4115
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4113 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...
4116
	}
4117
4118
	/**
4119
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4120
	 *
4121
	 * @param string $login_url The wp-login URL.
4122
	 * @param string $redirect  URL to redirect users after logging in.
4123
	 * @since Jetpack 8.4
4124
	 * @return string
4125
	 */
4126
	public function login_url( $login_url, $redirect ) {
4127
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
0 ignored issues
show
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...
4128
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4129
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4130
		}
4131
		return $login_url;
4132
	}
4133
4134
	/**
4135
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4136
	 *
4137
	 * @since Jetpack 8.4
4138
	 */
4139
	public function login_init() {
4140
		// phpcs:ignore WordPress.Security.NonceVerification
4141
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4142
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4143
			wp_safe_redirect(
4144
				add_query_arg(
4145
					array(
4146
						'forceInstall' => 1,
4147
						'url'          => rawurlencode( get_site_url() ),
4148
					),
4149
					// @todo provide way to go to specific calypso env.
4150
					self::get_calypso_host() . 'jetpack/connect'
4151
				)
4152
			);
4153
			exit;
4154
		}
4155
	}
4156
4157
	/*
4158
	 * Registration flow:
4159
	 * 1 - ::admin_page_load() action=register
4160
	 * 2 - ::try_registration()
4161
	 * 3 - ::register()
4162
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4163
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4164
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4165
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4166
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4167
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4168
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4169
	 *       jetpack_id, jetpack_secret, jetpack_public
4170
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4171
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4172
	 * 5 - user logs in with WP.com account
4173
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4174
	 *		- Manager::authorize()
4175
	 *		- Manager::get_token()
4176
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4177
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4178
	 *			- which responds with access_token, token_type, scope
4179
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4180
	 *		- Jetpack::activate_default_modules()
4181
	 *     		- Deactivates deprecated plugins
4182
	 *     		- Activates all default modules
4183
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4184
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4185
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4186
	 *     Done!
4187
	 */
4188
4189
	/**
4190
	 * Handles the page load events for the Jetpack admin page
4191
	 */
4192
	function admin_page_load() {
4193
		$error = false;
4194
4195
		// Make sure we have the right body class to hook stylings for subpages off of.
4196
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4197
4198
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4199
			// Should only be used in intermediate redirects to preserve state across redirects
4200
			self::restate();
4201
		}
4202
4203
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4204
			// @todo: Add validation against a known allowed list.
4205
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4206
			// User clicked in the iframe to link their accounts
4207
			if ( ! self::is_user_connected() ) {
4208
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4209
4210
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4211
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4212
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4213
4214
				if ( isset( $_GET['notes_iframe'] ) ) {
4215
					$connect_url .= '&notes_iframe';
4216
				}
4217
				wp_redirect( $connect_url );
4218
				exit;
4219
			} else {
4220
				if ( ! isset( $_GET['calypso_env'] ) ) {
4221
					self::state( 'message', 'already_authorized' );
4222
					wp_safe_redirect( self::admin_url() );
4223
					exit;
4224
				} else {
4225
					$connect_url  = $this->build_connect_url( true, false, $from );
4226
					$connect_url .= '&already_authorized=true';
4227
					wp_redirect( $connect_url );
4228
					exit;
4229
				}
4230
			}
4231
		}
4232
4233
		if ( isset( $_GET['action'] ) ) {
4234
			switch ( $_GET['action'] ) {
4235
				case 'authorize':
4236
					if ( self::is_active() && self::is_user_connected() ) {
4237
						self::state( 'message', 'already_authorized' );
4238
						wp_safe_redirect( self::admin_url() );
4239
						exit;
4240
					}
4241
					self::log( 'authorize' );
4242
					$client_server = new Jetpack_Client_Server();
4243
					$client_server->client_authorize();
4244
					exit;
4245
				case 'register':
4246
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4247
						$error = 'cheatin';
4248
						break;
4249
					}
4250
					check_admin_referer( 'jetpack-register' );
4251
					self::log( 'register' );
4252
					self::maybe_set_version_option();
4253
					$registered = self::try_registration();
4254 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4255
						$error = $registered->get_error_code();
0 ignored issues
show
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...
4256
						self::state( 'error', $error );
4257
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
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...
4258
4259
						/**
4260
						 * Jetpack registration Error.
4261
						 *
4262
						 * @since 7.5.0
4263
						 *
4264
						 * @param string|int $error The error code.
4265
						 * @param \WP_Error $registered The error object.
4266
						 */
4267
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4268
						break;
4269
					}
4270
4271
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4272
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4273
4274
					/**
4275
					 * Jetpack registration Success.
4276
					 *
4277
					 * @since 7.5.0
4278
					 *
4279
					 * @param string $from 'from' GET parameter;
4280
					 */
4281
					do_action( 'jetpack_connection_register_success', $from );
4282
4283
					$url = $this->build_connect_url( true, $redirect, $from );
4284
4285
					if ( ! empty( $_GET['onboarding'] ) ) {
4286
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4287
					}
4288
4289
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4290
						$url = add_query_arg( 'auth_approved', 'true', $url );
4291
					}
4292
4293
					wp_redirect( $url );
4294
					exit;
4295
				case 'activate':
4296
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4297
						$error = 'cheatin';
4298
						break;
4299
					}
4300
4301
					$module = stripslashes( $_GET['module'] );
4302
					check_admin_referer( "jetpack_activate-$module" );
4303
					self::log( 'activate', $module );
4304
					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...
4305
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4306
					}
4307
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4308
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4309
					exit;
4310
				case 'activate_default_modules':
4311
					check_admin_referer( 'activate_default_modules' );
4312
					self::log( 'activate_default_modules' );
4313
					self::restate();
4314
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4315
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4316
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4317
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4318
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4319
					exit;
4320
				case 'disconnect':
4321
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4322
						$error = 'cheatin';
4323
						break;
4324
					}
4325
4326
					check_admin_referer( 'jetpack-disconnect' );
4327
					self::log( 'disconnect' );
4328
					self::disconnect();
4329
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4330
					exit;
4331
				case 'reconnect':
4332
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4333
						$error = 'cheatin';
4334
						break;
4335
					}
4336
4337
					check_admin_referer( 'jetpack-reconnect' );
4338
					self::log( 'reconnect' );
4339
					$this->disconnect();
4340
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4341
					exit;
4342 View Code Duplication
				case 'deactivate':
4343
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4344
						$error = 'cheatin';
4345
						break;
4346
					}
4347
4348
					$modules = stripslashes( $_GET['module'] );
4349
					check_admin_referer( "jetpack_deactivate-$modules" );
4350
					foreach ( explode( ',', $modules ) as $module ) {
4351
						self::log( 'deactivate', $module );
4352
						self::deactivate_module( $module );
4353
						self::state( 'message', 'module_deactivated' );
4354
					}
4355
					self::state( 'module', $modules );
4356
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4357
					exit;
4358
				case 'unlink':
4359
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4360
					check_admin_referer( 'jetpack-unlink' );
4361
					self::log( 'unlink' );
4362
					Connection_Manager::disconnect_user();
4363
					self::state( 'message', 'unlinked' );
4364
					if ( 'sub-unlink' == $redirect ) {
4365
						wp_safe_redirect( admin_url() );
4366
					} else {
4367
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4368
					}
4369
					exit;
4370
				case 'onboard':
4371
					if ( ! current_user_can( 'manage_options' ) ) {
4372
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4373
					} else {
4374
						self::create_onboarding_token();
4375
						$url = $this->build_connect_url( true );
4376
4377
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4378
							$url = add_query_arg( 'onboarding', $token, $url );
4379
						}
4380
4381
						$calypso_env = $this->get_calypso_env();
4382
						if ( ! empty( $calypso_env ) ) {
4383
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4384
						}
4385
4386
						wp_redirect( $url );
4387
						exit;
4388
					}
4389
					exit;
4390
				default:
4391
					/**
4392
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4393
					 *
4394
					 * @since 2.6.0
4395
					 *
4396
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4397
					 */
4398
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4399
			}
4400
		}
4401
4402
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4403
			self::activate_new_modules( true );
4404
		}
4405
4406
		$message_code = self::state( 'message' );
4407
		if ( self::state( 'optin-manage' ) ) {
4408
			$activated_manage = $message_code;
4409
			$message_code     = 'jetpack-manage';
4410
		}
4411
4412
		switch ( $message_code ) {
4413
			case 'jetpack-manage':
4414
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4415
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4416
				$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>';
4417
				if ( $activated_manage ) {
0 ignored issues
show
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...
4418
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4419
				}
4420
				break;
4421
4422
		}
4423
4424
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4425
4426
		if ( ! empty( $deactivated_plugins ) ) {
4427
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4428
			$deactivated_titles  = array();
4429
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4430
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4431
					continue;
4432
				}
4433
4434
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4435
			}
4436
4437
			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...
4438
				if ( $this->message ) {
4439
					$this->message .= "<br /><br />\n";
4440
				}
4441
4442
				$this->message .= wp_sprintf(
4443
					_n(
4444
						'Jetpack contains the most recent version of the old %l plugin.',
4445
						'Jetpack contains the most recent versions of the old %l plugins.',
4446
						count( $deactivated_titles ),
4447
						'jetpack'
4448
					),
4449
					$deactivated_titles
4450
				);
4451
4452
				$this->message .= "<br />\n";
4453
4454
				$this->message .= _n(
4455
					'The old version has been deactivated and can be removed from your site.',
4456
					'The old versions have been deactivated and can be removed from your site.',
4457
					count( $deactivated_titles ),
4458
					'jetpack'
4459
				);
4460
			}
4461
		}
4462
4463
		$this->privacy_checks = self::state( 'privacy_checks' );
4464
4465
		if ( $this->message || $this->error || $this->privacy_checks ) {
4466
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4467
		}
4468
4469
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4470
	}
4471
4472
	function admin_notices() {
4473
4474
		if ( $this->error ) {
4475
			?>
4476
<div id="message" class="jetpack-message jetpack-err">
4477
	<div class="squeezer">
4478
		<h2>
4479
			<?php
4480
			echo wp_kses(
4481
				$this->error,
4482
				array(
4483
					'a'      => array( 'href' => array() ),
4484
					'small'  => true,
4485
					'code'   => true,
4486
					'strong' => true,
4487
					'br'     => true,
4488
					'b'      => true,
4489
				)
4490
			);
4491
			?>
4492
			</h2>
4493
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4494
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4495
<?php	endif; ?>
4496
	</div>
4497
</div>
4498
			<?php
4499
		}
4500
4501
		if ( $this->message ) {
4502
			?>
4503
<div id="message" class="jetpack-message">
4504
	<div class="squeezer">
4505
		<h2>
4506
			<?php
4507
			echo wp_kses(
4508
				$this->message,
4509
				array(
4510
					'strong' => array(),
4511
					'a'      => array( 'href' => true ),
4512
					'br'     => true,
4513
				)
4514
			);
4515
			?>
4516
			</h2>
4517
	</div>
4518
</div>
4519
			<?php
4520
		}
4521
4522
		if ( $this->privacy_checks ) :
4523
			$module_names = $module_slugs = array();
4524
4525
			$privacy_checks = explode( ',', $this->privacy_checks );
4526
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4527
			foreach ( $privacy_checks as $module_slug ) {
4528
				$module = self::get_module( $module_slug );
4529
				if ( ! $module ) {
4530
					continue;
4531
				}
4532
4533
				$module_slugs[] = $module_slug;
4534
				$module_names[] = "<strong>{$module['name']}</strong>";
4535
			}
4536
4537
			$module_slugs = join( ',', $module_slugs );
4538
			?>
4539
<div id="message" class="jetpack-message jetpack-err">
4540
	<div class="squeezer">
4541
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4542
		<p>
4543
			<?php
4544
			echo wp_kses(
4545
				wptexturize(
4546
					wp_sprintf(
4547
						_nx(
4548
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4549
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4550
							count( $privacy_checks ),
4551
							'%l = list of Jetpack module/feature names',
4552
							'jetpack'
4553
						),
4554
						$module_names
4555
					)
4556
				),
4557
				array( 'strong' => true )
4558
			);
4559
4560
			echo "\n<br />\n";
4561
4562
			echo wp_kses(
4563
				sprintf(
4564
					_nx(
4565
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4566
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4567
						count( $privacy_checks ),
4568
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4569
						'jetpack'
4570
					),
4571
					wp_nonce_url(
4572
						self::admin_url(
4573
							array(
4574
								'page'   => 'jetpack',
4575
								'action' => 'deactivate',
4576
								'module' => urlencode( $module_slugs ),
4577
							)
4578
						),
4579
						"jetpack_deactivate-$module_slugs"
4580
					),
4581
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4582
				),
4583
				array(
4584
					'a' => array(
4585
						'href'  => true,
4586
						'title' => true,
4587
					),
4588
				)
4589
			);
4590
			?>
4591
		</p>
4592
	</div>
4593
</div>
4594
			<?php
4595
endif;
4596
	}
4597
4598
	/**
4599
	 * We can't always respond to a signed XML-RPC request with a
4600
	 * helpful error message. In some circumstances, doing so could
4601
	 * leak information.
4602
	 *
4603
	 * Instead, track that the error occurred via a Jetpack_Option,
4604
	 * and send that data back in the heartbeat.
4605
	 * All this does is increment a number, but it's enough to find
4606
	 * trends.
4607
	 *
4608
	 * @param WP_Error $xmlrpc_error The error produced during
4609
	 *                               signature validation.
4610
	 */
4611
	function track_xmlrpc_error( $xmlrpc_error ) {
4612
		$code = is_wp_error( $xmlrpc_error )
4613
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
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...
4614
			: 'should-not-happen';
4615
4616
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4617
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4618
			// No need to update the option if we already have
4619
			// this code stored.
4620
			return;
4621
		}
4622
		$xmlrpc_errors[ $code ] = true;
4623
4624
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
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...
4625
	}
4626
4627
	/**
4628
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4629
	 */
4630
	function stat( $group, $detail ) {
4631
		if ( ! isset( $this->stats[ $group ] ) ) {
4632
			$this->stats[ $group ] = array();
4633
		}
4634
		$this->stats[ $group ][] = $detail;
4635
	}
4636
4637
	/**
4638
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4639
	 */
4640
	function do_stats( $method = '' ) {
4641
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4642
			foreach ( $this->stats as $group => $stats ) {
4643
				if ( is_array( $stats ) && count( $stats ) ) {
4644
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4645
					if ( 'server_side' === $method ) {
4646
						self::do_server_side_stat( $args );
4647
					} else {
4648
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4649
					}
4650
				}
4651
				unset( $this->stats[ $group ] );
4652
			}
4653
		}
4654
	}
4655
4656
	/**
4657
	 * Runs stats code for a one-off, server-side.
4658
	 *
4659
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4660
	 *
4661
	 * @return bool If it worked.
4662
	 */
4663
	static function do_server_side_stat( $args ) {
4664
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4665
		if ( is_wp_error( $response ) ) {
4666
			return false;
4667
		}
4668
4669
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4670
			return false;
4671
		}
4672
4673
		return true;
4674
	}
4675
4676
	/**
4677
	 * Builds the stats url.
4678
	 *
4679
	 * @param $args array|string The arguments to append to the URL.
4680
	 *
4681
	 * @return string The URL to be pinged.
4682
	 */
4683
	static function build_stats_url( $args ) {
4684
		$defaults = array(
4685
			'v'    => 'wpcom2',
4686
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4687
		);
4688
		$args     = wp_parse_args( $args, $defaults );
0 ignored issues
show
$defaults is of type array<string,string,{"v"...ring","rand":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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