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