Completed
Push — fix/assign-issues-numbers ( e06ba9 )
by Jeremy
08:33
created

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

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

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

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

Loading history...
6907
	 */
6908
	public static function dns_prefetch( $urls = null ) {
6909
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6910
		if ( $urls ) {
6911
			Assets::add_resource_hint( $urls );
6912
		}
6913
	}
6914
6915
	public function wp_dashboard_setup() {
6916
		if ( self::is_active() ) {
6917
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6918
		}
6919
6920
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6921
			$jetpack_logo = new Jetpack_Logo();
6922
			$widget_title = sprintf(
6923
				wp_kses(
6924
					/* translators: Placeholder is a Jetpack logo. */
6925
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6926
					array( 'span' => array() )
6927
				),
6928
				$jetpack_logo->get_jp_emblem( true )
6929
			);
6930
6931
			wp_add_dashboard_widget(
6932
				'jetpack_summary_widget',
6933
				$widget_title,
6934
				array( __CLASS__, 'dashboard_widget' )
6935
			);
6936
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6937
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6938
6939
			// If we're inactive and not in development mode, sort our box to the top.
6940
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6941
				global $wp_meta_boxes;
6942
6943
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6944
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6945
6946
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6947
			}
6948
		}
6949
	}
6950
6951
	/**
6952
	 * @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...
6953
	 * @return mixed
6954
	 */
6955
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6956
		if ( ! is_array( $sorted ) ) {
6957
			return $sorted;
6958
		}
6959
6960
		foreach ( $sorted as $box_context => $ids ) {
6961
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6962
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6963
				continue;
6964
			}
6965
6966
			$ids_array = explode( ',', $ids );
6967
			$key       = array_search( 'dashboard_stats', $ids_array );
6968
6969
			if ( false !== $key ) {
6970
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6971
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6972
				$sorted[ $box_context ] = implode( ',', $ids_array );
6973
				// We've found it, stop searching, and just return.
6974
				break;
6975
			}
6976
		}
6977
6978
		return $sorted;
6979
	}
6980
6981
	public static function dashboard_widget() {
6982
		/**
6983
		 * Fires when the dashboard is loaded.
6984
		 *
6985
		 * @since 3.4.0
6986
		 */
6987
		do_action( 'jetpack_dashboard_widget' );
6988
	}
6989
6990
	public static function dashboard_widget_footer() {
6991
		?>
6992
		<footer>
6993
6994
		<div class="protect">
6995
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6996
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6997
				<p class="blocked-count">
6998
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6999
				</p>
7000
				<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>
7001
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
7002
				<a href="
7003
				<?php
7004
				echo esc_url(
7005
					wp_nonce_url(
7006
						self::admin_url(
7007
							array(
7008
								'action' => 'activate',
7009
								'module' => 'protect',
7010
							)
7011
						),
7012
						'jetpack_activate-protect'
7013
					)
7014
				);
7015
				?>
7016
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7017
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7018
				</a>
7019
			<?php else : ?>
7020
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7021
			<?php endif; ?>
7022
		</div>
7023
7024
		<div class="akismet">
7025
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7026
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7027
				<p class="blocked-count">
7028
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7029
				</p>
7030
				<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>
7031
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7032
				<a href="
7033
				<?php
7034
				echo esc_url(
7035
					wp_nonce_url(
7036
						add_query_arg(
7037
							array(
7038
								'action' => 'activate',
7039
								'plugin' => 'akismet/akismet.php',
7040
							),
7041
							admin_url( 'plugins.php' )
7042
						),
7043
						'activate-plugin_akismet/akismet.php'
7044
					)
7045
				);
7046
				?>
7047
							" class="button button-jetpack">
7048
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7049
				</a>
7050
			<?php else : ?>
7051
				<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>
7052
			<?php endif; ?>
7053
		</div>
7054
7055
		</footer>
7056
		<?php
7057
	}
7058
7059
	/*
7060
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7061
	 */
7062
	function jetpack_icon_user_connected( $columns ) {
7063
		$columns['user_jetpack'] = '';
7064
		return $columns;
7065
	}
7066
7067
	/*
7068
	 * Show Jetpack icon if the user is linked.
7069
	 */
7070
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7071
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7072
			$jetpack_logo = new Jetpack_Logo();
7073
			$emblem_html  = sprintf(
7074
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7075
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7076
				$jetpack_logo->get_jp_emblem()
7077
			);
7078
			return $emblem_html;
7079
		}
7080
7081
		return $val;
7082
	}
7083
7084
	/*
7085
	 * Style the Jetpack user column
7086
	 */
7087
	function jetpack_user_col_style() {
7088
		global $current_screen;
7089
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7090
			?>
7091
			<style>
7092
				.fixed .column-user_jetpack {
7093
					width: 21px;
7094
				}
7095
				.jp-emblem-user-admin svg {
7096
					width: 20px;
7097
					height: 20px;
7098
				}
7099
				.jp-emblem-user-admin path {
7100
					fill: #00BE28;
7101
				}
7102
			</style>
7103
			<?php
7104
		}
7105
	}
7106
7107
	/**
7108
	 * Checks if Akismet is active and working.
7109
	 *
7110
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7111
	 * that implied usage of methods present since more recent version.
7112
	 * See https://github.com/Automattic/jetpack/pull/9585
7113
	 *
7114
	 * @since  5.1.0
7115
	 *
7116
	 * @return bool True = Akismet available. False = Aksimet not available.
7117
	 */
7118
	public static function is_akismet_active() {
7119
		static $status = null;
7120
7121
		if ( ! is_null( $status ) ) {
7122
			return $status;
7123
		}
7124
7125
		// Check if a modern version of Akismet is active.
7126
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7127
			$status = false;
7128
			return $status;
7129
		}
7130
7131
		// Make sure there is a key known to Akismet at all before verifying key.
7132
		$akismet_key = Akismet::get_api_key();
7133
		if ( ! $akismet_key ) {
7134
			$status = false;
7135
			return $status;
7136
		}
7137
7138
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7139
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7140
7141
		// 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.
7142
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7143
		// We cache the result of the Akismet key verification for ten minutes.
7144
		if ( ! $akismet_key_state || $recheck ) {
7145
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7146
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7147
		}
7148
7149
		$status = 'valid' === $akismet_key_state;
7150
7151
		return $status;
7152
	}
7153
7154
	/**
7155
	 * @deprecated
7156
	 *
7157
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7158
	 */
7159
	public static function is_function_in_backtrace() {
7160
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7161
	}
7162
7163
	/**
7164
	 * Given a minified path, and a non-minified path, will return
7165
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7166
	 *
7167
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7168
	 * root Jetpack directory.
7169
	 *
7170
	 * @since 5.6.0
7171
	 *
7172
	 * @param string $min_path
7173
	 * @param string $non_min_path
7174
	 * @return string The URL to the file
7175
	 */
7176
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7177
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7178
	}
7179
7180
	/**
7181
	 * Checks for whether Jetpack Backup is enabled.
7182
	 * Will return true if the state of Backup is anything except "unavailable".
7183
	 *
7184
	 * @return bool|int|mixed
7185
	 */
7186
	public static function is_rewind_enabled() {
7187
		if ( ! self::is_active() ) {
7188
			return false;
7189
		}
7190
7191
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7192
		if ( false === $rewind_enabled ) {
7193
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7194
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7195
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7196
				&& ! empty( $rewind_data['state'] )
7197
				&& 'active' === $rewind_data['state'] )
7198
				? 1
7199
				: 0;
7200
7201
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7202
		}
7203
		return $rewind_enabled;
7204
	}
7205
7206
	/**
7207
	 * Return Calypso environment value; used for developing Jetpack and pairing
7208
	 * it with different Calypso enrionments, such as localhost.
7209
	 *
7210
	 * @since 7.4.0
7211
	 *
7212
	 * @return string Calypso environment
7213
	 */
7214
	public static function get_calypso_env() {
7215
		if ( isset( $_GET['calypso_env'] ) ) {
7216
			return sanitize_key( $_GET['calypso_env'] );
7217
		}
7218
7219
		if ( getenv( 'CALYPSO_ENV' ) ) {
7220
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7221
		}
7222
7223
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7224
			return sanitize_key( CALYPSO_ENV );
7225
		}
7226
7227
		return '';
7228
	}
7229
7230
	/**
7231
	 * Returns the hostname with protocol for Calypso.
7232
	 * Used for developing Jetpack with Calypso.
7233
	 *
7234
	 * @since 8.4.0
7235
	 *
7236
	 * @return string Calypso host.
7237
	 */
7238
	public static function get_calypso_host() {
7239
		$calypso_env = self::get_calypso_env();
7240
		switch ( $calypso_env ) {
7241
			case 'development':
7242
				return 'http://calypso.localhost:3000/';
7243
			case 'wpcalypso':
7244
				return 'https://wpcalypso.wordpress.com/';
7245
			case 'horizon':
7246
				return 'https://horizon.wordpress.com/';
7247
			default:
7248
				return 'https://wordpress.com/';
7249
		}
7250
	}
7251
7252
	/**
7253
	 * Checks whether or not TOS has been agreed upon.
7254
	 * Will return true if a user has clicked to register, or is already connected.
7255
	 */
7256
	public static function jetpack_tos_agreed() {
7257
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7258
7259
		$terms_of_service = new Terms_Of_Service();
7260
		return $terms_of_service->has_agreed();
7261
7262
	}
7263
7264
	/**
7265
	 * Handles activating default modules as well general cleanup for the new connection.
7266
	 *
7267
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7268
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7269
	 * @param boolean $send_state_messages          Whether to send state messages.
7270
	 * @return void
7271
	 */
7272
	public static function handle_post_authorization_actions(
7273
		$activate_sso = false,
7274
		$redirect_on_activation_error = false,
7275
		$send_state_messages = true
7276
	) {
7277
		$other_modules = $activate_sso
7278
			? array( 'sso' )
7279
			: array();
7280
7281
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7282
			self::delete_active_modules();
7283
7284
			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...
7285
		} else {
7286
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7287
		}
7288
7289
		// Since this is a fresh connection, be sure to clear out IDC options
7290
		Jetpack_IDC::clear_all_idc_options();
7291
7292
		if ( $send_state_messages ) {
7293
			self::state( 'message', 'authorized' );
7294
		}
7295
	}
7296
7297
	/**
7298
	 * Returns a boolean for whether backups UI should be displayed or not.
7299
	 *
7300
	 * @return bool Should backups UI be displayed?
7301
	 */
7302
	public static function show_backups_ui() {
7303
		/**
7304
		 * Whether UI for backups should be displayed.
7305
		 *
7306
		 * @since 6.5.0
7307
		 *
7308
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7309
		 */
7310
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7311
	}
7312
7313
	/*
7314
	 * Deprecated manage functions
7315
	 */
7316
	function prepare_manage_jetpack_notice() {
7317
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7318
	}
7319
	function manage_activate_screen() {
7320
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7321
	}
7322
	function admin_jetpack_manage_notice() {
7323
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7324
	}
7325
	function opt_out_jetpack_manage_url() {
7326
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7327
	}
7328
	function opt_in_jetpack_manage_url() {
7329
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7330
	}
7331
	function opt_in_jetpack_manage_notice() {
7332
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7333
	}
7334
	function can_display_jetpack_manage_notice() {
7335
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7336
	}
7337
7338
	/**
7339
	 * Clean leftoveruser meta.
7340
	 *
7341
	 * Delete Jetpack-related user meta when it is no longer needed.
7342
	 *
7343
	 * @since 7.3.0
7344
	 *
7345
	 * @param int $user_id User ID being updated.
7346
	 */
7347
	public static function user_meta_cleanup( $user_id ) {
7348
		$meta_keys = array(
7349
			// AtD removed from Jetpack 7.3
7350
			'AtD_options',
7351
			'AtD_check_when',
7352
			'AtD_guess_lang',
7353
			'AtD_ignored_phrases',
7354
		);
7355
7356
		foreach ( $meta_keys as $meta_key ) {
7357
			if ( get_user_meta( $user_id, $meta_key ) ) {
7358
				delete_user_meta( $user_id, $meta_key );
7359
			}
7360
		}
7361
	}
7362
7363
	/**
7364
	 * Checks if a Jetpack site is both active and not in development.
7365
	 *
7366
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7367
	 *
7368
	 * @return bool True if Jetpack is active and not in development.
7369
	 */
7370
	public static function is_active_and_not_development_mode() {
7371
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7372
			return false;
7373
		}
7374
		return true;
7375
	}
7376
7377
	/**
7378
	 * Returns the list of products that we have available for purchase.
7379
	 */
7380
	public static function get_products_for_purchase() {
7381
		$products = array();
7382
		if ( ! is_multisite() ) {
7383
			$products[] = array(
7384
				'key'               => 'backup',
7385
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7386
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7387
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7388
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7389
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7390
				'options'           => array(
7391
					array(
7392
						'type'        => 'daily',
7393
						'slug'        => 'jetpack-backup-daily',
7394
						'key'         => 'jetpack_backup_daily',
7395
						'name'        => __( 'Daily Backups', 'jetpack' ),
7396
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7397
					),
7398
					array(
7399
						'type'        => 'realtime',
7400
						'slug'        => 'jetpack-backup-realtime',
7401
						'key'         => 'jetpack_backup_realtime',
7402
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7403
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7404
					),
7405
				),
7406
				'default_option'    => 'realtime',
7407
				'show_promotion'    => true,
7408
				'discount_percent'  => 70,
7409
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7410
			);
7411
7412
			$products[] = array(
7413
				'key'               => 'scan',
7414
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7415
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7416
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7417
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7418
				'show_promotion'    => true,
7419
				'discount_percent'  => 30,
7420
				'options'           => array(
7421
					array(
7422
						'type'      => 'scan',
7423
						'slug'      => 'jetpack-scan',
7424
						'key'       => 'jetpack_scan',
7425
						'name'      => __( 'Daily Scan', 'jetpack' ),
7426
					),
7427
				),
7428
				'default_option'    => 'scan',
7429
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7430
			);
7431
		}
7432
7433
		$products[] = array(
7434
			'key'               => 'search',
7435
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7436
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7437
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7438
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7439
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7440
			'options'           => array(
7441
				array(
7442
					'type'      => 'search',
7443
					'slug'      => 'jetpack-search',
7444
					'key'       => 'jetpack_search',
7445
					'name'      => __( 'Search', 'jetpack' ),
7446
				),
7447
			),
7448
			'tears'             => array(),
7449
			'default_option'    => 'search',
7450
			'show_promotion'    => false,
7451
			'included_in_plans' => array( 'search-plan' ),
7452
		);
7453
7454
		return $products;
7455
	}
7456
}
7457