Completed
Push — try/package-button-block ( 9d9e85...92fe0a )
by
unknown
145:10 queued 137:02
created

Jetpack::__construct()   F

Complexity

Conditions 25
Paths 8

Size

Total Lines 264

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
nc 8
nop 0
dl 0
loc 264
rs 3.3333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

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

Loading history...
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
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
640
		add_filter( 'jetpack_gutenberg', function( $should_load ) {
641
			if ( ! Jetpack::is_active() && ! ( new Status() )->is_development_mode() ) {
642
				return false;
643
			}
644
			return $should_load;
645
		} );
646
		add_filter( 'jetpack_blocks_directory', function() {
647
			return JETPACK__PLUGIN_DIR . '_inc/blocks/';
648
		}, 0, 1 );
649
		add_action( 'jetpack_set_available_extensions', array( $this, 'set_available_extensions' ), 10, 2 );
650
		add_action( 'enqueue_block_editor_assets', function() {
651
			if ( ! Jetpack_Gutenberg::should_load() ) {
652
				return;
653
			}
654
655
			// Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
656
			if ( ! ( new Status() )->is_development_mode() && Jetpack::is_active() ) {
657
				wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
658
			}
659
660
661
			if ( ! Jetpack_Gutenberg::should_load() ) {
662
				return;
663
			}
664
665
			$rtl = is_rtl() ? '.rtl' : '';
666
			$blocks_dir       = Jetpack_Gutenberg::get_blocks_directory();
667
			$blocks_variation = Jetpack_Gutenberg::blocks_variation();
668
669
			if ( 'production' !== $blocks_variation ) {
670
				$blocks_env = '-' . esc_attr( $blocks_variation );
671
			} else {
672
				$blocks_env = '';
673
			}
674
675
			$editor_script = plugins_url( "{$blocks_dir}editor{$blocks_env}.js", JETPACK__PLUGIN_FILE );
676
			$editor_style  = plugins_url( "{$blocks_dir}editor{$blocks_env}{$rtl}.css", JETPACK__PLUGIN_FILE );
677
678
			$editor_deps_path = JETPACK__PLUGIN_DIR . $blocks_dir . "editor{$blocks_env}.asset.php";
679
			$editor_deps      = array( 'wp-polyfill' );
680
			if ( file_exists( $editor_deps_path ) ) {
681
				$asset_manifest = include $editor_deps_path;
682
				$editor_deps    = $asset_manifest['dependencies'];
683
			}
684
685
			$version = Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
686
				? filemtime( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
687
				: JETPACK__VERSION;
688
689
			if ( method_exists( 'Jetpack', 'build_raw_urls' ) ) {
690
				$site_fragment = Jetpack::build_raw_urls( home_url() );
691
			} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
692
				$site_fragment = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
693
			} else {
694
				$site_fragment = '';
695
			}
696
697
			wp_enqueue_script(
698
				'jetpack-blocks-editor',
699
				$editor_script,
700
				$editor_deps,
701
				$version,
702
				false
703
			);
704
705
			if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
706
				$user                      = wp_get_current_user();
707
				$user_data                 = array(
708
					'userid'   => $user->ID,
709
					'username' => $user->user_login,
710
				);
711
				$blog_id                   = get_current_blog_id();
712
				$is_current_user_connected = true;
713
			} else {
714
				$user_data                 = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
715
				$blog_id                   = Jetpack_Options::get_option( 'id', 0 );
716
				$is_current_user_connected = Jetpack::is_user_connected();
717
			}
718
719
			wp_localize_script(
720
				'jetpack-blocks-editor',
721
				'Jetpack_Editor_Initial_State',
722
				array(
723
					'available_blocks' => Jetpack_Gutenberg::get_availability(),
724
					'jetpack'          => array(
725
						'is_active'                 => Jetpack::is_active(),
726
						'is_current_user_connected' => $is_current_user_connected,
727
					),
728
					'siteFragment'     => $site_fragment,
729
					'tracksUserData'   => $user_data,
730
					'wpcomBlogId'      => $blog_id,
731
					'allowedMimeTypes' => wp_get_mime_types(),
732
				)
733
			);
734
735
			wp_set_script_translations( 'jetpack-blocks-editor', 'jetpack' );
736
737
			wp_enqueue_style( 'jetpack-blocks-editor', $editor_style, array(), $version );
738
		} );
739
		/**
740
		 * Some blocks do not depend on a specific module,
741
		 * and can consequently be loaded outside of the usual modules.
742
		 * We will look for such modules in the extensions/ directory.
743
		 *
744
		 * @since 7.1.0
745
		 *
746
		 * @deprecated 8.8.0 Blocks should be Jetpack modules and manage their own initialization.
747
		 */
748
		add_action( 'jetpack_after_extensions_init', function() {
749
			error_log("loading extensions after init");
750
			if ( Jetpack_Gutenberg::should_load() ) {
751
				/**
752
				 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
753
				 * If available, load them.
754
				 */
755
				foreach ( Jetpack_Gutenberg::$extensions as $extension ) {
756
					error_log("loading extension $extension");
757
					$extension_file_glob = glob( JETPACK__PLUGIN_DIR . 'extensions/*/' . $extension . '/' . $extension . '.php' );
758
					if ( ! empty( $extension_file_glob ) ) {
759
						error_log(json_encode($extension_file_glob));
760
						include_once $extension_file_glob[0];
761
					}
762
				}
763
			}
764
		} );
765
766
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
767
768
		// Unlink user before deleting the user from WP.com.
769
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
770
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
771
772
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
773
774
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
775
		add_action( 'login_init', array( $this, 'login_init' ) );
776
777
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
778
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
779
780
		add_action( 'admin_init', array( $this, 'admin_init' ) );
781
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
782
783
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
784
785
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
786
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
787
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
788
789
		// returns HTTPS support status
790
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
791
792
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
793
794
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
795
796
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
797
798
		/**
799
		 * These actions run checks to load additional files.
800
		 * They check for external files or plugins, so they need to run as late as possible.
801
		 */
802
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
803
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
804
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
805
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
806
807
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
808
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
809
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
810
811
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
812
813
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
814
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
815
816
		// A filter to control all just in time messages
817
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
818
819
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
820
821
		/*
822
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
823
		 * We should make sure to only do this for front end links.
824
		 */
825
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
826
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
827
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
828
829
			/*
830
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
831
			 * so they point moderation links on emails to Calypso.
832
			 */
833
			jetpack_require_lib( 'functions.wp-notify' );
834
		}
835
836
		add_action(
837
			'plugins_loaded',
838
			function() {
839
				if ( User_Agent_Info::is_mobile_app() ) {
840
					add_filter( 'get_edit_post_link', '__return_empty_string' );
841
				}
842
			}
843
		);
844
845
		// Update the Jetpack plan from API on heartbeats.
846
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
847
848
		/**
849
		 * This is the hack to concatenate all css files into one.
850
		 * For description and reasoning see the implode_frontend_css method.
851
		 *
852
		 * Super late priority so we catch all the registered styles.
853
		 */
854
		if ( ! is_admin() ) {
855
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
856
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
857
		}
858
859
		/**
860
		 * These are sync actions that we need to keep track of for jitms
861
		 */
862
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
863
864
		// Actually push the stats on shutdown.
865
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
866
			add_action( 'shutdown', array( $this, 'push_stats' ) );
867
		}
868
869
		// Actions for Manager::authorize().
870
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
871
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
872
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
873
874
		// Filters for the Manager::get_token() urls and request body.
875
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
876
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
877
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
878
	}
879
880
	/**
881
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
882
	 * Config object.
883
	 */
884
	public function configure() {
885
		$config = new Config();
886
887
		foreach (
888
			array(
889
				'sync',
890
				'tracking',
891
				'tos',
892
			)
893
			as $feature
894
		) {
895
			$config->ensure( $feature );
896
		}
897
898
		$config->ensure(
899
			'connection',
900
			array(
901
				'slug' => 'jetpack',
902
				'name' => 'Jetpack',
903
			)
904
		);
905
906
		if ( is_admin() ) {
907
			$config->ensure( 'jitm' );
908
		}
909
910
		if ( ! $this->connection_manager ) {
911
			$this->connection_manager = new Connection_Manager( 'jetpack' );
912
		}
913
914
		/*
915
		 * Load things that should only be in Network Admin.
916
		 *
917
		 * For now blow away everything else until a more full
918
		 * understanding of what is needed at the network level is
919
		 * available
920
		 */
921
		if ( is_multisite() ) {
922
			$network = Jetpack_Network::init();
923
			$network->set_connection( $this->connection_manager );
924
		}
925
926
		if ( $this->connection_manager->is_active() ) {
927
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
928
929
			Jetpack_Heartbeat::init();
930
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
931
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
932
				Jetpack_Search_Performance_Logger::init();
933
			}
934
		}
935
936
		// Initialize remote file upload request handlers.
937
		$this->add_remote_request_handlers();
938
939
		/*
940
		 * Enable enhanced handling of previewing sites in Calypso
941
		 */
942
		if ( self::is_active() ) {
943
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
944
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
945
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
946
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
947
		}
948
	}
949
950
	/**
951
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
952
	 * initialization code.
953
	 *
954
	 * @action plugins_loaded
955
	 */
956
	public function late_initialization() {
957
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
958
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
959
960
		Partner::init();
961
962
		/**
963
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
964
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
965
		 *
966
		 * @since 8.1.0
967
		 *
968
		 * @param Jetpack $jetpack the main plugin class object.
969
		 */
970
		do_action( 'jetpack_loaded', $this );
971
972
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
973
	}
974
975
	/**
976
	 * Sets up the XMLRPC request handlers.
977
	 *
978
	 * @deprecated since 7.7.0
979
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
980
	 *
981
	 * @param array                 $request_params Incoming request parameters.
982
	 * @param Boolean               $is_active      Whether the connection is currently active.
983
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
984
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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

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

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

Loading history...
985
	 */
986 View Code Duplication
	public function setup_xmlrpc_handlers(
987
		$request_params,
988
		$is_active,
989
		$is_signed,
990
		Jetpack_XMLRPC_Server $xmlrpc_server = null
991
	) {
992
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
993
994
		if ( ! $this->connection_manager ) {
995
			$this->connection_manager = new Connection_Manager();
996
		}
997
998
		return $this->connection_manager->setup_xmlrpc_handlers(
999
			$request_params,
1000
			$is_active,
1001
			$is_signed,
1002
			$xmlrpc_server
1003
		);
1004
	}
1005
1006
	/**
1007
	 * Used to set the list of extensions for the current environment. Extracted from class.jetpack-gutenberg.php
1008
	 */
1009
	public function set_available_extensions( $list, $variation ) {
1010
		$preset_file = Jetpack_Gutenberg::get_blocks_directory() . 'index.json';
1011
		if ( file_exists( $preset_file ) ) {
1012
			$presets = json_decode(
1013
				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
1014
				file_get_contents( $preset_file ), true
1015
			);
1016
			if ( ! empty( $presets ) && isset( $presets[$variation] ) && is_array( $presets[$variation] ) ) {
1017
				$list = array_merge( $list, $presets[$variation] );
1018
			}
1019
		}
1020
		return $list;
1021
	}
1022
1023
	/**
1024
	 * Initialize REST API registration connector.
1025
	 *
1026
	 * @deprecated since 7.7.0
1027
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
1028
	 */
1029 View Code Duplication
	public function initialize_rest_api_registration_connector() {
1030
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
1031
1032
		if ( ! $this->connection_manager ) {
1033
			$this->connection_manager = new Connection_Manager();
1034
		}
1035
1036
		$this->connection_manager->initialize_rest_api_registration_connector();
1037
	}
1038
1039
	/**
1040
	 * This is ported over from the manage module, which has been deprecated and baked in here.
1041
	 *
1042
	 * @param $domains
1043
	 */
1044
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
1045
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
1046
	}
1047
1048
	/**
1049
	 * Return $domains, with 'wordpress.com' appended.
1050
	 * This is ported over from the manage module, which has been deprecated and baked in here.
1051
	 *
1052
	 * @param $domains
1053
	 * @return array
1054
	 */
1055
	function allow_wpcom_domain( $domains ) {
1056
		if ( empty( $domains ) ) {
1057
			$domains = array();
1058
		}
1059
		$domains[] = 'wordpress.com';
1060
		return array_unique( $domains );
1061
	}
1062
1063
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1064
		$post = get_post( $post_id );
1065
1066
		if ( empty( $post ) ) {
1067
			return $default_url;
1068
		}
1069
1070
		$post_type = $post->post_type;
1071
1072
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1073
		// https://en.support.wordpress.com/custom-post-types/
1074
		$allowed_post_types = array(
1075
			'post',
1076
			'page',
1077
			'jetpack-portfolio',
1078
			'jetpack-testimonial',
1079
		);
1080
1081
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1082
			return $default_url;
1083
		}
1084
1085
		return esc_url(
1086
			Redirect::get_url(
1087
				'calypso-edit-' . $post_type,
1088
				array(
1089
					'path' => $post_id,
1090
				)
1091
			)
1092
		);
1093
	}
1094
1095
	function point_edit_comment_links_to_calypso( $url ) {
1096
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1097
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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

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

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

Loading history...
1098
1099
		return esc_url(
1100
			Redirect::get_url(
1101
				'calypso-edit-comment',
1102
				array(
1103
					'path' => $query_args['amp;c'],
1104
				)
1105
			)
1106
		);
1107
1108
	}
1109
1110
	function jetpack_track_last_sync_callback( $params ) {
1111
		/**
1112
		 * Filter to turn off jitm caching
1113
		 *
1114
		 * @since 5.4.0
1115
		 *
1116
		 * @param bool false Whether to cache just in time messages
1117
		 */
1118
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1119
			return $params;
1120
		}
1121
1122
		if ( is_array( $params ) && isset( $params[0] ) ) {
1123
			$option = $params[0];
1124
			if ( 'active_plugins' === $option ) {
1125
				// use the cache if we can, but not terribly important if it gets evicted
1126
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1127
			}
1128
		}
1129
1130
		return $params;
1131
	}
1132
1133
	function jetpack_connection_banner_callback() {
1134
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1135
1136
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1137
		if (
1138
			isset( $_REQUEST['dismissBanner'] ) &&
1139
			! Jetpack_Connection_Banner::force_display()
1140
		) {
1141
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1142
			wp_send_json_success();
1143
		}
1144
1145
		wp_die();
1146
	}
1147
1148
	/**
1149
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1150
	 * Only used in our alternate XML-RPC endpoint, where we want to
1151
	 * ensure that Core and other plugins' methods are not exposed.
1152
	 *
1153
	 * @deprecated since 7.7.0
1154
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1155
	 *
1156
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1157
	 * @return array Filtered $methods
1158
	 */
1159 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1160
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1161
1162
		if ( ! $this->connection_manager ) {
1163
			$this->connection_manager = new Connection_Manager();
1164
		}
1165
1166
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1167
	}
1168
1169
	/**
1170
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1171
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1172
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1173
	 * which is accessible via a different URI. Most of the below is copied directly
1174
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1175
	 *
1176
	 * @deprecated since 7.7.0
1177
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1178
	 */
1179 View Code Duplication
	public function alternate_xmlrpc() {
1180
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1181
1182
		if ( ! $this->connection_manager ) {
1183
			$this->connection_manager = new Connection_Manager();
1184
		}
1185
1186
		$this->connection_manager->alternate_xmlrpc();
1187
	}
1188
1189
	/**
1190
	 * The callback for the JITM ajax requests.
1191
	 *
1192
	 * @deprecated since 7.9.0
1193
	 */
1194
	function jetpack_jitm_ajax_callback() {
1195
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1196
	}
1197
1198
	/**
1199
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1200
	 */
1201
	function push_stats() {
1202
		if ( ! empty( $this->stats ) ) {
1203
			$this->do_stats( 'server_side' );
1204
		}
1205
	}
1206
1207
	/**
1208
	 * Sets the Jetpack custom capabilities.
1209
	 *
1210
	 * @param string[] $caps    Array of the user's capabilities.
1211
	 * @param string   $cap     Capability name.
1212
	 * @param int      $user_id The user ID.
1213
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1214
	 */
1215
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1216
		$is_development_mode = ( new Status() )->is_development_mode();
1217
		switch ( $cap ) {
1218
			case 'jetpack_manage_modules':
1219
			case 'jetpack_activate_modules':
1220
			case 'jetpack_deactivate_modules':
1221
				$caps = array( 'manage_options' );
1222
				break;
1223
			case 'jetpack_configure_modules':
1224
				$caps = array( 'manage_options' );
1225
				break;
1226
			case 'jetpack_manage_autoupdates':
1227
				$caps = array(
1228
					'manage_options',
1229
					'update_plugins',
1230
				);
1231
				break;
1232
			case 'jetpack_network_admin_page':
1233
			case 'jetpack_network_settings_page':
1234
				$caps = array( 'manage_network_plugins' );
1235
				break;
1236
			case 'jetpack_network_sites_page':
1237
				$caps = array( 'manage_sites' );
1238
				break;
1239
			case 'jetpack_admin_page':
1240
				if ( $is_development_mode ) {
1241
					$caps = array( 'manage_options' );
1242
					break;
1243
				} else {
1244
					$caps = array( 'read' );
1245
				}
1246
				break;
1247
		}
1248
		return $caps;
1249
	}
1250
1251
	/**
1252
	 * Require a Jetpack authentication.
1253
	 *
1254
	 * @deprecated since 7.7.0
1255
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1256
	 */
1257 View Code Duplication
	public function require_jetpack_authentication() {
1258
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1259
1260
		if ( ! $this->connection_manager ) {
1261
			$this->connection_manager = new Connection_Manager();
1262
		}
1263
1264
		$this->connection_manager->require_jetpack_authentication();
1265
	}
1266
1267
	/**
1268
	 * Load language files
1269
	 *
1270
	 * @action plugins_loaded
1271
	 */
1272
	public static function plugin_textdomain() {
1273
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1274
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1275
	}
1276
1277
	/**
1278
	 * Register assets for use in various modules and the Jetpack admin page.
1279
	 *
1280
	 * @uses wp_script_is, wp_register_script, plugins_url
1281
	 * @action wp_loaded
1282
	 * @return null
1283
	 */
1284
	public function register_assets() {
1285 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1286
			wp_register_script(
1287
				'jetpack-gallery-settings',
1288
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1289
				array( 'media-views' ),
1290
				'20121225'
1291
			);
1292
		}
1293
1294
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1295
			wp_register_script(
1296
				'jetpack-twitter-timeline',
1297
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1298
				array( 'jquery' ),
1299
				'4.0.0',
1300
				true
1301
			);
1302
		}
1303
1304
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1305
			wp_register_script(
1306
				'jetpack-facebook-embed',
1307
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1308
				array(),
1309
				null,
1310
				true
1311
			);
1312
1313
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1314
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1315
			if ( ! is_numeric( $fb_app_id ) ) {
1316
				$fb_app_id = '';
1317
			}
1318
			wp_localize_script(
1319
				'jetpack-facebook-embed',
1320
				'jpfbembed',
1321
				array(
1322
					'appid'  => $fb_app_id,
1323
					'locale' => $this->get_locale(),
1324
				)
1325
			);
1326
		}
1327
1328
		/**
1329
		 * As jetpack_register_genericons is by default fired off a hook,
1330
		 * the hook may have already fired by this point.
1331
		 * So, let's just trigger it manually.
1332
		 */
1333
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1334
		jetpack_register_genericons();
1335
1336
		/**
1337
		 * Register the social logos
1338
		 */
1339
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1340
		jetpack_register_social_logos();
1341
1342 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1343
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1344
		}
1345
	}
1346
1347
	/**
1348
	 * Guess locale from language code.
1349
	 *
1350
	 * @param string $lang Language code.
1351
	 * @return string|bool
1352
	 */
1353 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1354
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1355
			return 'en_US';
1356
		}
1357
1358
		if ( ! class_exists( 'GP_Locales' ) ) {
1359
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1360
				return false;
1361
			}
1362
1363
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1364
		}
1365
1366
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1367
			// WP.com: get_locale() returns 'it'
1368
			$locale = GP_Locales::by_slug( $lang );
1369
		} else {
1370
			// Jetpack: get_locale() returns 'it_IT';
1371
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1372
		}
1373
1374
		if ( ! $locale ) {
1375
			return false;
1376
		}
1377
1378
		if ( empty( $locale->facebook_locale ) ) {
1379
			if ( empty( $locale->wp_locale ) ) {
1380
				return false;
1381
			} else {
1382
				// Facebook SDK is smart enough to fall back to en_US if a
1383
				// locale isn't supported. Since supported Facebook locales
1384
				// can fall out of sync, we'll attempt to use the known
1385
				// wp_locale value and rely on said fallback.
1386
				return $locale->wp_locale;
1387
			}
1388
		}
1389
1390
		return $locale->facebook_locale;
1391
	}
1392
1393
	/**
1394
	 * Get the locale.
1395
	 *
1396
	 * @return string|bool
1397
	 */
1398
	function get_locale() {
1399
		$locale = $this->guess_locale_from_lang( get_locale() );
1400
1401
		if ( ! $locale ) {
1402
			$locale = 'en_US';
1403
		}
1404
1405
		return $locale;
1406
	}
1407
1408
	/**
1409
	 * Return the network_site_url so that .com knows what network this site is a part of.
1410
	 *
1411
	 * @param  bool $option
1412
	 * @return string
1413
	 */
1414
	public function jetpack_main_network_site_option( $option ) {
1415
		return network_site_url();
1416
	}
1417
	/**
1418
	 * Network Name.
1419
	 */
1420
	static function network_name( $option = null ) {
1421
		global $current_site;
1422
		return $current_site->site_name;
1423
	}
1424
	/**
1425
	 * Does the network allow new user and site registrations.
1426
	 *
1427
	 * @return string
1428
	 */
1429
	static function network_allow_new_registrations( $option = null ) {
1430
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1431
	}
1432
	/**
1433
	 * Does the network allow admins to add new users.
1434
	 *
1435
	 * @return boolian
1436
	 */
1437
	static function network_add_new_users( $option = null ) {
1438
		return (bool) get_site_option( 'add_new_users' );
1439
	}
1440
	/**
1441
	 * File upload psace left per site in MB.
1442
	 *  -1 means NO LIMIT.
1443
	 *
1444
	 * @return number
1445
	 */
1446
	static function network_site_upload_space( $option = null ) {
1447
		// value in MB
1448
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1449
	}
1450
1451
	/**
1452
	 * Network allowed file types.
1453
	 *
1454
	 * @return string
1455
	 */
1456
	static function network_upload_file_types( $option = null ) {
1457
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1458
	}
1459
1460
	/**
1461
	 * Maximum file upload size set by the network.
1462
	 *
1463
	 * @return number
1464
	 */
1465
	static function network_max_upload_file_size( $option = null ) {
1466
		// value in KB
1467
		return get_site_option( 'fileupload_maxk', 300 );
1468
	}
1469
1470
	/**
1471
	 * Lets us know if a site allows admins to manage the network.
1472
	 *
1473
	 * @return array
1474
	 */
1475
	static function network_enable_administration_menus( $option = null ) {
1476
		return get_site_option( 'menu_items' );
1477
	}
1478
1479
	/**
1480
	 * If a user has been promoted to or demoted from admin, we need to clear the
1481
	 * jetpack_other_linked_admins transient.
1482
	 *
1483
	 * @since 4.3.2
1484
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1485
	 *
1486
	 * @param int    $user_id   The user ID whose role changed.
1487
	 * @param string $role      The new role.
1488
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

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

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

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

Loading history...
1489
	 */
1490
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1491
		if ( 'administrator' == $role
1492
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1493
			|| is_null( $old_roles )
1494
		) {
1495
			delete_transient( 'jetpack_other_linked_admins' );
1496
		}
1497
	}
1498
1499
	/**
1500
	 * Checks to see if there are any other users available to become primary
1501
	 * Users must both:
1502
	 * - Be linked to wpcom
1503
	 * - Be an admin
1504
	 *
1505
	 * @return mixed False if no other users are linked, Int if there are.
1506
	 */
1507
	static function get_other_linked_admins() {
1508
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1509
1510
		if ( false === $other_linked_users ) {
1511
			$admins = get_users( array( 'role' => 'administrator' ) );
1512
			if ( count( $admins ) > 1 ) {
1513
				$available = array();
1514
				foreach ( $admins as $admin ) {
1515
					if ( self::is_user_connected( $admin->ID ) ) {
1516
						$available[] = $admin->ID;
1517
					}
1518
				}
1519
1520
				$count_connected_admins = count( $available );
1521
				if ( count( $available ) > 1 ) {
1522
					$other_linked_users = $count_connected_admins;
1523
				} else {
1524
					$other_linked_users = 0;
1525
				}
1526
			} else {
1527
				$other_linked_users = 0;
1528
			}
1529
1530
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1531
		}
1532
1533
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1534
	}
1535
1536
	/**
1537
	 * Return whether we are dealing with a multi network setup or not.
1538
	 * The reason we are type casting this is because we want to avoid the situation where
1539
	 * the result is false since when is_main_network_option return false it cases
1540
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1541
	 * database which could be set to anything as opposed to what this function returns.
1542
	 *
1543
	 * @param  bool $option
1544
	 *
1545
	 * @return boolean
1546
	 */
1547
	public function is_main_network_option( $option ) {
1548
		// return '1' or ''
1549
		return (string) (bool) self::is_multi_network();
1550
	}
1551
1552
	/**
1553
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1554
	 *
1555
	 * @param  string $option
1556
	 * @return boolean
1557
	 */
1558
	public function is_multisite( $option ) {
1559
		return (string) (bool) is_multisite();
1560
	}
1561
1562
	/**
1563
	 * Implemented since there is no core is multi network function
1564
	 * Right now there is no way to tell if we which network is the dominant network on the system
1565
	 *
1566
	 * @since  3.3
1567
	 * @return boolean
1568
	 */
1569 View Code Duplication
	public static function is_multi_network() {
1570
		global  $wpdb;
1571
1572
		// if we don't have a multi site setup no need to do any more
1573
		if ( ! is_multisite() ) {
1574
			return false;
1575
		}
1576
1577
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1578
		if ( $num_sites > 1 ) {
1579
			return true;
1580
		} else {
1581
			return false;
1582
		}
1583
	}
1584
1585
	/**
1586
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1587
	 *
1588
	 * @return null
1589
	 */
1590
	function update_jetpack_main_network_site_option() {
1591
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1592
	}
1593
	/**
1594
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1595
	 */
1596
	function update_jetpack_network_settings() {
1597
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1598
		// Only sync this info for the main network site.
1599
	}
1600
1601
	/**
1602
	 * Get back if the current site is single user site.
1603
	 *
1604
	 * @return bool
1605
	 */
1606 View Code Duplication
	public static function is_single_user_site() {
1607
		global $wpdb;
1608
1609
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1610
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1611
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1612
		}
1613
		return 1 === (int) $some_users;
1614
	}
1615
1616
	/**
1617
	 * Returns true if the site has file write access false otherwise.
1618
	 *
1619
	 * @return string ( '1' | '0' )
1620
	 **/
1621
	public static function file_system_write_access() {
1622
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1623
			require_once ABSPATH . 'wp-admin/includes/file.php';
1624
		}
1625
1626
		require_once ABSPATH . 'wp-admin/includes/template.php';
1627
1628
		$filesystem_method = get_filesystem_method();
1629
		if ( $filesystem_method === 'direct' ) {
1630
			return 1;
1631
		}
1632
1633
		ob_start();
1634
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1635
		ob_end_clean();
1636
		if ( $filesystem_credentials_are_stored ) {
1637
			return 1;
1638
		}
1639
		return 0;
1640
	}
1641
1642
	/**
1643
	 * Finds out if a site is using a version control system.
1644
	 *
1645
	 * @return string ( '1' | '0' )
1646
	 **/
1647
	public static function is_version_controlled() {
1648
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1649
		return (string) (int) Functions::is_version_controlled();
1650
	}
1651
1652
	/**
1653
	 * Determines whether the current theme supports featured images or not.
1654
	 *
1655
	 * @return string ( '1' | '0' )
1656
	 */
1657
	public static function featured_images_enabled() {
1658
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1659
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1660
	}
1661
1662
	/**
1663
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1664
	 *
1665
	 * @deprecated 4.7 use get_avatar_url instead.
1666
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1667
	 * @param int               $size Size of the avatar image
1668
	 * @param string            $default URL to a default image to use if no avatar is available
1669
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1670
	 *
1671
	 * @return array
1672
	 */
1673
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1674
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1675
		return get_avatar_url(
1676
			$id_or_email,
1677
			array(
1678
				'size'          => $size,
1679
				'default'       => $default,
1680
				'force_default' => $force_display,
1681
			)
1682
		);
1683
	}
1684
1685
	/**
1686
	 * jetpack_updates is saved in the following schema:
1687
	 *
1688
	 * array (
1689
	 *      'plugins'                       => (int) Number of plugin updates available.
1690
	 *      'themes'                        => (int) Number of theme updates available.
1691
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1692
	 *      'translations'                  => (int) Number of translation updates available.
1693
	 *      'total'                         => (int) Total of all available updates.
1694
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1695
	 * )
1696
	 *
1697
	 * @return array
1698
	 */
1699
	public static function get_updates() {
1700
		$update_data = wp_get_update_data();
1701
1702
		// Stores the individual update counts as well as the total count.
1703
		if ( isset( $update_data['counts'] ) ) {
1704
			$updates = $update_data['counts'];
1705
		}
1706
1707
		// If we need to update WordPress core, let's find the latest version number.
1708 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1709
			$cur = get_preferred_from_update_core();
1710
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1711
				$updates['wp_update_version'] = $cur->current;
1712
			}
1713
		}
1714
		return isset( $updates ) ? $updates : array();
1715
	}
1716
1717
	public static function get_update_details() {
1718
		$update_details = array(
1719
			'update_core'    => get_site_transient( 'update_core' ),
1720
			'update_plugins' => get_site_transient( 'update_plugins' ),
1721
			'update_themes'  => get_site_transient( 'update_themes' ),
1722
		);
1723
		return $update_details;
1724
	}
1725
1726
	public static function refresh_update_data() {
1727
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1728
1729
	}
1730
1731
	public static function refresh_theme_data() {
1732
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1733
	}
1734
1735
	/**
1736
	 * Is Jetpack active?
1737
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1738
	 *
1739
	 * @return bool
1740
	 */
1741
	public static function is_active() {
1742
		return self::connection()->is_active();
1743
	}
1744
1745
	/**
1746
	 * Make an API call to WordPress.com for plan status
1747
	 *
1748
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1749
	 *
1750
	 * @return bool True if plan is updated, false if no update
1751
	 */
1752
	public static function refresh_active_plan_from_wpcom() {
1753
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1754
		return Jetpack_Plan::refresh_from_wpcom();
1755
	}
1756
1757
	/**
1758
	 * Get the plan that this Jetpack site is currently using
1759
	 *
1760
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1761
	 * @return array Active Jetpack plan details.
1762
	 */
1763
	public static function get_active_plan() {
1764
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1765
		return Jetpack_Plan::get();
1766
	}
1767
1768
	/**
1769
	 * Determine whether the active plan supports a particular feature
1770
	 *
1771
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1772
	 * @return bool True if plan supports feature, false if not.
1773
	 */
1774
	public static function active_plan_supports( $feature ) {
1775
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1776
		return Jetpack_Plan::supports( $feature );
1777
	}
1778
1779
	/**
1780
	 * Deprecated: Is Jetpack in development (offline) mode?
1781
	 *
1782
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1783
	 * and themes still use it, and we do not want to flood them with notices.
1784
	 *
1785
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1786
	 *
1787
	 * @deprecated since 8.0.
1788
	 */
1789
	public static function is_development_mode() {
1790
		return ( new Status() )->is_development_mode();
1791
	}
1792
1793
	/**
1794
	 * Whether the site is currently onboarding or not.
1795
	 * A site is considered as being onboarded if it currently has an onboarding token.
1796
	 *
1797
	 * @since 5.8
1798
	 *
1799
	 * @access public
1800
	 * @static
1801
	 *
1802
	 * @return bool True if the site is currently onboarding, false otherwise
1803
	 */
1804
	public static function is_onboarding() {
1805
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1806
	}
1807
1808
	/**
1809
	 * Determines reason for Jetpack development mode.
1810
	 */
1811
	public static function development_mode_trigger_text() {
1812
		if ( ! ( new Status() )->is_development_mode() ) {
1813
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1814
		}
1815
1816
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1817
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1818
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1819
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1820
		} else {
1821
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1822
		}
1823
1824
		return $notice;
1825
1826
	}
1827
	/**
1828
	 * Get Jetpack development mode notice text and notice class.
1829
	 *
1830
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1831
	 */
1832
	public static function show_development_mode_notice() {
1833 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1834
			$notice = sprintf(
1835
				/* translators: %s is a URL */
1836
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1837
				Redirect::get_url( 'jetpack-support-development-mode' )
1838
			);
1839
1840
			$notice .= ' ' . self::development_mode_trigger_text();
1841
1842
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1843
		}
1844
1845
		// Throw up a notice if using a development version and as for feedback.
1846
		if ( self::is_development_version() ) {
1847
			/* translators: %s is a URL */
1848
			$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' ) );
1849
1850
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1851
		}
1852
		// Throw up a notice if using staging mode
1853 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1854
			/* translators: %s is a URL */
1855
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1856
1857
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1858
		}
1859
	}
1860
1861
	/**
1862
	 * Whether Jetpack's version maps to a public release, or a development version.
1863
	 */
1864
	public static function is_development_version() {
1865
		/**
1866
		 * Allows filtering whether this is a development version of Jetpack.
1867
		 *
1868
		 * This filter is especially useful for tests.
1869
		 *
1870
		 * @since 4.3.0
1871
		 *
1872
		 * @param bool $development_version Is this a develoment version of Jetpack?
1873
		 */
1874
		return (bool) apply_filters(
1875
			'jetpack_development_version',
1876
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1877
		);
1878
	}
1879
1880
	/**
1881
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1882
	 */
1883
	public static function is_user_connected( $user_id = false ) {
1884
		return self::connection()->is_user_connected( $user_id );
1885
	}
1886
1887
	/**
1888
	 * Get the wpcom user data of the current|specified connected user.
1889
	 */
1890 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1891
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1892
		if ( ! $user_id ) {
1893
			$user_id = get_current_user_id();
1894
		}
1895
1896
		$transient_key = "jetpack_connected_user_data_$user_id";
1897
1898
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1899
			return $cached_user_data;
1900
		}
1901
1902
		$xml = new Jetpack_IXR_Client(
1903
			array(
1904
				'user_id' => $user_id,
1905
			)
1906
		);
1907
		$xml->query( 'wpcom.getUser' );
1908
		if ( ! $xml->isError() ) {
1909
			$user_data = $xml->getResponse();
1910
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1911
			return $user_data;
1912
		}
1913
1914
		return false;
1915
	}
1916
1917
	/**
1918
	 * Get the wpcom email of the current|specified connected user.
1919
	 */
1920
	public static function get_connected_user_email( $user_id = null ) {
1921
		if ( ! $user_id ) {
1922
			$user_id = get_current_user_id();
1923
		}
1924
1925
		$xml = new Jetpack_IXR_Client(
1926
			array(
1927
				'user_id' => $user_id,
1928
			)
1929
		);
1930
		$xml->query( 'wpcom.getUserEmail' );
1931
		if ( ! $xml->isError() ) {
1932
			return $xml->getResponse();
1933
		}
1934
		return false;
1935
	}
1936
1937
	/**
1938
	 * Get the wpcom email of the master user.
1939
	 */
1940
	public static function get_master_user_email() {
1941
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1942
		if ( $master_user_id ) {
1943
			return self::get_connected_user_email( $master_user_id );
1944
		}
1945
		return '';
1946
	}
1947
1948
	/**
1949
	 * Whether the current user is the connection owner.
1950
	 *
1951
	 * @deprecated since 7.7
1952
	 *
1953
	 * @return bool Whether the current user is the connection owner.
1954
	 */
1955
	public function current_user_is_connection_owner() {
1956
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1957
		return self::connection()->is_connection_owner();
1958
	}
1959
1960
	/**
1961
	 * Gets current user IP address.
1962
	 *
1963
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1964
	 *
1965
	 * @return string                  Current user IP address.
1966
	 */
1967
	public static function current_user_ip( $check_all_headers = false ) {
1968
		if ( $check_all_headers ) {
1969
			foreach ( array(
1970
				'HTTP_CF_CONNECTING_IP',
1971
				'HTTP_CLIENT_IP',
1972
				'HTTP_X_FORWARDED_FOR',
1973
				'HTTP_X_FORWARDED',
1974
				'HTTP_X_CLUSTER_CLIENT_IP',
1975
				'HTTP_FORWARDED_FOR',
1976
				'HTTP_FORWARDED',
1977
				'HTTP_VIA',
1978
			) as $key ) {
1979
				if ( ! empty( $_SERVER[ $key ] ) ) {
1980
					return $_SERVER[ $key ];
1981
				}
1982
			}
1983
		}
1984
1985
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1986
	}
1987
1988
	/**
1989
	 * Synchronize connected user role changes
1990
	 */
1991
	function user_role_change( $user_id ) {
1992
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1993
		Users::user_role_change( $user_id );
1994
	}
1995
1996
	/**
1997
	 * Loads the currently active modules.
1998
	 */
1999
	public static function load_modules() {
2000
		$is_development_mode = ( new Status() )->is_development_mode();
2001
		if (
2002
			! self::is_active()
2003
			&& ! $is_development_mode
2004
			&& ! self::is_onboarding()
2005
			&& (
2006
				! is_multisite()
2007
				|| ! get_site_option( 'jetpack_protect_active' )
2008
			)
2009
		) {
2010
			return;
2011
		}
2012
2013
		$version = Jetpack_Options::get_option( 'version' );
2014 View Code Duplication
		if ( ! $version ) {
2015
			$version = $old_version = JETPACK__VERSION . ':' . time();
2016
			/** This action is documented in class.jetpack.php */
2017
			do_action( 'updating_jetpack_version', $version, false );
2018
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2019
		}
2020
		list( $version ) = explode( ':', $version );
2021
2022
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
2023
2024
		$modules_data = array();
2025
2026
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
2027
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
2028
			$updated_modules = array();
2029
			foreach ( $modules as $module ) {
2030
				$modules_data[ $module ] = self::get_module( $module );
2031
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
2032
					continue;
2033
				}
2034
2035
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
2036
					continue;
2037
				}
2038
2039
				$updated_modules[] = $module;
2040
			}
2041
2042
			$modules = array_diff( $modules, $updated_modules );
2043
		}
2044
2045
		foreach ( $modules as $index => $module ) {
2046
			// If we're in dev mode, disable modules requiring a connection
2047
			if ( $is_development_mode ) {
2048
				// Prime the pump if we need to
2049
				if ( empty( $modules_data[ $module ] ) ) {
2050
					$modules_data[ $module ] = self::get_module( $module );
2051
				}
2052
				// If the module requires a connection, but we're in local mode, don't include it.
2053
				if ( $modules_data[ $module ]['requires_connection'] ) {
2054
					continue;
2055
				}
2056
			}
2057
2058
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
2059
				continue;
2060
			}
2061
2062
			if ( ! include_once self::get_module_path( $module ) ) {
2063
				unset( $modules[ $index ] );
2064
				self::update_active_modules( array_values( $modules ) );
2065
				continue;
2066
			}
2067
2068
			/**
2069
			 * Fires when a specific module is loaded.
2070
			 * The dynamic part of the hook, $module, is the module slug.
2071
			 *
2072
			 * @since 1.1.0
2073
			 */
2074
			do_action( 'jetpack_module_loaded_' . $module );
2075
		}
2076
2077
		/**
2078
		 * Fires when all the modules are loaded.
2079
		 *
2080
		 * @since 1.1.0
2081
		 */
2082
		do_action( 'jetpack_modules_loaded' );
2083
2084
		// 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.
2085
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2086
	}
2087
2088
	/**
2089
	 * Check if Jetpack's REST API compat file should be included
2090
	 *
2091
	 * @action plugins_loaded
2092
	 * @return null
2093
	 */
2094
	public function check_rest_api_compat() {
2095
		/**
2096
		 * Filters the list of REST API compat files to be included.
2097
		 *
2098
		 * @since 2.2.5
2099
		 *
2100
		 * @param array $args Array of REST API compat files to include.
2101
		 */
2102
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2103
2104
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2105
			require_once $_jetpack_rest_api_compat_include;
2106
		}
2107
	}
2108
2109
	/**
2110
	 * Gets all plugins currently active in values, regardless of whether they're
2111
	 * traditionally activated or network activated.
2112
	 *
2113
	 * @todo Store the result in core's object cache maybe?
2114
	 */
2115
	public static function get_active_plugins() {
2116
		$active_plugins = (array) get_option( 'active_plugins', array() );
2117
2118
		if ( is_multisite() ) {
2119
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2120
			// whereas active_plugins stores them in the values.
2121
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2122
			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...
2123
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2124
			}
2125
		}
2126
2127
		sort( $active_plugins );
2128
2129
		return array_unique( $active_plugins );
2130
	}
2131
2132
	/**
2133
	 * Gets and parses additional plugin data to send with the heartbeat data
2134
	 *
2135
	 * @since 3.8.1
2136
	 *
2137
	 * @return array Array of plugin data
2138
	 */
2139
	public static function get_parsed_plugin_data() {
2140
		if ( ! function_exists( 'get_plugins' ) ) {
2141
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2142
		}
2143
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2144
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2145
		$active_plugins = self::get_active_plugins();
2146
2147
		$plugins = array();
2148
		foreach ( $all_plugins as $path => $plugin_data ) {
2149
			$plugins[ $path ] = array(
2150
				'is_active' => in_array( $path, $active_plugins ),
2151
				'file'      => $path,
2152
				'name'      => $plugin_data['Name'],
2153
				'version'   => $plugin_data['Version'],
2154
				'author'    => $plugin_data['Author'],
2155
			);
2156
		}
2157
2158
		return $plugins;
2159
	}
2160
2161
	/**
2162
	 * Gets and parses theme data to send with the heartbeat data
2163
	 *
2164
	 * @since 3.8.1
2165
	 *
2166
	 * @return array Array of theme data
2167
	 */
2168
	public static function get_parsed_theme_data() {
2169
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2170
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2171
2172
		$themes = array();
2173
		foreach ( $all_themes as $slug => $theme_data ) {
2174
			$theme_headers = array();
2175
			foreach ( $header_keys as $header_key ) {
2176
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2177
			}
2178
2179
			$themes[ $slug ] = array(
2180
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2181
				'slug'            => $slug,
2182
				'theme_root'      => $theme_data->get_theme_root_uri(),
2183
				'parent'          => $theme_data->parent(),
2184
				'headers'         => $theme_headers,
2185
			);
2186
		}
2187
2188
		return $themes;
2189
	}
2190
2191
	/**
2192
	 * Checks whether a specific plugin is active.
2193
	 *
2194
	 * We don't want to store these in a static variable, in case
2195
	 * there are switch_to_blog() calls involved.
2196
	 */
2197
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2198
		return in_array( $plugin, self::get_active_plugins() );
2199
	}
2200
2201
	/**
2202
	 * Check if Jetpack's Open Graph tags should be used.
2203
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2204
	 *
2205
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2206
	 * @action plugins_loaded
2207
	 * @return null
2208
	 */
2209
	public function check_open_graph() {
2210
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2211
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2212
		}
2213
2214
		$active_plugins = self::get_active_plugins();
2215
2216
		if ( ! empty( $active_plugins ) ) {
2217
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2218
				if ( in_array( $plugin, $active_plugins ) ) {
2219
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2220
					break;
2221
				}
2222
			}
2223
		}
2224
2225
		/**
2226
		 * Allow the addition of Open Graph Meta Tags to all pages.
2227
		 *
2228
		 * @since 2.0.3
2229
		 *
2230
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2231
		 */
2232
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2233
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2234
		}
2235
	}
2236
2237
	/**
2238
	 * Check if Jetpack's Twitter tags should be used.
2239
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2240
	 *
2241
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2242
	 * @action plugins_loaded
2243
	 * @return null
2244
	 */
2245
	public function check_twitter_tags() {
2246
2247
		$active_plugins = self::get_active_plugins();
2248
2249
		if ( ! empty( $active_plugins ) ) {
2250
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2251
				if ( in_array( $plugin, $active_plugins ) ) {
2252
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2253
					break;
2254
				}
2255
			}
2256
		}
2257
2258
		/**
2259
		 * Allow Twitter Card Meta tags to be disabled.
2260
		 *
2261
		 * @since 2.6.0
2262
		 *
2263
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2264
		 */
2265
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2266
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2267
		}
2268
	}
2269
2270
	/**
2271
	 * Allows plugins to submit security reports.
2272
	 *
2273
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2274
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2275
	 * @param array  $args         See definitions above
2276
	 */
2277
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2278
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2279
	}
2280
2281
	/* Jetpack Options API */
2282
2283
	public static function get_option_names( $type = 'compact' ) {
2284
		return Jetpack_Options::get_option_names( $type );
2285
	}
2286
2287
	/**
2288
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2289
	 *
2290
	 * @param string $name    Option name
2291
	 * @param mixed  $default (optional)
2292
	 */
2293
	public static function get_option( $name, $default = false ) {
2294
		return Jetpack_Options::get_option( $name, $default );
2295
	}
2296
2297
	/**
2298
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2299
	 *
2300
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2301
	 * @param string $name  Option name
2302
	 * @param mixed  $value Option value
2303
	 */
2304
	public static function update_option( $name, $value ) {
2305
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2306
		return Jetpack_Options::update_option( $name, $value );
2307
	}
2308
2309
	/**
2310
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2311
	 *
2312
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2313
	 * @param array $array array( option name => option value, ... )
2314
	 */
2315
	public static function update_options( $array ) {
2316
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2317
		return Jetpack_Options::update_options( $array );
2318
	}
2319
2320
	/**
2321
	 * Deletes the given option.  May be passed multiple option names as an array.
2322
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2323
	 *
2324
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2325
	 * @param string|array $names
2326
	 */
2327
	public static function delete_option( $names ) {
2328
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2329
		return Jetpack_Options::delete_option( $names );
2330
	}
2331
2332
	/**
2333
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2334
	 *
2335
	 * Enters a user token into the user_tokens option
2336
	 *
2337
	 * @param int    $user_id The user id.
2338
	 * @param string $token The user token.
2339
	 * @param bool   $is_master_user Whether the user is the master user.
2340
	 * @return bool
2341
	 */
2342
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2343
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2344
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2345
	}
2346
2347
	/**
2348
	 * Returns an array of all PHP files in the specified absolute path.
2349
	 * Equivalent to glob( "$absolute_path/*.php" ).
2350
	 *
2351
	 * @param string $absolute_path The absolute path of the directory to search.
2352
	 * @return array Array of absolute paths to the PHP files.
2353
	 */
2354
	public static function glob_php( $absolute_path ) {
2355
		if ( function_exists( 'glob' ) ) {
2356
			return glob( "$absolute_path/*.php" );
2357
		}
2358
2359
		$absolute_path = untrailingslashit( $absolute_path );
2360
		$files         = array();
2361
		if ( ! $dir = @opendir( $absolute_path ) ) {
2362
			return $files;
2363
		}
2364
2365
		while ( false !== $file = readdir( $dir ) ) {
2366
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2367
				continue;
2368
			}
2369
2370
			$file = "$absolute_path/$file";
2371
2372
			if ( ! is_file( $file ) ) {
2373
				continue;
2374
			}
2375
2376
			$files[] = $file;
2377
		}
2378
2379
		closedir( $dir );
2380
2381
		return $files;
2382
	}
2383
2384
	public static function activate_new_modules( $redirect = false ) {
2385
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2386
			return;
2387
		}
2388
2389
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2390 View Code Duplication
		if ( ! $jetpack_old_version ) {
2391
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2392
			/** This action is documented in class.jetpack.php */
2393
			do_action( 'updating_jetpack_version', $version, false );
2394
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2395
		}
2396
2397
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2398
2399
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2400
			return;
2401
		}
2402
2403
		$active_modules     = self::get_active_modules();
2404
		$reactivate_modules = array();
2405
		foreach ( $active_modules as $active_module ) {
2406
			$module = self::get_module( $active_module );
2407
			if ( ! isset( $module['changed'] ) ) {
2408
				continue;
2409
			}
2410
2411
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2412
				continue;
2413
			}
2414
2415
			$reactivate_modules[] = $active_module;
2416
			self::deactivate_module( $active_module );
2417
		}
2418
2419
		$new_version = JETPACK__VERSION . ':' . time();
2420
		/** This action is documented in class.jetpack.php */
2421
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2422
		Jetpack_Options::update_options(
2423
			array(
2424
				'version'     => $new_version,
2425
				'old_version' => $jetpack_old_version,
2426
			)
2427
		);
2428
2429
		self::state( 'message', 'modules_activated' );
2430
2431
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2432
2433
		if ( $redirect ) {
2434
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2435
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2436
				$page = $_GET['page'];
2437
			}
2438
2439
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2440
			exit;
2441
		}
2442
	}
2443
2444
	/**
2445
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2446
	 * Make sure to tuck away module "library" files in a sub-directory.
2447
	 */
2448
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2449
		static $modules = null;
2450
2451
		if ( ! isset( $modules ) ) {
2452
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2453
			// Use the cache if we're on the front-end and it's available...
2454
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2455
				$modules = $available_modules_option[ JETPACK__VERSION ];
2456
			} else {
2457
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2458
2459
				$modules = array();
2460
2461
				foreach ( $files as $file ) {
2462
					if ( ! $headers = self::get_module( $file ) ) {
2463
						continue;
2464
					}
2465
2466
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2467
				}
2468
2469
				Jetpack_Options::update_option(
2470
					'available_modules',
2471
					array(
2472
						JETPACK__VERSION => $modules,
2473
					)
2474
				);
2475
			}
2476
		}
2477
2478
		/**
2479
		 * Filters the array of modules available to be activated.
2480
		 *
2481
		 * @since 2.4.0
2482
		 *
2483
		 * @param array $modules Array of available modules.
2484
		 * @param string $min_version Minimum version number required to use modules.
2485
		 * @param string $max_version Maximum version number required to use modules.
2486
		 */
2487
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2488
2489
		if ( ! $min_version && ! $max_version ) {
2490
			return array_keys( $mods );
2491
		}
2492
2493
		$r = array();
2494
		foreach ( $mods as $slug => $introduced ) {
2495
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2496
				continue;
2497
			}
2498
2499
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2500
				continue;
2501
			}
2502
2503
			$r[] = $slug;
2504
		}
2505
2506
		return $r;
2507
	}
2508
2509
	/**
2510
	 * Default modules loaded on activation.
2511
	 */
2512
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2513
		$return = array();
2514
2515
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2516
			$module_data = self::get_module( $module );
2517
2518
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2519
				case 'yes':
2520
					$return[] = $module;
2521
					break;
2522
				case 'public':
2523
					if ( Jetpack_Options::get_option( 'public' ) ) {
2524
						$return[] = $module;
2525
					}
2526
					break;
2527
				case 'no':
2528
				default:
2529
					break;
2530
			}
2531
		}
2532
		/**
2533
		 * Filters the array of default modules.
2534
		 *
2535
		 * @since 2.5.0
2536
		 *
2537
		 * @param array $return Array of default modules.
2538
		 * @param string $min_version Minimum version number required to use modules.
2539
		 * @param string $max_version Maximum version number required to use modules.
2540
		 */
2541
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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

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

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

Loading history...
2542
	}
2543
2544
	/**
2545
	 * Checks activated modules during auto-activation to determine
2546
	 * if any of those modules are being deprecated.  If so, close
2547
	 * them out, and add any replacement modules.
2548
	 *
2549
	 * Runs at priority 99 by default.
2550
	 *
2551
	 * This is run late, so that it can still activate a module if
2552
	 * the new module is a replacement for another that the user
2553
	 * currently has active, even if something at the normal priority
2554
	 * would kibosh everything.
2555
	 *
2556
	 * @since 2.6
2557
	 * @uses jetpack_get_default_modules filter
2558
	 * @param array $modules
2559
	 * @return array
2560
	 */
2561
	function handle_deprecated_modules( $modules ) {
2562
		$deprecated_modules = array(
2563
			'debug'            => null,  // Closed out and moved to the debugger library.
2564
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2565
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2566
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2567
		);
2568
2569
		// Don't activate SSO if they never completed activating WPCC.
2570
		if ( self::is_module_active( 'wpcc' ) ) {
2571
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2572
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2573
				$deprecated_modules['wpcc'] = null;
2574
			}
2575
		}
2576
2577
		foreach ( $deprecated_modules as $module => $replacement ) {
2578
			if ( self::is_module_active( $module ) ) {
2579
				self::deactivate_module( $module );
2580
				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...
2581
					$modules[] = $replacement;
2582
				}
2583
			}
2584
		}
2585
2586
		return array_unique( $modules );
2587
	}
2588
2589
	/**
2590
	 * Checks activated plugins during auto-activation to determine
2591
	 * if any of those plugins are in the list with a corresponding module
2592
	 * that is not compatible with the plugin. The module will not be allowed
2593
	 * to auto-activate.
2594
	 *
2595
	 * @since 2.6
2596
	 * @uses jetpack_get_default_modules filter
2597
	 * @param array $modules
2598
	 * @return array
2599
	 */
2600
	function filter_default_modules( $modules ) {
2601
2602
		$active_plugins = self::get_active_plugins();
2603
2604
		if ( ! empty( $active_plugins ) ) {
2605
2606
			// For each module we'd like to auto-activate...
2607
			foreach ( $modules as $key => $module ) {
2608
				// If there are potential conflicts for it...
2609
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2610
					// For each potential conflict...
2611
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2612
						// If that conflicting plugin is active...
2613
						if ( in_array( $plugin, $active_plugins ) ) {
2614
							// Remove that item from being auto-activated.
2615
							unset( $modules[ $key ] );
2616
						}
2617
					}
2618
				}
2619
			}
2620
		}
2621
2622
		return $modules;
2623
	}
2624
2625
	/**
2626
	 * Extract a module's slug from its full path.
2627
	 */
2628
	public static function get_module_slug( $file ) {
2629
		return str_replace( '.php', '', basename( $file ) );
2630
	}
2631
2632
	/**
2633
	 * Generate a module's path from its slug.
2634
	 */
2635
	public static function get_module_path( $slug ) {
2636
		/**
2637
		 * Filters the path of a modules.
2638
		 *
2639
		 * @since 7.4.0
2640
		 *
2641
		 * @param array $return The absolute path to a module's root php file
2642
		 * @param string $slug The module slug
2643
		 */
2644
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

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

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

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

Loading history...
2645
	}
2646
2647
	/**
2648
	 * Load module data from module file. Headers differ from WordPress
2649
	 * plugin headers to avoid them being identified as standalone
2650
	 * plugins on the WordPress plugins page.
2651
	 */
2652
	public static function get_module( $module ) {
2653
		$headers = array(
2654
			'name'                      => 'Module Name',
2655
			'description'               => 'Module Description',
2656
			'sort'                      => 'Sort Order',
2657
			'recommendation_order'      => 'Recommendation Order',
2658
			'introduced'                => 'First Introduced',
2659
			'changed'                   => 'Major Changes In',
2660
			'deactivate'                => 'Deactivate',
2661
			'free'                      => 'Free',
2662
			'requires_connection'       => 'Requires Connection',
2663
			'auto_activate'             => 'Auto Activate',
2664
			'module_tags'               => 'Module Tags',
2665
			'feature'                   => 'Feature',
2666
			'additional_search_queries' => 'Additional Search Queries',
2667
			'plan_classes'              => 'Plans',
2668
		);
2669
2670
		$file = self::get_module_path( self::get_module_slug( $module ) );
2671
2672
		$mod = self::get_file_data( $file, $headers );
2673
		if ( empty( $mod['name'] ) ) {
2674
			return false;
2675
		}
2676
2677
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2678
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2679
		$mod['deactivate']           = empty( $mod['deactivate'] );
2680
		$mod['free']                 = empty( $mod['free'] );
2681
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2682
2683
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2684
			$mod['auto_activate'] = 'No';
2685
		} else {
2686
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2687
		}
2688
2689
		if ( $mod['module_tags'] ) {
2690
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2691
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2692
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2693
		} else {
2694
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2695
		}
2696
2697 View Code Duplication
		if ( $mod['plan_classes'] ) {
2698
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2699
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2700
		} else {
2701
			$mod['plan_classes'] = array( 'free' );
2702
		}
2703
2704 View Code Duplication
		if ( $mod['feature'] ) {
2705
			$mod['feature'] = explode( ',', $mod['feature'] );
2706
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2707
		} else {
2708
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2709
		}
2710
2711
		/**
2712
		 * Filters the feature array on a module.
2713
		 *
2714
		 * This filter allows you to control where each module is filtered: Recommended,
2715
		 * and the default "Other" listing.
2716
		 *
2717
		 * @since 3.5.0
2718
		 *
2719
		 * @param array   $mod['feature'] The areas to feature this module:
2720
		 *     'Recommended' shows on the main Jetpack admin screen.
2721
		 *     'Other' should be the default if no other value is in the array.
2722
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2723
		 * @param array   $mod All the currently assembled module data.
2724
		 */
2725
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2726
2727
		/**
2728
		 * Filter the returned data about a module.
2729
		 *
2730
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2731
		 * so please be careful.
2732
		 *
2733
		 * @since 3.6.0
2734
		 *
2735
		 * @param array   $mod    The details of the requested module.
2736
		 * @param string  $module The slug of the module, e.g. sharedaddy
2737
		 * @param string  $file   The path to the module source file.
2738
		 */
2739
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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

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

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

Loading history...
2740
	}
2741
2742
	/**
2743
	 * Like core's get_file_data implementation, but caches the result.
2744
	 */
2745
	public static function get_file_data( $file, $headers ) {
2746
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2747
		$file_name = basename( $file );
2748
2749
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2750
2751
		$file_data_option = get_transient( $cache_key );
2752
2753
		if ( ! is_array( $file_data_option ) ) {
2754
			delete_transient( $cache_key );
2755
			$file_data_option = false;
2756
		}
2757
2758
		if ( false === $file_data_option ) {
2759
			$file_data_option = array();
2760
		}
2761
2762
		$key           = md5( $file_name . serialize( $headers ) );
2763
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2764
2765
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2766
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2767
			return $file_data_option[ $key ];
2768
		}
2769
2770
		$data = get_file_data( $file, $headers );
2771
2772
		$file_data_option[ $key ] = $data;
2773
2774
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2775
2776
		return $data;
2777
	}
2778
2779
2780
	/**
2781
	 * Return translated module tag.
2782
	 *
2783
	 * @param string $tag Tag as it appears in each module heading.
2784
	 *
2785
	 * @return mixed
2786
	 */
2787
	public static function translate_module_tag( $tag ) {
2788
		return jetpack_get_module_i18n_tag( $tag );
2789
	}
2790
2791
	/**
2792
	 * Get i18n strings as a JSON-encoded string
2793
	 *
2794
	 * @return string The locale as JSON
2795
	 */
2796
	public static function get_i18n_data_json() {
2797
2798
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2799
		// JSON files with the file they should be included for. This is an md5
2800
		// of '_inc/build/admin.js'.
2801
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2802
2803
		$i18n_json =
2804
				   JETPACK__PLUGIN_DIR
2805
				   . 'languages/json/jetpack-'
2806
				   . get_user_locale()
2807
				   . '-'
2808
				   . $path_md5
2809
				   . '.json';
2810
2811
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2812
			$locale_data = @file_get_contents( $i18n_json );
2813
			if ( $locale_data ) {
2814
				return $locale_data;
2815
			}
2816
		}
2817
2818
		// Return valid empty Jed locale
2819
		return '{ "locale_data": { "messages": { "": {} } } }';
2820
	}
2821
2822
	/**
2823
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2824
	 *
2825
	 * @since 3.9.2
2826
	 *
2827
	 * @param array $modules
2828
	 *
2829
	 * @return string|void
2830
	 */
2831
	public static function get_translated_modules( $modules ) {
2832
		foreach ( $modules as $index => $module ) {
2833
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2834
			if ( isset( $module['name'] ) ) {
2835
				$modules[ $index ]['name'] = $i18n_module['name'];
2836
			}
2837
			if ( isset( $module['description'] ) ) {
2838
				$modules[ $index ]['description']       = $i18n_module['description'];
2839
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2840
			}
2841
		}
2842
		return $modules;
2843
	}
2844
2845
	/**
2846
	 * Get a list of activated modules as an array of module slugs.
2847
	 */
2848
	public static function get_active_modules() {
2849
		$active = Jetpack_Options::get_option( 'active_modules' );
2850
2851
		if ( ! is_array( $active ) ) {
2852
			$active = array();
2853
		}
2854
2855
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2856
			$active[] = 'vaultpress';
2857
		} else {
2858
			$active = array_diff( $active, array( 'vaultpress' ) );
2859
		}
2860
2861
		// If protect is active on the main site of a multisite, it should be active on all sites.
2862
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2863
			$active[] = 'protect';
2864
		}
2865
2866
		/**
2867
		 * Allow filtering of the active modules.
2868
		 *
2869
		 * Gives theme and plugin developers the power to alter the modules that
2870
		 * are activated on the fly.
2871
		 *
2872
		 * @since 5.8.0
2873
		 *
2874
		 * @param array $active Array of active module slugs.
2875
		 */
2876
		$active = apply_filters( 'jetpack_active_modules', $active );
2877
2878
		return array_unique( $active );
2879
	}
2880
2881
	/**
2882
	 * Check whether or not a Jetpack module is active.
2883
	 *
2884
	 * @param string $module The slug of a Jetpack module.
2885
	 * @return bool
2886
	 *
2887
	 * @static
2888
	 */
2889
	public static function is_module_active( $module ) {
2890
		return in_array( $module, self::get_active_modules() );
2891
	}
2892
2893
	public static function is_module( $module ) {
2894
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2895
	}
2896
2897
	/**
2898
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2899
	 *
2900
	 * @param bool $catch True to start catching, False to stop.
2901
	 *
2902
	 * @static
2903
	 */
2904
	public static function catch_errors( $catch ) {
2905
		static $display_errors, $error_reporting;
2906
2907
		if ( $catch ) {
2908
			$display_errors  = @ini_set( 'display_errors', 1 );
2909
			$error_reporting = @error_reporting( E_ALL );
2910
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2911
		} else {
2912
			@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...
2913
			@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...
2914
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2915
		}
2916
	}
2917
2918
	/**
2919
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2920
	 */
2921
	public static function catch_errors_on_shutdown() {
2922
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2923
	}
2924
2925
	/**
2926
	 * Rewrite any string to make paths easier to read.
2927
	 *
2928
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2929
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2930
	 *
2931
	 * @param $string
2932
	 * @return mixed
2933
	 */
2934
	public static function alias_directories( $string ) {
2935
		// ABSPATH has a trailing slash.
2936
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2937
		// WP_CONTENT_DIR does not have a trailing slash.
2938
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2939
2940
		return $string;
2941
	}
2942
2943
	public static function activate_default_modules(
2944
		$min_version = false,
2945
		$max_version = false,
2946
		$other_modules = array(),
2947
		$redirect = null,
2948
		$send_state_messages = null
2949
	) {
2950
		$jetpack = self::init();
2951
2952
		if ( is_null( $redirect ) ) {
2953
			if (
2954
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2955
			||
2956
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2957
			||
2958
				( defined( 'WP_CLI' ) && WP_CLI )
2959
			||
2960
				( defined( 'DOING_CRON' ) && DOING_CRON )
2961
			||
2962
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2963
			) {
2964
				$redirect = false;
2965
			} elseif ( is_admin() ) {
2966
				$redirect = true;
2967
			} else {
2968
				$redirect = false;
2969
			}
2970
		}
2971
2972
		if ( is_null( $send_state_messages ) ) {
2973
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2974
		}
2975
2976
		$modules = self::get_default_modules( $min_version, $max_version );
2977
		$modules = array_merge( $other_modules, $modules );
2978
2979
		// Look for standalone plugins and disable if active.
2980
2981
		$to_deactivate = array();
2982
		foreach ( $modules as $module ) {
2983
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2984
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2985
			}
2986
		}
2987
2988
		$deactivated = array();
2989
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2990
			list( $probable_file, $probable_title ) = $deactivate_me;
2991
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2992
				$deactivated[] = $module;
2993
			}
2994
		}
2995
2996
		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...
2997
			if ( $send_state_messages ) {
2998
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2999
			}
3000
3001
			if ( $redirect ) {
3002
				$url = add_query_arg(
3003
					array(
3004
						'action'   => 'activate_default_modules',
3005
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
3006
					),
3007
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
3008
				);
3009
				wp_safe_redirect( $url );
3010
				exit;
3011
			}
3012
		}
3013
3014
		/**
3015
		 * Fires before default modules are activated.
3016
		 *
3017
		 * @since 1.9.0
3018
		 *
3019
		 * @param string $min_version Minimum version number required to use modules.
3020
		 * @param string $max_version Maximum version number required to use modules.
3021
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3022
		 */
3023
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
3024
3025
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
3026
		if ( $send_state_messages ) {
3027
			self::restate();
3028
			self::catch_errors( true );
3029
		}
3030
3031
		$active = self::get_active_modules();
3032
3033
		foreach ( $modules as $module ) {
3034
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
3035
				$active[] = $module;
3036
				self::update_active_modules( $active );
3037
				continue;
3038
			}
3039
3040
			if ( $send_state_messages && in_array( $module, $active ) ) {
3041
				$module_info = self::get_module( $module );
3042 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
3043
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3044
					if ( $active_state = self::state( $state ) ) {
3045
						$active_state = explode( ',', $active_state );
3046
					} else {
3047
						$active_state = array();
3048
					}
3049
					$active_state[] = $module;
3050
					self::state( $state, implode( ',', $active_state ) );
3051
				}
3052
				continue;
3053
			}
3054
3055
			$file = self::get_module_path( $module );
3056
			if ( ! file_exists( $file ) ) {
3057
				continue;
3058
			}
3059
3060
			// we'll override this later if the plugin can be included without fatal error
3061
			if ( $redirect ) {
3062
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3063
			}
3064
3065
			if ( $send_state_messages ) {
3066
				self::state( 'error', 'module_activation_failed' );
3067
				self::state( 'module', $module );
3068
			}
3069
3070
			ob_start();
3071
			require_once $file;
3072
3073
			$active[] = $module;
3074
3075 View Code Duplication
			if ( $send_state_messages ) {
3076
3077
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
3078
				if ( $active_state = self::state( $state ) ) {
3079
					$active_state = explode( ',', $active_state );
3080
				} else {
3081
					$active_state = array();
3082
				}
3083
				$active_state[] = $module;
3084
				self::state( $state, implode( ',', $active_state ) );
3085
			}
3086
3087
			self::update_active_modules( $active );
3088
3089
			ob_end_clean();
3090
		}
3091
3092
		if ( $send_state_messages ) {
3093
			self::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3094
			self::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3095
		}
3096
3097
		self::catch_errors( false );
3098
		/**
3099
		 * Fires when default modules are activated.
3100
		 *
3101
		 * @since 1.9.0
3102
		 *
3103
		 * @param string $min_version Minimum version number required to use modules.
3104
		 * @param string $max_version Maximum version number required to use modules.
3105
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3106
		 */
3107
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3108
	}
3109
3110
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3111
		/**
3112
		 * Fires before a module is activated.
3113
		 *
3114
		 * @since 2.6.0
3115
		 *
3116
		 * @param string $module Module slug.
3117
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3118
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3119
		 */
3120
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3121
3122
		$jetpack = self::init();
3123
3124
		if ( ! strlen( $module ) ) {
3125
			return false;
3126
		}
3127
3128
		if ( ! self::is_module( $module ) ) {
3129
			return false;
3130
		}
3131
3132
		// If it's already active, then don't do it again
3133
		$active = self::get_active_modules();
3134
		foreach ( $active as $act ) {
3135
			if ( $act == $module ) {
3136
				return true;
3137
			}
3138
		}
3139
3140
		$module_data = self::get_module( $module );
3141
3142
		$is_development_mode = ( new Status() )->is_development_mode();
3143
		if ( ! self::is_active() ) {
3144
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3145
				return false;
3146
			}
3147
3148
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3149
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3150
				return false;
3151
			}
3152
		}
3153
3154
		// Check and see if the old plugin is active
3155
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3156
			// Deactivate the old plugin
3157
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3158
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3159
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3160
				self::state( 'deactivated_plugins', $module );
3161
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3162
				exit;
3163
			}
3164
		}
3165
3166
		// Protect won't work with mis-configured IPs
3167
		if ( 'protect' === $module ) {
3168
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3169
			if ( ! jetpack_protect_get_ip() ) {
3170
				self::state( 'message', 'protect_misconfigured_ip' );
3171
				return false;
3172
			}
3173
		}
3174
3175
		if ( ! Jetpack_Plan::supports( $module ) ) {
3176
			return false;
3177
		}
3178
3179
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3180
		self::state( 'module', $module );
3181
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3182
3183
		self::catch_errors( true );
3184
		ob_start();
3185
		require self::get_module_path( $module );
3186
		/** This action is documented in class.jetpack.php */
3187
		do_action( 'jetpack_activate_module', $module );
3188
		$active[] = $module;
3189
		self::update_active_modules( $active );
3190
3191
		self::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3192
		ob_end_clean();
3193
		self::catch_errors( false );
3194
3195
		if ( $redirect ) {
3196
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3197
		}
3198
		if ( $exit ) {
3199
			exit;
3200
		}
3201
		return true;
3202
	}
3203
3204
	function activate_module_actions( $module ) {
3205
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3206
	}
3207
3208
	public static function deactivate_module( $module ) {
3209
		/**
3210
		 * Fires when a module is deactivated.
3211
		 *
3212
		 * @since 1.9.0
3213
		 *
3214
		 * @param string $module Module slug.
3215
		 */
3216
		do_action( 'jetpack_pre_deactivate_module', $module );
3217
3218
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3219
3220
		$active = self::get_active_modules();
3221
		$new    = array_filter( array_diff( $active, (array) $module ) );
3222
3223
		return self::update_active_modules( $new );
3224
	}
3225
3226
	public static function enable_module_configurable( $module ) {
3227
		$module = self::get_module_slug( $module );
3228
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3229
	}
3230
3231
	/**
3232
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3233
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3234
	 *
3235
	 * @param string $module Module slug
3236
	 * @return string $url module configuration URL
3237
	 */
3238
	public static function module_configuration_url( $module ) {
3239
		$module      = self::get_module_slug( $module );
3240
		$default_url = self::admin_url() . "#/settings?term=$module";
3241
		/**
3242
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3243
		 *
3244
		 * @since 6.9.0
3245
		 *
3246
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3247
		 */
3248
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3249
3250
		return $url;
3251
	}
3252
3253
	/* Installation */
3254
	public static function bail_on_activation( $message, $deactivate = true ) {
3255
		?>
3256
<!doctype html>
3257
<html>
3258
<head>
3259
<meta charset="<?php bloginfo( 'charset' ); ?>">
3260
<style>
3261
* {
3262
	text-align: center;
3263
	margin: 0;
3264
	padding: 0;
3265
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3266
}
3267
p {
3268
	margin-top: 1em;
3269
	font-size: 18px;
3270
}
3271
</style>
3272
<body>
3273
<p><?php echo esc_html( $message ); ?></p>
3274
</body>
3275
</html>
3276
		<?php
3277
		if ( $deactivate ) {
3278
			$plugins = get_option( 'active_plugins' );
3279
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3280
			$update  = false;
3281
			foreach ( $plugins as $i => $plugin ) {
3282
				if ( $plugin === $jetpack ) {
3283
					$plugins[ $i ] = false;
3284
					$update        = true;
3285
				}
3286
			}
3287
3288
			if ( $update ) {
3289
				update_option( 'active_plugins', array_filter( $plugins ) );
3290
			}
3291
		}
3292
		exit;
3293
	}
3294
3295
	/**
3296
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3297
	 *
3298
	 * @static
3299
	 */
3300
	public static function plugin_activation( $network_wide ) {
3301
		Jetpack_Options::update_option( 'activated', 1 );
3302
3303
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3304
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3305
		}
3306
3307
		if ( $network_wide ) {
3308
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3309
		}
3310
3311
		// For firing one-off events (notices) immediately after activation
3312
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3313
3314
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3315
3316
		Health::on_jetpack_activated();
3317
3318
		self::plugin_initialize();
3319
	}
3320
3321
	public static function get_activation_source( $referer_url ) {
3322
3323
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3324
			return array( 'wp-cli', null );
3325
		}
3326
3327
		$referer = wp_parse_url( $referer_url );
3328
3329
		$source_type  = 'unknown';
3330
		$source_query = null;
3331
3332
		if ( ! is_array( $referer ) ) {
3333
			return array( $source_type, $source_query );
3334
		}
3335
3336
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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

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

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

Loading history...
3337
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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

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

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

Loading history...
3338
3339
		if ( isset( $referer['query'] ) ) {
3340
			parse_str( $referer['query'], $query_parts );
3341
		} else {
3342
			$query_parts = array();
3343
		}
3344
3345
		if ( $plugins_path === $referer['path'] ) {
3346
			$source_type = 'list';
3347
		} elseif ( $plugins_install_path === $referer['path'] ) {
3348
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3349
			switch ( $tab ) {
3350
				case 'popular':
3351
					$source_type = 'popular';
3352
					break;
3353
				case 'recommended':
3354
					$source_type = 'recommended';
3355
					break;
3356
				case 'favorites':
3357
					$source_type = 'favorites';
3358
					break;
3359
				case 'search':
3360
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3361
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3362
					break;
3363
				default:
3364
					$source_type = 'featured';
3365
			}
3366
		}
3367
3368
		return array( $source_type, $source_query );
3369
	}
3370
3371
	/**
3372
	 * Runs before bumping version numbers up to a new version
3373
	 *
3374
	 * @param string $version    Version:timestamp.
3375
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3376
	 */
3377
	public static function do_version_bump( $version, $old_version ) {
3378
		if ( $old_version ) { // For existing Jetpack installations.
3379
3380
			// If a front end page is visited after the update, the 'wp' action will fire.
3381
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3382
3383
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3384
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3385
		}
3386
	}
3387
3388
	/**
3389
	 * Sets the display_update_modal state.
3390
	 */
3391
	public static function set_update_modal_display() {
3392
		self::state( 'display_update_modal', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3393
	}
3394
3395
	/**
3396
	 * Sets the internal version number and activation state.
3397
	 *
3398
	 * @static
3399
	 */
3400
	public static function plugin_initialize() {
3401
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3402
			Jetpack_Options::update_option( 'activated', 2 );
3403
		}
3404
3405 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3406
			$version = $old_version = JETPACK__VERSION . ':' . time();
3407
			/** This action is documented in class.jetpack.php */
3408
			do_action( 'updating_jetpack_version', $version, false );
3409
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3410
		}
3411
3412
		self::load_modules();
3413
3414
		Jetpack_Options::delete_option( 'do_activate' );
3415
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3416
	}
3417
3418
	/**
3419
	 * Removes all connection options
3420
	 *
3421
	 * @static
3422
	 */
3423
	public static function plugin_deactivation() {
3424
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3425
		$tracking = new Tracking();
3426
		$tracking->record_user_event( 'deactivate_plugin', array() );
3427
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3428
			Jetpack_Network::init()->deactivate();
3429
		} else {
3430
			self::disconnect( false );
3431
			// Jetpack_Heartbeat::init()->deactivate();
3432
		}
3433
	}
3434
3435
	/**
3436
	 * Disconnects from the Jetpack servers.
3437
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3438
	 *
3439
	 * @static
3440
	 */
3441
	public static function disconnect( $update_activated_state = true ) {
3442
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3443
		$connection = self::connection();
3444
		$connection->clean_nonces( true );
3445
3446
		// If the site is in an IDC because sync is not allowed,
3447
		// let's make sure to not disconnect the production site.
3448
		if ( ! self::validate_sync_error_idc_option() ) {
3449
			$tracking = new Tracking();
3450
			$tracking->record_user_event( 'disconnect_site', array() );
3451
3452
			$connection->disconnect_site_wpcom( true );
3453
		}
3454
3455
		$connection->delete_all_connection_tokens( true );
3456
		Jetpack_IDC::clear_all_idc_options();
3457
3458
		if ( $update_activated_state ) {
3459
			Jetpack_Options::update_option( 'activated', 4 );
3460
		}
3461
3462
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3463
			// Check then record unique disconnection if site has never been disconnected previously
3464
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3465
				$jetpack_unique_connection['disconnected'] = 1;
3466
			} else {
3467
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3468
					// track unique disconnect
3469
					$jetpack = self::init();
3470
3471
					$jetpack->stat( 'connections', 'unique-disconnect' );
3472
					$jetpack->do_stats( 'server_side' );
3473
				}
3474
				// increment number of times disconnected
3475
				$jetpack_unique_connection['disconnected'] += 1;
3476
			}
3477
3478
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3479
		}
3480
3481
		// Delete all the sync related data. Since it could be taking up space.
3482
		Sender::get_instance()->uninstall();
3483
3484
		// Disable the Heartbeat cron
3485
		Jetpack_Heartbeat::init()->deactivate();
3486
	}
3487
3488
	/**
3489
	 * Unlinks the current user from the linked WordPress.com user.
3490
	 *
3491
	 * @deprecated since 7.7
3492
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3493
	 *
3494
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
3495
	 * @return Boolean Whether the disconnection of the user was successful.
3496
	 */
3497
	public static function unlink_user( $user_id = null ) {
3498
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3499
		return Connection_Manager::disconnect_user( $user_id );
3500
	}
3501
3502
	/**
3503
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3504
	 */
3505
	public static function try_registration() {
3506
		$terms_of_service = new Terms_Of_Service();
3507
		// The user has agreed to the TOS at some point by now.
3508
		$terms_of_service->agree();
3509
3510
		// Let's get some testing in beta versions and such.
3511
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3512
			// Before attempting to connect, let's make sure that the domains are viable.
3513
			$domains_to_check = array_unique(
3514
				array(
3515
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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

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

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

Loading history...
3516
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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

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

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

Loading history...
3517
				)
3518
			);
3519
			foreach ( $domains_to_check as $domain ) {
3520
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Documentation introduced by
$domain is of type array<string,string>|false, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3521
				if ( is_wp_error( $result ) ) {
3522
					return $result;
3523
				}
3524
			}
3525
		}
3526
3527
		$result = self::register();
3528
3529
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3530
		if ( ! $result || is_wp_error( $result ) ) {
3531
			return $result;
3532
		} else {
3533
			return true;
3534
		}
3535
	}
3536
3537
	/**
3538
	 * Tracking an internal event log. Try not to put too much chaff in here.
3539
	 *
3540
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3541
	 */
3542
	public static function log( $code, $data = null ) {
3543
		// only grab the latest 200 entries
3544
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3545
3546
		// Append our event to the log
3547
		$log_entry = array(
3548
			'time'    => time(),
3549
			'user_id' => get_current_user_id(),
3550
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3551
			'code'    => $code,
3552
		);
3553
		// Don't bother storing it unless we've got some.
3554
		if ( ! is_null( $data ) ) {
3555
			$log_entry['data'] = $data;
3556
		}
3557
		$log[] = $log_entry;
3558
3559
		// Try add_option first, to make sure it's not autoloaded.
3560
		// @todo: Add an add_option method to Jetpack_Options
3561
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3562
			Jetpack_Options::update_option( 'log', $log );
3563
		}
3564
3565
		/**
3566
		 * Fires when Jetpack logs an internal event.
3567
		 *
3568
		 * @since 3.0.0
3569
		 *
3570
		 * @param array $log_entry {
3571
		 *  Array of details about the log entry.
3572
		 *
3573
		 *  @param string time Time of the event.
3574
		 *  @param int user_id ID of the user who trigerred the event.
3575
		 *  @param int blog_id Jetpack Blog ID.
3576
		 *  @param string code Unique name for the event.
3577
		 *  @param string data Data about the event.
3578
		 * }
3579
		 */
3580
		do_action( 'jetpack_log_entry', $log_entry );
3581
	}
3582
3583
	/**
3584
	 * Get the internal event log.
3585
	 *
3586
	 * @param $event (string) - only return the specific log events
3587
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3588
	 *
3589
	 * @return array of log events || WP_Error for invalid params
3590
	 */
3591
	public static function get_log( $event = false, $num = false ) {
3592
		if ( $event && ! is_string( $event ) ) {
3593
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

Loading history...
3594
		}
3595
3596
		if ( $num && ! is_numeric( $num ) ) {
3597
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

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

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

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

Loading history...
3598
		}
3599
3600
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3601
3602
		// If nothing set - act as it did before, otherwise let's start customizing the output
3603
		if ( ! $num && ! $event ) {
3604
			return $entire_log;
3605
		} else {
3606
			$entire_log = array_reverse( $entire_log );
3607
		}
3608
3609
		$custom_log_output = array();
3610
3611
		if ( $event ) {
3612
			foreach ( $entire_log as $log_event ) {
3613
				if ( $event == $log_event['code'] ) {
3614
					$custom_log_output[] = $log_event;
3615
				}
3616
			}
3617
		} else {
3618
			$custom_log_output = $entire_log;
3619
		}
3620
3621
		if ( $num ) {
3622
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3623
		}
3624
3625
		return $custom_log_output;
3626
	}
3627
3628
	/**
3629
	 * Log modification of important settings.
3630
	 */
3631
	public static function log_settings_change( $option, $old_value, $value ) {
3632
		switch ( $option ) {
3633
			case 'jetpack_sync_non_public_post_stati':
3634
				self::log( $option, $value );
3635
				break;
3636
		}
3637
	}
3638
3639
	/**
3640
	 * Return stat data for WPCOM sync
3641
	 */
3642
	public static function get_stat_data( $encode = true, $extended = true ) {
3643
		$data = Jetpack_Heartbeat::generate_stats_array();
3644
3645
		if ( $extended ) {
3646
			$additional_data = self::get_additional_stat_data();
3647
			$data            = array_merge( $data, $additional_data );
3648
		}
3649
3650
		if ( $encode ) {
3651
			return json_encode( $data );
3652
		}
3653
3654
		return $data;
3655
	}
3656
3657
	/**
3658
	 * Get additional stat data to sync to WPCOM
3659
	 */
3660
	public static function get_additional_stat_data( $prefix = '' ) {
3661
		$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...
3662
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3663
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3664
		$return[ "{$prefix}site-count" ]    = 0;
3665
3666
		if ( function_exists( 'get_blog_count' ) ) {
3667
			$return[ "{$prefix}site-count" ] = get_blog_count();
3668
		}
3669
		return $return;
3670
	}
3671
3672
	private static function get_site_user_count() {
3673
		global $wpdb;
3674
3675
		if ( function_exists( 'wp_is_large_network' ) ) {
3676
			if ( wp_is_large_network( 'users' ) ) {
3677
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3678
			}
3679
		}
3680
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3681
			// It wasn't there, so regenerate the data and save the transient
3682
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3683
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3684
		}
3685
		return $user_count;
3686
	}
3687
3688
	/* Admin Pages */
3689
3690
	function admin_init() {
3691
		// If the plugin is not connected, display a connect message.
3692
		if (
3693
			// the plugin was auto-activated and needs its candy
3694
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3695
		||
3696
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3697
			! Jetpack_Options::get_option( 'activated' )
3698
		) {
3699
			self::plugin_initialize();
3700
		}
3701
3702
		$is_development_mode = ( new Status() )->is_development_mode();
3703
		if ( ! self::is_active() && ! $is_development_mode ) {
3704
			Jetpack_Connection_Banner::init();
3705
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3706
			// Upgrade: 1.1 -> 1.1.1
3707
			// Check and see if host can verify the Jetpack servers' SSL certificate
3708
			$args       = array();
3709
			$connection = self::connection();
3710
			Client::_wp_remote_request(
3711
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3712
				$args,
3713
				true
3714
			);
3715
		}
3716
3717
		Jetpack_Wizard_Banner::init();
3718
3719
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3720
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3721
		}
3722
3723
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3724
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3725
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3726
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3727
3728
		if ( self::is_active() || $is_development_mode ) {
3729
			// Artificially throw errors in certain specific cases during plugin activation.
3730
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3731
		}
3732
3733
		// Add custom column in wp-admin/users.php to show whether user is linked.
3734
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3735
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3736
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3737
	}
3738
3739
	function admin_body_class( $admin_body_class = '' ) {
3740
		$classes = explode( ' ', trim( $admin_body_class ) );
3741
3742
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3743
3744
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3745
		return " $admin_body_class ";
3746
	}
3747
3748
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3749
		return $admin_body_class . ' jetpack-pagestyles ';
3750
	}
3751
3752
	/**
3753
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3754
	 * This function artificially throws errors for such cases (per a specific list).
3755
	 *
3756
	 * @param string $plugin The activated plugin.
3757
	 */
3758
	function throw_error_on_activate_plugin( $plugin ) {
3759
		$active_modules = self::get_active_modules();
3760
3761
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3762
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3763
			$throw = false;
3764
3765
			// Try and make sure it really was the stats plugin
3766
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3767
				if ( 'stats.php' == basename( $plugin ) ) {
3768
					$throw = true;
3769
				}
3770
			} else {
3771
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3772
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3773
					$throw = true;
3774
				}
3775
			}
3776
3777
			if ( $throw ) {
3778
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3779
			}
3780
		}
3781
	}
3782
3783
	function intercept_plugin_error_scrape_init() {
3784
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3785
	}
3786
3787
	function intercept_plugin_error_scrape( $action, $result ) {
3788
		if ( ! $result ) {
3789
			return;
3790
		}
3791
3792
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3793
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3794
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3795
			}
3796
		}
3797
	}
3798
3799
	/**
3800
	 * Register the remote file upload request handlers, if needed.
3801
	 *
3802
	 * @access public
3803
	 */
3804
	public function add_remote_request_handlers() {
3805
		// Remote file uploads are allowed only via AJAX requests.
3806
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3807
			return;
3808
		}
3809
3810
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3811
		$remote_request_actions = array(
3812
			'jetpack_upload_file',
3813
			'jetpack_update_file',
3814
		);
3815
3816
		// phpcs:ignore WordPress.Security.NonceVerification
3817
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3818
			return;
3819
		}
3820
3821
		// Require Jetpack authentication for the remote file upload AJAX requests.
3822
		if ( ! $this->connection_manager ) {
3823
			$this->connection_manager = new Connection_Manager();
3824
		}
3825
3826
		$this->connection_manager->require_jetpack_authentication();
3827
3828
		// Register the remote file upload AJAX handlers.
3829
		foreach ( $remote_request_actions as $action ) {
3830
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3831
		}
3832
	}
3833
3834
	/**
3835
	 * Handler for Jetpack remote file uploads.
3836
	 *
3837
	 * @access public
3838
	 */
3839
	public function remote_request_handlers() {
3840
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3841
3842
		switch ( current_filter() ) {
3843
			case 'wp_ajax_nopriv_jetpack_upload_file':
3844
				$response = $this->upload_handler();
3845
				break;
3846
3847
			case 'wp_ajax_nopriv_jetpack_update_file':
3848
				$response = $this->upload_handler( true );
3849
				break;
3850
			default:
3851
				$response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

Loading history...
3852
				break;
3853
		}
3854
3855
		if ( ! $response ) {
3856
			$response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
3857
		}
3858
3859
		if ( is_wp_error( $response ) ) {
3860
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3861
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3862
			$error_description = $response->get_error_message();
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3863
3864
			if ( ! is_int( $status_code ) ) {
3865
				$status_code = 400;
3866
			}
3867
3868
			status_header( $status_code );
3869
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3870
		}
3871
3872
		status_header( 200 );
3873
		if ( true === $response ) {
3874
			exit;
3875
		}
3876
3877
		die( json_encode( (object) $response ) );
3878
	}
3879
3880
	/**
3881
	 * Uploads a file gotten from the global $_FILES.
3882
	 * If `$update_media_item` is true and `post_id` is defined
3883
	 * the attachment file of the media item (gotten through of the post_id)
3884
	 * will be updated instead of add a new one.
3885
	 *
3886
	 * @param  boolean $update_media_item - update media attachment
3887
	 * @return array - An array describing the uploadind files process
3888
	 */
3889
	function upload_handler( $update_media_item = false ) {
3890
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3891
			return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 405.

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

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

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

Loading history...
3892
		}
3893
3894
		$user = wp_authenticate( '', '' );
3895
		if ( ! $user || is_wp_error( $user ) ) {
3896
			return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 403.

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

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

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

Loading history...
3897
		}
3898
3899
		wp_set_current_user( $user->ID );
3900
3901
		if ( ! current_user_can( 'upload_files' ) ) {
3902
			return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

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

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

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

Loading history...
3903
		}
3904
3905
		if ( empty( $_FILES ) ) {
3906
			return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

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

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

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

Loading history...
3907
		}
3908
3909
		foreach ( array_keys( $_FILES ) as $files_key ) {
3910
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3911
				return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'missing_hmac'.

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

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

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

Loading history...
3912
			}
3913
		}
3914
3915
		$media_keys = array_keys( $_FILES['media'] );
3916
3917
		$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...
3918
		if ( ! $token || is_wp_error( $token ) ) {
3919
			return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3920
		}
3921
3922
		$uploaded_files = array();
3923
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3924
		unset( $GLOBALS['post'] );
3925
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3926
			$file = array();
3927
			foreach ( $media_keys as $media_key ) {
3928
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3929
			}
3930
3931
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3932
3933
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3934
			if ( $hmac_provided !== $hmac_file ) {
3935
				$uploaded_files[ $index ] = (object) array(
3936
					'error'             => 'invalid_hmac',
3937
					'error_description' => 'The corresponding HMAC for this file does not match',
3938
				);
3939
				continue;
3940
			}
3941
3942
			$_FILES['.jetpack.upload.'] = $file;
3943
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3944
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3945
				$post_id = 0;
3946
			}
3947
3948
			if ( $update_media_item ) {
3949
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3950
					return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

Loading history...
3951
				}
3952
3953
				$media_array = $_FILES['media'];
3954
3955
				$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...
3956
				$file_array['type']     = $media_array['type'][0];
3957
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3958
				$file_array['error']    = $media_array['error'][0];
3959
				$file_array['size']     = $media_array['size'][0];
3960
3961
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3962
3963
				if ( is_wp_error( $edited_media_item ) ) {
3964
					return $edited_media_item;
3965
				}
3966
3967
				$response = (object) array(
3968
					'id'   => (string) $post_id,
3969
					'file' => (string) $edited_media_item->post_title,
3970
					'url'  => (string) wp_get_attachment_url( $post_id ),
3971
					'type' => (string) $edited_media_item->post_mime_type,
3972
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3973
				);
3974
3975
				return (array) array( $response );
3976
			}
3977
3978
			$attachment_id = media_handle_upload(
3979
				'.jetpack.upload.',
3980
				$post_id,
3981
				array(),
3982
				array(
3983
					'action' => 'jetpack_upload_file',
3984
				)
3985
			);
3986
3987
			if ( ! $attachment_id ) {
3988
				$uploaded_files[ $index ] = (object) array(
3989
					'error'             => 'unknown',
3990
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3991
				);
3992
			} elseif ( is_wp_error( $attachment_id ) ) {
3993
				$uploaded_files[ $index ] = (object) array(
3994
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3995
					'error_description' => $attachment_id->get_error_message(),
3996
				);
3997
			} else {
3998
				$attachment               = get_post( $attachment_id );
3999
				$uploaded_files[ $index ] = (object) array(
4000
					'id'   => (string) $attachment_id,
4001
					'file' => $attachment->post_title,
4002
					'url'  => wp_get_attachment_url( $attachment_id ),
4003
					'type' => $attachment->post_mime_type,
4004
					'meta' => wp_get_attachment_metadata( $attachment_id ),
4005
				);
4006
				// Zip files uploads are not supported unless they are done for installation purposed
4007
				// lets delete them in case something goes wrong in this whole process
4008
				if ( 'application/zip' === $attachment->post_mime_type ) {
4009
					// Schedule a cleanup for 2 hours from now in case of failed install.
4010
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
4011
				}
4012
			}
4013
		}
4014
		if ( ! is_null( $global_post ) ) {
4015
			$GLOBALS['post'] = $global_post;
4016
		}
4017
4018
		return $uploaded_files;
4019
	}
4020
4021
	/**
4022
	 * Add help to the Jetpack page
4023
	 *
4024
	 * @since Jetpack (1.2.3)
4025
	 * @return false if not the Jetpack page
4026
	 */
4027
	function admin_help() {
4028
		$current_screen = get_current_screen();
4029
4030
		// Overview
4031
		$current_screen->add_help_tab(
4032
			array(
4033
				'id'      => 'home',
4034
				'title'   => __( 'Home', 'jetpack' ),
4035
				'content' =>
4036
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4037
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4038
					'<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>',
4039
			)
4040
		);
4041
4042
		// Screen Content
4043
		if ( current_user_can( 'manage_options' ) ) {
4044
			$current_screen->add_help_tab(
4045
				array(
4046
					'id'      => 'settings',
4047
					'title'   => __( 'Settings', 'jetpack' ),
4048
					'content' =>
4049
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
4050
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4051
						'<ol>' .
4052
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4053
							'<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>' .
4054
						'</ol>' .
4055
						'<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>',
4056
				)
4057
			);
4058
		}
4059
4060
		// Help Sidebar
4061
		$support_url = Redirect::get_url( 'jetpack-support' );
4062
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
4063
		$current_screen->set_help_sidebar(
4064
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4065
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4066
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4067
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4068
		);
4069
	}
4070
4071
	function admin_menu_css() {
4072
		wp_enqueue_style( 'jetpack-icons' );
4073
	}
4074
4075
	function admin_menu_order() {
4076
		return true;
4077
	}
4078
4079 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
4080
		$jp_menu_order = array();
4081
4082
		foreach ( $menu_order as $index => $item ) {
4083
			if ( $item != 'jetpack' ) {
4084
				$jp_menu_order[] = $item;
4085
			}
4086
4087
			if ( $index == 0 ) {
4088
				$jp_menu_order[] = 'jetpack';
4089
			}
4090
		}
4091
4092
		return $jp_menu_order;
4093
	}
4094
4095
	function admin_banner_styles() {
4096
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4097
4098 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4099
			wp_register_style(
4100
				'jetpack-dops-style',
4101
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4102
				array(),
4103
				JETPACK__VERSION
4104
			);
4105
		}
4106
4107
		wp_enqueue_style(
4108
			'jetpack',
4109
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4110
			array( 'jetpack-dops-style' ),
4111
			JETPACK__VERSION . '-20121016'
4112
		);
4113
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4114
		wp_style_add_data( 'jetpack', 'suffix', $min );
4115
	}
4116
4117
	function plugin_action_links( $actions ) {
4118
4119
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4120
4121
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4122
			return array_merge(
4123
				$jetpack_home,
4124
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4125
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4126
				$actions
4127
			);
4128
		}
4129
4130
		return array_merge( $jetpack_home, $actions );
4131
	}
4132
4133
	/**
4134
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4135
	 *
4136
	 * @param string $hook The current admin page.
4137
	 *
4138
	 * @return void
4139
	 */
4140
	public function deactivate_dialog( $hook ) {
4141
		if (
4142
			'plugins.php' === $hook
4143
			&& self::is_active()
4144
		) {
4145
4146
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4147
4148
			if ( count( $active_plugins_using_connection ) > 1 ) {
4149
4150
				add_thickbox();
4151
4152
				wp_register_script(
4153
					'jp-tracks',
4154
					'//stats.wp.com/w.js',
4155
					array(),
4156
					gmdate( 'YW' ),
4157
					true
4158
				);
4159
4160
				wp_register_script(
4161
					'jp-tracks-functions',
4162
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4163
					array( 'jp-tracks' ),
4164
					JETPACK__VERSION,
4165
					false
4166
				);
4167
4168
				wp_enqueue_script(
4169
					'jetpack-deactivate-dialog-js',
4170
					Assets::get_file_url_for_environment(
4171
						'_inc/build/jetpack-deactivate-dialog.min.js',
4172
						'_inc/jetpack-deactivate-dialog.js'
4173
					),
4174
					array( 'jquery', 'jp-tracks-functions' ),
4175
					JETPACK__VERSION,
4176
					true
4177
				);
4178
4179
				wp_localize_script(
4180
					'jetpack-deactivate-dialog-js',
4181
					'deactivate_dialog',
4182
					array(
4183
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4184
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4185
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4186
					)
4187
				);
4188
4189
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4190
4191
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4192
			}
4193
		}
4194
	}
4195
4196
	/**
4197
	 * Outputs the content of the deactivation modal
4198
	 *
4199
	 * @return void
4200
	 */
4201
	public function deactivate_dialog_content() {
4202
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4203
		unset( $active_plugins_using_connection['jetpack'] );
4204
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4202 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...
4205
	}
4206
4207
	/**
4208
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4209
	 *
4210
	 * @param string $login_url The wp-login URL.
4211
	 * @param string $redirect  URL to redirect users after logging in.
4212
	 * @since Jetpack 8.4
4213
	 * @return string
4214
	 */
4215
	public function login_url( $login_url, $redirect ) {
4216
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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

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

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

Loading history...
4217
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4218
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4219
		}
4220
		return $login_url;
4221
	}
4222
4223
	/**
4224
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4225
	 *
4226
	 * @since Jetpack 8.4
4227
	 */
4228
	public function login_init() {
4229
		// phpcs:ignore WordPress.Security.NonceVerification
4230
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4231
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4232
			wp_safe_redirect(
4233
				add_query_arg(
4234
					array(
4235
						'forceInstall' => 1,
4236
						'url'          => rawurlencode( get_site_url() ),
4237
					),
4238
					// @todo provide way to go to specific calypso env.
4239
					self::get_calypso_host() . 'jetpack/connect'
4240
				)
4241
			);
4242
			exit;
4243
		}
4244
	}
4245
4246
	/*
4247
	 * Registration flow:
4248
	 * 1 - ::admin_page_load() action=register
4249
	 * 2 - ::try_registration()
4250
	 * 3 - ::register()
4251
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4252
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4253
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4254
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4255
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4256
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4257
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4258
	 *       jetpack_id, jetpack_secret, jetpack_public
4259
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4260
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4261
	 * 5 - user logs in with WP.com account
4262
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4263
	 *		- Manager::authorize()
4264
	 *		- Manager::get_token()
4265
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4266
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4267
	 *			- which responds with access_token, token_type, scope
4268
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4269
	 *		- Jetpack::activate_default_modules()
4270
	 *     		- Deactivates deprecated plugins
4271
	 *     		- Activates all default modules
4272
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4273
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4274
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4275
	 *     Done!
4276
	 */
4277
4278
	/**
4279
	 * Handles the page load events for the Jetpack admin page
4280
	 */
4281
	function admin_page_load() {
4282
		$error = false;
4283
4284
		// Make sure we have the right body class to hook stylings for subpages off of.
4285
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4286
4287
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4288
			// Should only be used in intermediate redirects to preserve state across redirects
4289
			self::restate();
4290
		}
4291
4292
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4293
			// @todo: Add validation against a known allowed list.
4294
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4295
			// User clicked in the iframe to link their accounts
4296
			if ( ! self::is_user_connected() ) {
4297
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4298
4299
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4300
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4301
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4302
4303
				if ( isset( $_GET['notes_iframe'] ) ) {
4304
					$connect_url .= '&notes_iframe';
4305
				}
4306
				wp_redirect( $connect_url );
4307
				exit;
4308
			} else {
4309
				if ( ! isset( $_GET['calypso_env'] ) ) {
4310
					self::state( 'message', 'already_authorized' );
4311
					wp_safe_redirect( self::admin_url() );
4312
					exit;
4313
				} else {
4314
					$connect_url  = $this->build_connect_url( true, false, $from );
4315
					$connect_url .= '&already_authorized=true';
4316
					wp_redirect( $connect_url );
4317
					exit;
4318
				}
4319
			}
4320
		}
4321
4322
		if ( isset( $_GET['action'] ) ) {
4323
			switch ( $_GET['action'] ) {
4324
				case 'authorize':
4325
					if ( self::is_active() && self::is_user_connected() ) {
4326
						self::state( 'message', 'already_authorized' );
4327
						wp_safe_redirect( self::admin_url() );
4328
						exit;
4329
					}
4330
					self::log( 'authorize' );
4331
					$client_server = new Jetpack_Client_Server();
4332
					$client_server->client_authorize();
4333
					exit;
4334
				case 'register':
4335
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4336
						$error = 'cheatin';
4337
						break;
4338
					}
4339
					check_admin_referer( 'jetpack-register' );
4340
					self::log( 'register' );
4341
					self::maybe_set_version_option();
4342
					$registered = self::try_registration();
4343 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4344
						$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4345
						self::state( 'error', $error );
4346
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4347
4348
						/**
4349
						 * Jetpack registration Error.
4350
						 *
4351
						 * @since 7.5.0
4352
						 *
4353
						 * @param string|int $error The error code.
4354
						 * @param \WP_Error $registered The error object.
4355
						 */
4356
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4357
						break;
4358
					}
4359
4360
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4361
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4362
4363
					/**
4364
					 * Jetpack registration Success.
4365
					 *
4366
					 * @since 7.5.0
4367
					 *
4368
					 * @param string $from 'from' GET parameter;
4369
					 */
4370
					do_action( 'jetpack_connection_register_success', $from );
4371
4372
					$url = $this->build_connect_url( true, $redirect, $from );
4373
4374
					if ( ! empty( $_GET['onboarding'] ) ) {
4375
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4376
					}
4377
4378
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4379
						$url = add_query_arg( 'auth_approved', 'true', $url );
4380
					}
4381
4382
					wp_redirect( $url );
4383
					exit;
4384
				case 'activate':
4385
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4386
						$error = 'cheatin';
4387
						break;
4388
					}
4389
4390
					$module = stripslashes( $_GET['module'] );
4391
					check_admin_referer( "jetpack_activate-$module" );
4392
					self::log( 'activate', $module );
4393
					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...
4394
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4395
					}
4396
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4397
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4398
					exit;
4399
				case 'activate_default_modules':
4400
					check_admin_referer( 'activate_default_modules' );
4401
					self::log( 'activate_default_modules' );
4402
					self::restate();
4403
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4404
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4405
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4406
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4407
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4408
					exit;
4409
				case 'disconnect':
4410
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4411
						$error = 'cheatin';
4412
						break;
4413
					}
4414
4415
					check_admin_referer( 'jetpack-disconnect' );
4416
					self::log( 'disconnect' );
4417
					self::disconnect();
4418
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4419
					exit;
4420
				case 'reconnect':
4421
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4422
						$error = 'cheatin';
4423
						break;
4424
					}
4425
4426
					check_admin_referer( 'jetpack-reconnect' );
4427
					self::log( 'reconnect' );
4428
					$this->disconnect();
4429
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4430
					exit;
4431 View Code Duplication
				case 'deactivate':
4432
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4433
						$error = 'cheatin';
4434
						break;
4435
					}
4436
4437
					$modules = stripslashes( $_GET['module'] );
4438
					check_admin_referer( "jetpack_deactivate-$modules" );
4439
					foreach ( explode( ',', $modules ) as $module ) {
4440
						self::log( 'deactivate', $module );
4441
						self::deactivate_module( $module );
4442
						self::state( 'message', 'module_deactivated' );
4443
					}
4444
					self::state( 'module', $modules );
4445
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4446
					exit;
4447
				case 'unlink':
4448
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4449
					check_admin_referer( 'jetpack-unlink' );
4450
					self::log( 'unlink' );
4451
					Connection_Manager::disconnect_user();
4452
					self::state( 'message', 'unlinked' );
4453
					if ( 'sub-unlink' == $redirect ) {
4454
						wp_safe_redirect( admin_url() );
4455
					} else {
4456
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4457
					}
4458
					exit;
4459
				case 'onboard':
4460
					if ( ! current_user_can( 'manage_options' ) ) {
4461
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4462
					} else {
4463
						self::create_onboarding_token();
4464
						$url = $this->build_connect_url( true );
4465
4466
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4467
							$url = add_query_arg( 'onboarding', $token, $url );
4468
						}
4469
4470
						$calypso_env = $this->get_calypso_env();
4471
						if ( ! empty( $calypso_env ) ) {
4472
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4473
						}
4474
4475
						wp_redirect( $url );
4476
						exit;
4477
					}
4478
					exit;
4479
				default:
4480
					/**
4481
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4482
					 *
4483
					 * @since 2.6.0
4484
					 *
4485
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4486
					 */
4487
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4488
			}
4489
		}
4490
4491
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4492
			self::activate_new_modules( true );
4493
		}
4494
4495
		$message_code = self::state( 'message' );
4496
		if ( self::state( 'optin-manage' ) ) {
4497
			$activated_manage = $message_code;
4498
			$message_code     = 'jetpack-manage';
4499
		}
4500
4501
		switch ( $message_code ) {
4502
			case 'jetpack-manage':
4503
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4504
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4505
				$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>';
4506
				if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4507
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4508
				}
4509
				break;
4510
4511
		}
4512
4513
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4514
4515
		if ( ! empty( $deactivated_plugins ) ) {
4516
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4517
			$deactivated_titles  = array();
4518
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4519
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4520
					continue;
4521
				}
4522
4523
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4524
			}
4525
4526
			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...
4527
				if ( $this->message ) {
4528
					$this->message .= "<br /><br />\n";
4529
				}
4530
4531
				$this->message .= wp_sprintf(
4532
					_n(
4533
						'Jetpack contains the most recent version of the old %l plugin.',
4534
						'Jetpack contains the most recent versions of the old %l plugins.',
4535
						count( $deactivated_titles ),
4536
						'jetpack'
4537
					),
4538
					$deactivated_titles
4539
				);
4540
4541
				$this->message .= "<br />\n";
4542
4543
				$this->message .= _n(
4544
					'The old version has been deactivated and can be removed from your site.',
4545
					'The old versions have been deactivated and can be removed from your site.',
4546
					count( $deactivated_titles ),
4547
					'jetpack'
4548
				);
4549
			}
4550
		}
4551
4552
		$this->privacy_checks = self::state( 'privacy_checks' );
4553
4554
		if ( $this->message || $this->error || $this->privacy_checks ) {
4555
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4556
		}
4557
4558
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4559
	}
4560
4561
	function admin_notices() {
4562
4563
		if ( $this->error ) {
4564
			?>
4565
<div id="message" class="jetpack-message jetpack-err">
4566
	<div class="squeezer">
4567
		<h2>
4568
			<?php
4569
			echo wp_kses(
4570
				$this->error,
4571
				array(
4572
					'a'      => array( 'href' => array() ),
4573
					'small'  => true,
4574
					'code'   => true,
4575
					'strong' => true,
4576
					'br'     => true,
4577
					'b'      => true,
4578
				)
4579
			);
4580
			?>
4581
			</h2>
4582
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4583
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4584
<?php	endif; ?>
4585
	</div>
4586
</div>
4587
			<?php
4588
		}
4589
4590
		if ( $this->message ) {
4591
			?>
4592
<div id="message" class="jetpack-message">
4593
	<div class="squeezer">
4594
		<h2>
4595
			<?php
4596
			echo wp_kses(
4597
				$this->message,
4598
				array(
4599
					'strong' => array(),
4600
					'a'      => array( 'href' => true ),
4601
					'br'     => true,
4602
				)
4603
			);
4604
			?>
4605
			</h2>
4606
	</div>
4607
</div>
4608
			<?php
4609
		}
4610
4611
		if ( $this->privacy_checks ) :
4612
			$module_names = $module_slugs = array();
4613
4614
			$privacy_checks = explode( ',', $this->privacy_checks );
4615
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4616
			foreach ( $privacy_checks as $module_slug ) {
4617
				$module = self::get_module( $module_slug );
4618
				if ( ! $module ) {
4619
					continue;
4620
				}
4621
4622
				$module_slugs[] = $module_slug;
4623
				$module_names[] = "<strong>{$module['name']}</strong>";
4624
			}
4625
4626
			$module_slugs = join( ',', $module_slugs );
4627
			?>
4628
<div id="message" class="jetpack-message jetpack-err">
4629
	<div class="squeezer">
4630
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4631
		<p>
4632
			<?php
4633
			echo wp_kses(
4634
				wptexturize(
4635
					wp_sprintf(
4636
						_nx(
4637
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4638
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4639
							count( $privacy_checks ),
4640
							'%l = list of Jetpack module/feature names',
4641
							'jetpack'
4642
						),
4643
						$module_names
4644
					)
4645
				),
4646
				array( 'strong' => true )
4647
			);
4648
4649
			echo "\n<br />\n";
4650
4651
			echo wp_kses(
4652
				sprintf(
4653
					_nx(
4654
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4655
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4656
						count( $privacy_checks ),
4657
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4658
						'jetpack'
4659
					),
4660
					wp_nonce_url(
4661
						self::admin_url(
4662
							array(
4663
								'page'   => 'jetpack',
4664
								'action' => 'deactivate',
4665
								'module' => urlencode( $module_slugs ),
4666
							)
4667
						),
4668
						"jetpack_deactivate-$module_slugs"
4669
					),
4670
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4671
				),
4672
				array(
4673
					'a' => array(
4674
						'href'  => true,
4675
						'title' => true,
4676
					),
4677
				)
4678
			);
4679
			?>
4680
		</p>
4681
	</div>
4682
</div>
4683
			<?php
4684
endif;
4685
	}
4686
4687
	/**
4688
	 * We can't always respond to a signed XML-RPC request with a
4689
	 * helpful error message. In some circumstances, doing so could
4690
	 * leak information.
4691
	 *
4692
	 * Instead, track that the error occurred via a Jetpack_Option,
4693
	 * and send that data back in the heartbeat.
4694
	 * All this does is increment a number, but it's enough to find
4695
	 * trends.
4696
	 *
4697
	 * @param WP_Error $xmlrpc_error The error produced during
4698
	 *                               signature validation.
4699
	 */
4700
	function track_xmlrpc_error( $xmlrpc_error ) {
4701
		$code = is_wp_error( $xmlrpc_error )
4702
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
4703
			: 'should-not-happen';
4704
4705
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4706
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4707
			// No need to update the option if we already have
4708
			// this code stored.
4709
			return;
4710
		}
4711
		$xmlrpc_errors[ $code ] = true;
4712
4713
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4714
	}
4715
4716
	/**
4717
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4718
	 */
4719
	function stat( $group, $detail ) {
4720
		if ( ! isset( $this->stats[ $group ] ) ) {
4721
			$this->stats[ $group ] = array();
4722
		}
4723
		$this->stats[ $group ][] = $detail;
4724
	}
4725
4726
	/**
4727
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4728
	 */
4729
	function do_stats( $method = '' ) {
4730
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4731
			foreach ( $this->stats as $group => $stats ) {
4732
				if ( is_array( $stats ) && count( $stats ) ) {
4733
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4734
					if ( 'server_side' === $method ) {
4735
						self::do_server_side_stat( $args );
4736
					} else {
4737
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4738
					}
4739
				}
4740
				unset( $this->stats[ $group ] );
4741
			}
4742
		}
4743
	}
4744
4745
	/**
4746
	 * Runs stats code for a one-off, server-side.
4747
	 *
4748
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4749
	 *
4750
	 * @return bool If it worked.
4751
	 */
4752
	static function do_server_side_stat( $args ) {
4753
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4754
		if ( is_wp_error( $response ) ) {
4755
			return false;
4756
		}
4757
4758
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4759
			return false;
4760
		}
4761
4762
		return true;
4763
	}
4764
4765
	/**
4766
	 * Builds the stats url.
4767
	 *
4768
	 * @param $args array|string The arguments to append to the URL.
4769
	 *
4770
	 * @return string The URL to be pinged.
4771
	 */
4772
	static function build_stats_url( $args ) {
4773
		$defaults = array(
4774
			'v'    => 'wpcom2',
4775
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4776
		);
4777
		$args     = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$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...
4778
		/**
4779
		 * Filter the URL used as the Stats tracking pixel.
4780
		 *
4781
		 * @since 2.3.2
4782
		 *
4783
		 * @param string $url Base URL used as the Stats tracking pixel.
4784
		 */
4785
		$base_url = apply_filters(
4786
			'jetpack_stats_base_url',
4787
			'https://pixel.wp.com/g.gif'
4788
		);
4789
		$url      = add_query_arg( $args, $base_url );
4790
		return $url;
4791
	}
4792
4793
	/**
4794
	 * Get the role of the current user.
4795
	 *
4796
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4797
	 *
4798
	 * @access public
4799
	 * @static
4800
	 *
4801
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4802
	 */
4803
	public static function translate_current_user_to_role() {
4804
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4805
4806
		$roles = new Roles();
4807
		return $roles->translate_current_user_to_role();
4808
	}
4809
4810
	/**
4811
	 * Get the role of a particular user.
4812
	 *
4813
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4814
	 *
4815
	 * @access public
4816
	 * @static
4817
	 *
4818
	 * @param \WP_User $user User object.
4819
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4820
	 */
4821
	public static function translate_user_to_role( $user ) {
4822
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4823
4824
		$roles = new Roles();
4825
		return $roles->translate_user_to_role( $user );
4826
	}
4827
4828
	/**
4829
	 * Get the minimum capability for a role.
4830
	 *
4831
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4832
	 *
4833
	 * @access public
4834
	 * @static
4835
	 *
4836
	 * @param string $role Role name.
4837
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4838
	 */
4839
	public static function translate_role_to_cap( $role ) {
4840
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4841
4842
		$roles = new Roles();
4843
		return $roles->translate_role_to_cap( $role );
4844
	}
4845
4846
	/**
4847
	 * Sign a user role with the master access token.
4848
	 * If not specified, will default to the current user.
4849
	 *
4850
	 * @deprecated since 7.7
4851
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4852
	 *
4853
	 * @access public
4854
	 * @static
4855
	 *
4856
	 * @param string $role    User role.
4857
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
4858
	 * @return string Signed user role.
4859
	 */
4860
	public static function sign_role( $role, $user_id = null ) {
4861
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4862
		return self::connection()->sign_role( $role, $user_id );
4863
	}
4864
4865
	/**
4866
	 * Builds a URL to the Jetpack connection auth page
4867
	 *
4868
	 * @since 3.9.5
4869
	 *
4870
	 * @param bool        $raw If true, URL will not be escaped.
4871
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4872
	 *                              If string, will be a custom redirect.
4873
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4874
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4875
	 *
4876
	 * @return string Connect URL
4877
	 */
4878
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4879
		$site_id    = Jetpack_Options::get_option( 'id' );
4880
		$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...
4881
4882
		if ( $register || ! $blog_token || ! $site_id ) {
4883
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4884
4885
			if ( ! empty( $redirect ) ) {
4886
				$url = add_query_arg(
4887
					'redirect',
4888
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4889
					$url
4890
				);
4891
			}
4892
4893
			if ( is_network_admin() ) {
4894
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4895
			}
4896
4897
			$calypso_env = self::get_calypso_env();
4898
4899
			if ( ! empty( $calypso_env ) ) {
4900
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4901
			}
4902
		} else {
4903
4904
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4905
			// because otherwise this logic can get us in to a loop.
4906
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4907
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4908
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4909
4910
				$response = Client::wpcom_json_api_request_as_blog(
4911
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4912
					'1.1'
4913
				);
4914
4915
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4916
4917
					// Generating a register URL instead to refresh the existing token
4918
					return $this->build_connect_url( $raw, $redirect, $from, true );
4919
				}
4920
			}
4921
4922
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4878 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...
4923
		}
4924
4925
		if ( $from ) {
4926
			$url = add_query_arg( 'from', $from, $url );
4927
		}
4928
4929
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4930
		/**
4931
		 * Filter the URL used when connecting a user to a WordPress.com account.
4932
		 *
4933
		 * @since 8.1.0
4934
		 *
4935
		 * @param string $url Connection URL.
4936
		 * @param bool   $raw If true, URL will not be escaped.
4937
		 */
4938
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

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

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

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

Loading history...
4939
	}
4940
4941
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4942
4943
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4944
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4945
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4946
4947
		if ( $iframe ) {
4948
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4949
		}
4950
4951
		$c8n = self::connection();
4952
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4953
4954
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4955
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4956
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4957
4958
		if ( $iframe ) {
4959
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4960
		}
4961
4962
		return $url;
4963
	}
4964
4965
	/**
4966
	 * Filters the connection URL parameter array.
4967
	 *
4968
	 * @param array $args default URL parameters used by the package.
4969
	 * @return array the modified URL arguments array.
4970
	 */
4971
	public static function filter_connect_request_body( $args ) {
4972
		if (
4973
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4974
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4975
		) {
4976
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4977
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4978
				? $gp_locale->slug
4979
				: '';
4980
		}
4981
4982
		$tracking        = new Tracking();
4983
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4984
4985
		$args = array_merge(
4986
			$args,
4987
			array(
4988
				'_ui' => $tracks_identity['_ui'],
4989
				'_ut' => $tracks_identity['_ut'],
4990
			)
4991
		);
4992
4993
		$calypso_env = self::get_calypso_env();
4994
4995
		if ( ! empty( $calypso_env ) ) {
4996
			$args['calypso_env'] = $calypso_env;
4997
		}
4998
4999
		return $args;
5000
	}
5001
5002
	/**
5003
	 * Filters the URL that will process the connection data. It can be different from the URL
5004
	 * that we send the user to after everything is done.
5005
	 *
5006
	 * @param String $processing_url the default redirect URL used by the package.
5007
	 * @return String the modified URL.
5008
	 */
5009
	public static function filter_connect_processing_url( $processing_url ) {
5010
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
5011
		return $processing_url;
5012
	}
5013
5014
	/**
5015
	 * Filters the redirection URL that is used for connect requests. The redirect
5016
	 * URL should return the user back to the Jetpack console.
5017
	 *
5018
	 * @param String $redirect the default redirect URL used by the package.
5019
	 * @return String the modified URL.
5020
	 */
5021
	public static function filter_connect_redirect_url( $redirect ) {
5022
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
5023
		$redirect           = $redirect
5024
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
5025
			: $jetpack_admin_page;
5026
5027
		if ( isset( $_REQUEST['is_multisite'] ) ) {
5028
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5029
		}
5030
5031
		return $redirect;
5032
	}
5033
5034
	/**
5035
	 * This action fires at the beginning of the Manager::authorize method.
5036
	 */
5037
	public static function authorize_starting() {
5038
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5039
		// Checking if site has been active/connected previously before recording unique connection.
5040
		if ( ! $jetpack_unique_connection ) {
5041
			// jetpack_unique_connection option has never been set.
5042
			$jetpack_unique_connection = array(
5043
				'connected'    => 0,
5044
				'disconnected' => 0,
5045
				'version'      => '3.6.1',
5046
			);
5047
5048
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5049
5050
			// Track unique connection.
5051
			$jetpack = self::init();
5052
5053
			$jetpack->stat( 'connections', 'unique-connection' );
5054
			$jetpack->do_stats( 'server_side' );
5055
		}
5056
5057
		// Increment number of times connected.
5058
		$jetpack_unique_connection['connected'] += 1;
5059
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5060
	}
5061
5062
	/**
5063
	 * This action fires at the end of the Manager::authorize method when a secondary user is
5064
	 * linked.
5065
	 */
5066
	public static function authorize_ending_linked() {
5067
		// Don't activate anything since we are just connecting a user.
5068
		self::state( 'message', 'linked' );
5069
	}
5070
5071
	/**
5072
	 * This action fires at the end of the Manager::authorize method when the master user is
5073
	 * authorized.
5074
	 *
5075
	 * @param array $data The request data.
5076
	 */
5077
	public static function authorize_ending_authorized( $data ) {
5078
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5079
		self::invalidate_onboarding_token();
5080
5081
		// If redirect_uri is SSO, ensure SSO module is enabled.
5082
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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

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

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

Loading history...
5083
5084
		/** This filter is documented in class.jetpack-cli.php */
5085
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5086
5087
		$activate_sso = (
5088
			isset( $redirect_options['action'] ) &&
5089
			'jetpack-sso' === $redirect_options['action'] &&
5090
			$jetpack_start_enable_sso
5091
		);
5092
5093
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5094
5095
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5096
	}
5097
5098
	/**
5099
	 * Get our assumed site creation date.
5100
	 * Calculated based on the earlier date of either:
5101
	 * - Earliest admin user registration date.
5102
	 * - Earliest date of post of any post type.
5103
	 *
5104
	 * @since 7.2.0
5105
	 * @deprecated since 7.8.0
5106
	 *
5107
	 * @return string Assumed site creation date and time.
5108
	 */
5109
	public static function get_assumed_site_creation_date() {
5110
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5111
		return self::connection()->get_assumed_site_creation_date();
5112
	}
5113
5114 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5115
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5116
5117
		if ( $activation_source_name ) {
5118
			$args['_as'] = urlencode( $activation_source_name );
5119
		}
5120
5121
		if ( $activation_source_keyword ) {
5122
			$args['_ak'] = urlencode( $activation_source_keyword );
5123
		}
5124
	}
5125
5126
	function build_reconnect_url( $raw = false ) {
5127
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5128
		return $raw ? $url : esc_url( $url );
5129
	}
5130
5131
	public static function admin_url( $args = null ) {
5132
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
5133
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5134
		return $url;
5135
	}
5136
5137
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5138
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5139
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5140
	}
5141
5142
	function dismiss_jetpack_notice() {
5143
5144
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5145
			return;
5146
		}
5147
5148
		switch ( $_GET['jetpack-notice'] ) {
5149
			case 'dismiss':
5150
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5151
5152
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5153
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5154
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5155
				}
5156
				break;
5157
		}
5158
	}
5159
5160
	public static function sort_modules( $a, $b ) {
5161
		if ( $a['sort'] == $b['sort'] ) {
5162
			return 0;
5163
		}
5164
5165
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5166
	}
5167
5168
	function ajax_recheck_ssl() {
5169
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5170
		$result = self::permit_ssl( true );
5171
		wp_send_json(
5172
			array(
5173
				'enabled' => $result,
5174
				'message' => get_transient( 'jetpack_https_test_message' ),
5175
			)
5176
		);
5177
	}
5178
5179
	/* Client API */
5180
5181
	/**
5182
	 * Returns the requested Jetpack API URL
5183
	 *
5184
	 * @deprecated since 7.7
5185
	 * @return string
5186
	 */
5187
	public static function api_url( $relative_url ) {
5188
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5189
		$connection = self::connection();
5190
		return $connection->api_url( $relative_url );
5191
	}
5192
5193
	/**
5194
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5195
	 *
5196
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5197
	 */
5198
	public static function fix_url_for_bad_hosts( $url ) {
5199
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5200
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5201
	}
5202
5203
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5204
		// Default to a blog token.
5205
		$token_type = 'blog';
5206
5207
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5208
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5209
			if ( ! empty( $_GET['onboarding'] ) ) {
5210
				$jpo = $_GET;
5211
			} else {
5212
				$jpo = json_decode( $request_data, true );
5213
			}
5214
5215
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5216
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5217
5218
			if (
5219
				isset( $jpo_user )
5220
				&& isset( $jpo_token )
5221
				&& is_email( $jpo_user )
5222
				&& ctype_alnum( $jpo_token )
5223
				&& isset( $_GET['rest_route'] )
5224
				&& self::validate_onboarding_token_action(
5225
					$jpo_token,
5226
					$_GET['rest_route']
5227
				)
5228
			) {
5229
				$jp_user = get_user_by( 'email', $jpo_user );
5230
				if ( is_a( $jp_user, 'WP_User' ) ) {
5231
					wp_set_current_user( $jp_user->ID );
5232
					$user_can = is_multisite()
5233
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5234
						: current_user_can( 'manage_options' );
5235
					if ( $user_can ) {
5236
						$token_type              = 'user';
5237
						$token->external_user_id = $jp_user->ID;
5238
					}
5239
				}
5240
			}
5241
5242
			$token_data['type']    = $token_type;
5243
			$token_data['user_id'] = $token->external_user_id;
5244
		}
5245
5246
		return $token_data;
5247
	}
5248
5249
	/**
5250
	 * Create a random secret for validating onboarding payload
5251
	 *
5252
	 * @return string Secret token
5253
	 */
5254
	public static function create_onboarding_token() {
5255
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5256
			$token = wp_generate_password( 32, false );
5257
			Jetpack_Options::update_option( 'onboarding', $token );
5258
		}
5259
5260
		return $token;
5261
	}
5262
5263
	/**
5264
	 * Remove the onboarding token
5265
	 *
5266
	 * @return bool True on success, false on failure
5267
	 */
5268
	public static function invalidate_onboarding_token() {
5269
		return Jetpack_Options::delete_option( 'onboarding' );
5270
	}
5271
5272
	/**
5273
	 * Validate an onboarding token for a specific action
5274
	 *
5275
	 * @return boolean True if token/action pair is accepted, false if not
5276
	 */
5277
	public static function validate_onboarding_token_action( $token, $action ) {
5278
		// Compare tokens, bail if tokens do not match
5279
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5280
			return false;
5281
		}
5282
5283
		// List of valid actions we can take
5284
		$valid_actions = array(
5285
			'/jetpack/v4/settings',
5286
		);
5287
5288
		// Only allow valid actions.
5289
		if ( ! in_array( $action, $valid_actions ) ) {
5290
			return false;
5291
		}
5292
5293
		return true;
5294
	}
5295
5296
	/**
5297
	 * Checks to see if the URL is using SSL to connect with Jetpack
5298
	 *
5299
	 * @since 2.3.3
5300
	 * @return boolean
5301
	 */
5302
	public static function permit_ssl( $force_recheck = false ) {
5303
		// Do some fancy tests to see if ssl is being supported
5304
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5305
			$message = '';
5306
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5307
				$ssl = 0;
5308
			} else {
5309
				switch ( JETPACK_CLIENT__HTTPS ) {
5310
					case 'NEVER':
5311
						$ssl     = 0;
5312
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5313
						break;
5314
					case 'ALWAYS':
5315
					case 'AUTO':
5316
					default:
5317
						$ssl = 1;
5318
						break;
5319
				}
5320
5321
				// If it's not 'NEVER', test to see
5322
				if ( $ssl ) {
5323
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5324
						$ssl     = 0;
5325
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5326
					} else {
5327
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5328
						if ( is_wp_error( $response ) ) {
5329
							$ssl     = 0;
5330
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5331
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5332
							$ssl     = 0;
5333
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5334
						}
5335
					}
5336
				}
5337
			}
5338
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5339
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5340
		}
5341
5342
		return (bool) $ssl;
5343
	}
5344
5345
	/*
5346
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5347
	 */
5348
	public function alert_auto_ssl_fail() {
5349
		if ( ! current_user_can( 'manage_options' ) ) {
5350
			return;
5351
		}
5352
5353
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5354
		?>
5355
5356
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5357
			<div class="jp-banner__content">
5358
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5359
				<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>
5360
				<p>
5361
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5362
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5363
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5364
				</p>
5365
				<p>
5366
					<?php
5367
					printf(
5368
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5369
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5370
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5371
					);
5372
					?>
5373
				</p>
5374
			</div>
5375
		</div>
5376
		<style>
5377
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5378
		</style>
5379
		<script type="text/javascript">
5380
			jQuery( document ).ready( function( $ ) {
5381
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5382
					var $this = $( this );
5383
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5384
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5385
					e.preventDefault();
5386
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5387
					$.post( ajaxurl, data )
5388
					  .done( function( response ) {
5389
						  if ( response.enabled ) {
5390
							  $( '#jetpack-ssl-warning' ).hide();
5391
						  } else {
5392
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5393
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5394
						  }
5395
					  }.bind( $this ) );
5396
				} );
5397
			} );
5398
		</script>
5399
5400
		<?php
5401
	}
5402
5403
	/**
5404
	 * Returns the Jetpack XML-RPC API
5405
	 *
5406
	 * @deprecated 8.0 Use Connection_Manager instead.
5407
	 * @return string
5408
	 */
5409
	public static function xmlrpc_api_url() {
5410
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5411
		return self::connection()->xmlrpc_api_url();
5412
	}
5413
5414
	/**
5415
	 * Returns the connection manager object.
5416
	 *
5417
	 * @return Automattic\Jetpack\Connection\Manager
5418
	 */
5419
	public static function connection() {
5420
		$jetpack = static::init();
5421
5422
		// If the connection manager hasn't been instantiated, do that now.
5423
		if ( ! $jetpack->connection_manager ) {
5424
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5425
		}
5426
5427
		return $jetpack->connection_manager;
5428
	}
5429
5430
	/**
5431
	 * Creates two secret tokens and the end of life timestamp for them.
5432
	 *
5433
	 * Note these tokens are unique per call, NOT static per site for connecting.
5434
	 *
5435
	 * @since 2.6
5436
	 * @param String  $action  The action name.
5437
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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

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

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

Loading history...
5438
	 * @param Integer $exp     Expiration time in seconds.
5439
	 * @return array
5440
	 */
5441
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5442
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5443
	}
5444
5445
	public static function get_secrets( $action, $user_id ) {
5446
		$secrets = self::connection()->get_secrets( $action, $user_id );
5447
5448
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5449
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

Loading history...
5450
		}
5451
5452
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5453
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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

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

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

Loading history...
5454
		}
5455
5456
		return $secrets;
5457
	}
5458
5459
	/**
5460
	 * @deprecated 7.5 Use Connection_Manager instead.
5461
	 *
5462
	 * @param $action
5463
	 * @param $user_id
5464
	 */
5465
	public static function delete_secrets( $action, $user_id ) {
5466
		return self::connection()->delete_secrets( $action, $user_id );
5467
	}
5468
5469
	/**
5470
	 * Builds the timeout limit for queries talking with the wpcom servers.
5471
	 *
5472
	 * Based on local php max_execution_time in php.ini
5473
	 *
5474
	 * @since 2.6
5475
	 * @return int
5476
	 * @deprecated
5477
	 **/
5478
	public function get_remote_query_timeout_limit() {
5479
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5480
		return self::get_max_execution_time();
5481
	}
5482
5483
	/**
5484
	 * Builds the timeout limit for queries talking with the wpcom servers.
5485
	 *
5486
	 * Based on local php max_execution_time in php.ini
5487
	 *
5488
	 * @since 5.4
5489
	 * @return int
5490
	 **/
5491
	public static function get_max_execution_time() {
5492
		$timeout = (int) ini_get( 'max_execution_time' );
5493
5494
		// Ensure exec time set in php.ini
5495
		if ( ! $timeout ) {
5496
			$timeout = 30;
5497
		}
5498
		return $timeout;
5499
	}
5500
5501
	/**
5502
	 * Sets a minimum request timeout, and returns the current timeout
5503
	 *
5504
	 * @since 5.4
5505
	 **/
5506 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5507
		$timeout = self::get_max_execution_time();
5508
		if ( $timeout < $min_timeout ) {
5509
			$timeout = $min_timeout;
5510
			set_time_limit( $timeout );
5511
		}
5512
		return $timeout;
5513
	}
5514
5515
	/**
5516
	 * Takes the response from the Jetpack register new site endpoint and
5517
	 * verifies it worked properly.
5518
	 *
5519
	 * @since 2.6
5520
	 * @deprecated since 7.7.0
5521
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5522
	 **/
5523
	public function validate_remote_register_response() {
5524
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5525
	}
5526
5527
	/**
5528
	 * @return bool|WP_Error
5529
	 */
5530
	public static function register() {
5531
		$tracking = new Tracking();
5532
		$tracking->record_user_event( 'jpc_register_begin' );
5533
5534
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5535
5536
		$connection   = self::connection();
5537
		$registration = $connection->register();
5538
5539
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5540
5541
		if ( ! $registration || is_wp_error( $registration ) ) {
5542
			return $registration;
5543
		}
5544
5545
		return true;
5546
	}
5547
5548
	/**
5549
	 * Filters the registration request body to include tracking properties.
5550
	 *
5551
	 * @param array $properties
5552
	 * @return array amended properties.
5553
	 */
5554 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5555
		$tracking        = new Tracking();
5556
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5557
5558
		return array_merge(
5559
			$properties,
5560
			array(
5561
				'_ui' => $tracks_identity['_ui'],
5562
				'_ut' => $tracks_identity['_ut'],
5563
			)
5564
		);
5565
	}
5566
5567
	/**
5568
	 * Filters the token request body to include tracking properties.
5569
	 *
5570
	 * @param array $properties
5571
	 * @return array amended properties.
5572
	 */
5573 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5574
		$tracking        = new Tracking();
5575
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5576
5577
		return array_merge(
5578
			$properties,
5579
			array(
5580
				'_ui' => $tracks_identity['_ui'],
5581
				'_ut' => $tracks_identity['_ut'],
5582
			)
5583
		);
5584
	}
5585
5586
	/**
5587
	 * If the db version is showing something other that what we've got now, bump it to current.
5588
	 *
5589
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5590
	 */
5591
	public static function maybe_set_version_option() {
5592
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5593
		if ( JETPACK__VERSION != $version ) {
5594
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5595
5596
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5597
				/** This action is documented in class.jetpack.php */
5598
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5599
			}
5600
5601
			return true;
5602
		}
5603
		return false;
5604
	}
5605
5606
	/* Client Server API */
5607
5608
	/**
5609
	 * Loads the Jetpack XML-RPC client.
5610
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5611
	 *
5612
	 * @deprecated since 7.7.0
5613
	 */
5614
	public static function load_xml_rpc_client() {
5615
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5616
	}
5617
5618
	/**
5619
	 * Resets the saved authentication state in between testing requests.
5620
	 */
5621
	public function reset_saved_auth_state() {
5622
		$this->rest_authentication_status = null;
5623
5624
		if ( ! $this->connection_manager ) {
5625
			$this->connection_manager = new Connection_Manager();
5626
		}
5627
5628
		$this->connection_manager->reset_saved_auth_state();
5629
	}
5630
5631
	/**
5632
	 * Verifies the signature of the current request.
5633
	 *
5634
	 * @deprecated since 7.7.0
5635
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5636
	 *
5637
	 * @return false|array
5638
	 */
5639
	public function verify_xml_rpc_signature() {
5640
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5641
		return self::connection()->verify_xml_rpc_signature();
5642
	}
5643
5644
	/**
5645
	 * Verifies the signature of the current request.
5646
	 *
5647
	 * This function has side effects and should not be used. Instead,
5648
	 * use the memoized version `->verify_xml_rpc_signature()`.
5649
	 *
5650
	 * @deprecated since 7.7.0
5651
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5652
	 * @internal
5653
	 */
5654
	private function internal_verify_xml_rpc_signature() {
5655
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5656
	}
5657
5658
	/**
5659
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5660
	 *
5661
	 * @deprecated since 7.7.0
5662
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5663
	 *
5664
	 * @param \WP_User|mixed $user     User object if authenticated.
5665
	 * @param string         $username Username.
5666
	 * @param string         $password Password string.
5667
	 * @return \WP_User|mixed Authenticated user or error.
5668
	 */
5669 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5670
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5671
5672
		if ( ! $this->connection_manager ) {
5673
			$this->connection_manager = new Connection_Manager();
5674
		}
5675
5676
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5677
	}
5678
5679
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5680
	// Uses the existing XMLRPC request signing implementation.
5681
	function wp_rest_authenticate( $user ) {
5682
		if ( ! empty( $user ) ) {
5683
			// Another authentication method is in effect.
5684
			return $user;
5685
		}
5686
5687
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5688
			// Nothing to do for this authentication method.
5689
			return null;
5690
		}
5691
5692
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5693
			// Nothing to do for this authentication method.
5694
			return null;
5695
		}
5696
5697
		// Ensure that we always have the request body available.  At this
5698
		// point, the WP REST API code to determine the request body has not
5699
		// run yet.  That code may try to read from 'php://input' later, but
5700
		// this can only be done once per request in PHP versions prior to 5.6.
5701
		// So we will go ahead and perform this read now if needed, and save
5702
		// the request body where both the Jetpack signature verification code
5703
		// and the WP REST API code can see it.
5704
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5705
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5706
		}
5707
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5708
5709
		// Only support specific request parameters that have been tested and
5710
		// are known to work with signature verification.  A different method
5711
		// can be passed to the WP REST API via the '?_method=' parameter if
5712
		// needed.
5713
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5714
			$this->rest_authentication_status = new WP_Error(
5715
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5716
				__( 'This request method is not supported.', 'jetpack' ),
5717
				array( 'status' => 400 )
5718
			);
5719
			return null;
5720
		}
5721
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5722
			$this->rest_authentication_status = new WP_Error(
5723
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5724
				__( 'This request method does not support body parameters.', 'jetpack' ),
5725
				array( 'status' => 400 )
5726
			);
5727
			return null;
5728
		}
5729
5730
		if ( ! $this->connection_manager ) {
5731
			$this->connection_manager = new Connection_Manager();
5732
		}
5733
5734
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5735
5736
		if (
5737
			$verified &&
5738
			isset( $verified['type'] ) &&
5739
			'user' === $verified['type'] &&
5740
			! empty( $verified['user_id'] )
5741
		) {
5742
			// Authentication successful.
5743
			$this->rest_authentication_status = true;
5744
			return $verified['user_id'];
5745
		}
5746
5747
		// Something else went wrong.  Probably a signature error.
5748
		$this->rest_authentication_status = new WP_Error(
5749
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5750
			__( 'The request is not signed correctly.', 'jetpack' ),
5751
			array( 'status' => 400 )
5752
		);
5753
		return null;
5754
	}
5755
5756
	/**
5757
	 * Report authentication status to the WP REST API.
5758
	 *
5759
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5760
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5761
	 */
5762
	public function wp_rest_authentication_errors( $value ) {
5763
		if ( $value !== null ) {
5764
			return $value;
5765
		}
5766
		return $this->rest_authentication_status;
5767
	}
5768
5769
	/**
5770
	 * Add our nonce to this request.
5771
	 *
5772
	 * @deprecated since 7.7.0
5773
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5774
	 *
5775
	 * @param int    $timestamp Timestamp of the request.
5776
	 * @param string $nonce     Nonce string.
5777
	 */
5778 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5779
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5780
5781
		if ( ! $this->connection_manager ) {
5782
			$this->connection_manager = new Connection_Manager();
5783
		}
5784
5785
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5786
	}
5787
5788
	/**
5789
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5790
	 * Capture it here so we can verify the signature later.
5791
	 *
5792
	 * @deprecated since 7.7.0
5793
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5794
	 *
5795
	 * @param array $methods XMLRPC methods.
5796
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5797
	 */
5798 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5799
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5800
5801
		if ( ! $this->connection_manager ) {
5802
			$this->connection_manager = new Connection_Manager();
5803
		}
5804
5805
		return $this->connection_manager->xmlrpc_methods( $methods );
5806
	}
5807
5808
	/**
5809
	 * Register additional public XMLRPC methods.
5810
	 *
5811
	 * @deprecated since 7.7.0
5812
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5813
	 *
5814
	 * @param array $methods Public XMLRPC methods.
5815
	 * @return array Public XMLRPC methods, with the getOptions one.
5816
	 */
5817 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5818
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5819
5820
		if ( ! $this->connection_manager ) {
5821
			$this->connection_manager = new Connection_Manager();
5822
		}
5823
5824
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5825
	}
5826
5827
	/**
5828
	 * Handles a getOptions XMLRPC method call.
5829
	 *
5830
	 * @deprecated since 7.7.0
5831
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5832
	 *
5833
	 * @param array $args method call arguments.
5834
	 * @return array an amended XMLRPC server options array.
5835
	 */
5836 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5837
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5838
5839
		if ( ! $this->connection_manager ) {
5840
			$this->connection_manager = new Connection_Manager();
5841
		}
5842
5843
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
5844
	}
5845
5846
	/**
5847
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5848
	 *
5849
	 * @deprecated since 7.7.0
5850
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5851
	 *
5852
	 * @param array $options Standard Core options.
5853
	 * @return array Amended options.
5854
	 */
5855 View Code Duplication
	public function xmlrpc_options( $options ) {
5856
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5857
5858
		if ( ! $this->connection_manager ) {
5859
			$this->connection_manager = new Connection_Manager();
5860
		}
5861
5862
		return $this->connection_manager->xmlrpc_options( $options );
5863
	}
5864
5865
	/**
5866
	 * Cleans nonces that were saved when calling ::add_nonce.
5867
	 *
5868
	 * @deprecated since 7.7.0
5869
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5870
	 *
5871
	 * @param bool $all whether to clean even non-expired nonces.
5872
	 */
5873
	public static function clean_nonces( $all = false ) {
5874
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5875
		return self::connection()->clean_nonces( $all );
5876
	}
5877
5878
	/**
5879
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5880
	 * SET: state( $key, $value );
5881
	 * GET: $value = state( $key );
5882
	 *
5883
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

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

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

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

Loading history...
5884
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

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

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

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

Loading history...
5885
	 * @param bool   $restate private
5886
	 */
5887
	public static function state( $key = null, $value = null, $restate = false ) {
5888
		static $state = array();
5889
		static $path, $domain;
5890
		if ( ! isset( $path ) ) {
5891
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5892
			$admin_url = self::admin_url();
5893
			$bits      = wp_parse_url( $admin_url );
5894
5895
			if ( is_array( $bits ) ) {
5896
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5897
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5898
			} else {
5899
				$path = $domain = null;
5900
			}
5901
		}
5902
5903
		// Extract state from cookies and delete cookies
5904
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5905
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5906
			unset( $_COOKIE['jetpackState'] );
5907
			foreach ( $yum as $k => $v ) {
0 ignored issues
show
Bug introduced by
The expression $yum of type string|array<integer,string> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5908
				if ( strlen( $v ) ) {
5909
					$state[ $k ] = $v;
5910
				}
5911
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5912
			}
5913
		}
5914
5915
		if ( $restate ) {
5916
			foreach ( $state as $k => $v ) {
5917
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5918
			}
5919
			return;
5920
		}
5921
5922
		// Get a state variable.
5923
		if ( isset( $key ) && ! isset( $value ) ) {
5924
			if ( array_key_exists( $key, $state ) ) {
5925
				return $state[ $key ];
5926
			}
5927
			return null;
5928
		}
5929
5930
		// Set a state variable.
5931
		if ( isset( $key ) && isset( $value ) ) {
5932
			if ( is_array( $value ) && isset( $value[0] ) ) {
5933
				$value = $value[0];
5934
			}
5935
			$state[ $key ] = $value;
5936
			if ( ! headers_sent() ) {
5937
				if ( self::should_set_cookie( $key ) ) {
5938
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5939
				}
5940
			}
5941
		}
5942
	}
5943
5944
	public static function restate() {
5945
		self::state( null, null, true );
5946
	}
5947
5948
	/**
5949
	 * Determines whether the jetpackState[$key] value should be added to the
5950
	 * cookie.
5951
	 *
5952
	 * @param string $key The state key.
5953
	 *
5954
	 * @return boolean Whether the value should be added to the cookie.
5955
	 */
5956
	public static function should_set_cookie( $key ) {
5957
		global $current_screen;
5958
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5959
5960
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5961
			return false;
5962
		}
5963
5964
		return true;
5965
	}
5966
5967
	public static function check_privacy( $file ) {
5968
		static $is_site_publicly_accessible = null;
5969
5970
		if ( is_null( $is_site_publicly_accessible ) ) {
5971
			$is_site_publicly_accessible = false;
5972
5973
			$rpc = new Jetpack_IXR_Client();
5974
5975
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5976
			if ( $success ) {
5977
				$response = $rpc->getResponse();
5978
				if ( $response ) {
5979
					$is_site_publicly_accessible = true;
5980
				}
5981
			}
5982
5983
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5984
		}
5985
5986
		if ( $is_site_publicly_accessible ) {
5987
			return;
5988
		}
5989
5990
		$module_slug = self::get_module_slug( $file );
5991
5992
		$privacy_checks = self::state( 'privacy_checks' );
5993
		if ( ! $privacy_checks ) {
5994
			$privacy_checks = $module_slug;
5995
		} else {
5996
			$privacy_checks .= ",$module_slug";
5997
		}
5998
5999
		self::state( 'privacy_checks', $privacy_checks );
6000
	}
6001
6002
	/**
6003
	 * Helper method for multicall XMLRPC.
6004
	 *
6005
	 * @param ...$args Args for the async_call.
6006
	 */
6007
	public static function xmlrpc_async_call( ...$args ) {
6008
		global $blog_id;
6009
		static $clients = array();
6010
6011
		$client_blog_id = is_multisite() ? $blog_id : 0;
6012
6013
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
6014
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
6015
			if ( function_exists( 'ignore_user_abort' ) ) {
6016
				ignore_user_abort( true );
6017
			}
6018
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
6019
		}
6020
6021
		if ( ! empty( $args[0] ) ) {
6022
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
6023
		} elseif ( is_multisite() ) {
6024
			foreach ( $clients as $client_blog_id => $client ) {
6025
				if ( ! $client_blog_id || empty( $client->calls ) ) {
6026
					continue;
6027
				}
6028
6029
				$switch_success = switch_to_blog( $client_blog_id, true );
6030
				if ( ! $switch_success ) {
6031
					continue;
6032
				}
6033
6034
				flush();
6035
				$client->query();
6036
6037
				restore_current_blog();
6038
			}
6039
		} else {
6040
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
6041
				flush();
6042
				$clients[0]->query();
6043
			}
6044
		}
6045
	}
6046
6047
	public static function staticize_subdomain( $url ) {
6048
6049
		// Extract hostname from URL
6050
		$host = wp_parse_url( $url, PHP_URL_HOST );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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

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

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

Loading history...
6051
6052
		// Explode hostname on '.'
6053
		$exploded_host = explode( '.', $host );
6054
6055
		// Retrieve the name and TLD
6056
		if ( count( $exploded_host ) > 1 ) {
6057
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
6058
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
6059
			// Rebuild domain excluding subdomains
6060
			$domain = $name . '.' . $tld;
6061
		} else {
6062
			$domain = $host;
6063
		}
6064
		// Array of Automattic domains.
6065
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
6066
6067
		// Return $url if not an Automattic domain.
6068
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
6069
			return $url;
6070
		}
6071
6072
		if ( is_ssl() ) {
6073
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
6074
		}
6075
6076
		srand( crc32( basename( $url ) ) );
6077
		$static_counter = rand( 0, 2 );
6078
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
6079
6080
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
6081
	}
6082
6083
	/* JSON API Authorization */
6084
6085
	/**
6086
	 * Handles the login action for Authorizing the JSON API
6087
	 */
6088
	function login_form_json_api_authorization() {
6089
		$this->verify_json_api_authorization_request();
6090
6091
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
6092
6093
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
6094
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
6095
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
6096
	}
6097
6098
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
6099
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
6100
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6101
			return $url;
6102
		}
6103
6104
		$parsed_url = wp_parse_url( $url );
6105
		$url        = strtok( $url, '?' );
6106
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
6107
		if ( ! empty( $parsed_url['query'] ) ) {
6108
			$url .= "&{$parsed_url['query']}";
6109
		}
6110
6111
		return $url;
6112
	}
6113
6114
	// Make sure the POSTed request is handled by the same action
6115
	function preserve_action_in_login_form_for_json_api_authorization() {
6116
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6117
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6118
	}
6119
6120
	// If someone logs in to approve API access, store the Access Code in usermeta
6121
	function store_json_api_authorization_token( $user_login, $user ) {
6122
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6123
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6124
		$token = wp_generate_password( 32, false );
6125
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6126
	}
6127
6128
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6129
	function allow_wpcom_public_api_domain( $domains ) {
6130
		$domains[] = 'public-api.wordpress.com';
6131
		return $domains;
6132
	}
6133
6134
	static function is_redirect_encoded( $redirect_url ) {
6135
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6136
	}
6137
6138
	// Add all wordpress.com environments to the safe redirect allowed list.
6139
	function allow_wpcom_environments( $domains ) {
6140
		$domains[] = 'wordpress.com';
6141
		$domains[] = 'wpcalypso.wordpress.com';
6142
		$domains[] = 'horizon.wordpress.com';
6143
		$domains[] = 'calypso.localhost';
6144
		return $domains;
6145
	}
6146
6147
	// Add the Access Code details to the public-api.wordpress.com redirect
6148
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6149
		return add_query_arg(
6150
			urlencode_deep(
6151
				array(
6152
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6153
					'jetpack-user-id' => (int) $user->ID,
6154
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6155
				)
6156
			),
6157
			$redirect_to
6158
		);
6159
	}
6160
6161
6162
	/**
6163
	 * Verifies the request by checking the signature
6164
	 *
6165
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6166
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6167
	 *
6168
	 * @param null|array $environment
6169
	 */
6170
	function verify_json_api_authorization_request( $environment = null ) {
6171
		$environment = is_null( $environment )
6172
			? $_REQUEST
6173
			: $environment;
6174
6175
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
6176
		$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...
6177
		if ( ! $token || empty( $token->secret ) ) {
6178
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6179
		}
6180
6181
		$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' );
6182
6183
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6184
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6185
			/**
6186
			 * Jetpack authorisation request Error.
6187
			 *
6188
			 * @since 7.5.0
6189
			 */
6190
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6191
			$die_error = sprintf(
6192
				/* translators: %s is a URL */
6193
				__( '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' ),
6194
				Redirect::get_url( 'jetpack-support-double-encoding' )
6195
			);
6196
		}
6197
6198
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6199
6200
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6201
			$signature = $jetpack_signature->sign_request(
6202
				$environment['token'],
6203
				$environment['timestamp'],
6204
				$environment['nonce'],
6205
				'',
6206
				'GET',
6207
				$environment['jetpack_json_api_original_query'],
6208
				null,
6209
				true
6210
			);
6211
		} else {
6212
			$signature = $jetpack_signature->sign_current_request(
6213
				array(
6214
					'body'   => null,
6215
					'method' => 'GET',
6216
				)
6217
			);
6218
		}
6219
6220
		if ( ! $signature ) {
6221
			wp_die( $die_error );
6222
		} elseif ( is_wp_error( $signature ) ) {
6223
			wp_die( $die_error );
6224
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6225
			if ( is_ssl() ) {
6226
				// 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
6227
				$signature = $jetpack_signature->sign_current_request(
6228
					array(
6229
						'scheme' => 'http',
6230
						'body'   => null,
6231
						'method' => 'GET',
6232
					)
6233
				);
6234
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6235
					wp_die( $die_error );
6236
				}
6237
			} else {
6238
				wp_die( $die_error );
6239
			}
6240
		}
6241
6242
		$timestamp = (int) $environment['timestamp'];
6243
		$nonce     = stripslashes( (string) $environment['nonce'] );
6244
6245
		if ( ! $this->connection_manager ) {
6246
			$this->connection_manager = new Connection_Manager();
6247
		}
6248
6249
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6250
			// De-nonce the nonce, at least for 5 minutes.
6251
			// 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)
6252
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6253
			if ( $old_nonce_time < time() - 300 ) {
6254
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6255
			}
6256
		}
6257
6258
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6259
		$data_filters = array(
6260
			'state'        => 'opaque',
6261
			'client_id'    => 'int',
6262
			'client_title' => 'string',
6263
			'client_image' => 'url',
6264
		);
6265
6266
		foreach ( $data_filters as $key => $sanitation ) {
6267
			if ( ! isset( $data->$key ) ) {
6268
				wp_die( $die_error );
6269
			}
6270
6271
			switch ( $sanitation ) {
6272
				case 'int':
6273
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6274
					break;
6275
				case 'opaque':
6276
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6277
					break;
6278
				case 'string':
6279
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6280
					break;
6281
				case 'url':
6282
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6283
					break;
6284
			}
6285
		}
6286
6287
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6288
			wp_die( $die_error );
6289
		}
6290
	}
6291
6292
	function login_message_json_api_authorization( $message ) {
6293
		return '<p class="message">' . sprintf(
6294
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6295
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6296
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6297
	}
6298
6299
	/**
6300
	 * Get $content_width, but with a <s>twist</s> filter.
6301
	 */
6302
	public static function get_content_width() {
6303
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6304
			? $GLOBALS['content_width']
6305
			: false;
6306
		/**
6307
		 * Filter the Content Width value.
6308
		 *
6309
		 * @since 2.2.3
6310
		 *
6311
		 * @param string $content_width Content Width value.
6312
		 */
6313
		return apply_filters( 'jetpack_content_width', $content_width );
6314
	}
6315
6316
	/**
6317
	 * Pings the WordPress.com Mirror Site for the specified options.
6318
	 *
6319
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6320
	 *
6321
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6322
	 */
6323
	public function get_cloud_site_options( $option_names ) {
6324
		$option_names = array_filter( (array) $option_names, 'is_string' );
6325
6326
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6327
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6328
		if ( $xml->isError() ) {
6329
			return array(
6330
				'error_code' => $xml->getErrorCode(),
6331
				'error_msg'  => $xml->getErrorMessage(),
6332
			);
6333
		}
6334
		$cloud_site_options = $xml->getResponse();
6335
6336
		return $cloud_site_options;
6337
	}
6338
6339
	/**
6340
	 * Checks if the site is currently in an identity crisis.
6341
	 *
6342
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6343
	 */
6344
	public static function check_identity_crisis() {
6345
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6346
			return false;
6347
		}
6348
6349
		return Jetpack_Options::get_option( 'sync_error_idc' );
6350
	}
6351
6352
	/**
6353
	 * Checks whether the home and siteurl specifically are allowed.
6354
	 * Written so that we don't have re-check $key and $value params every time
6355
	 * we want to check if this site is allowed, for example in footer.php
6356
	 *
6357
	 * @since  3.8.0
6358
	 * @return bool True = already allowed False = not on the allowed list.
6359
	 */
6360
	public static function is_staging_site() {
6361
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6362
		return ( new Status() )->is_staging_site();
6363
	}
6364
6365
	/**
6366
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6367
	 *
6368
	 * @since 4.4.0
6369
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6370
	 *
6371
	 * @return bool
6372
	 */
6373
	public static function validate_sync_error_idc_option() {
6374
		$is_valid = false;
6375
6376
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6377
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6378
		if ( $sync_error && self::sync_idc_optin() ) {
6379
			$local_options = self::get_sync_error_idc_option();
6380
			// Ensure all values are set.
6381
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6382
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6383
					$is_valid = true;
6384
				}
6385
			}
6386
		}
6387
6388
		/**
6389
		 * Filters whether the sync_error_idc option is valid.
6390
		 *
6391
		 * @since 4.4.0
6392
		 *
6393
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6394
		 */
6395
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6396
6397
		if ( ! $is_valid && $sync_error ) {
6398
			// Since the option exists, and did not validate, delete it
6399
			Jetpack_Options::delete_option( 'sync_error_idc' );
6400
		}
6401
6402
		return $is_valid;
6403
	}
6404
6405
	/**
6406
	 * Normalizes a url by doing three things:
6407
	 *  - Strips protocol
6408
	 *  - Strips www
6409
	 *  - Adds a trailing slash
6410
	 *
6411
	 * @since 4.4.0
6412
	 * @param string $url
6413
	 * @return WP_Error|string
6414
	 */
6415
	public static function normalize_url_protocol_agnostic( $url ) {
6416
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6417
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6418
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
6419
		}
6420
6421
		// Strip www and protocols
6422
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6423
		return $url;
6424
	}
6425
6426
	/**
6427
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6428
	 *
6429
	 * @since 4.4.0
6430
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6431
	 *
6432
	 * @param array $response
6433
	 * @return array Array of the local urls, wpcom urls, and error code
6434
	 */
6435
	public static function get_sync_error_idc_option( $response = array() ) {
6436
		// Since the local options will hit the database directly, store the values
6437
		// in a transient to allow for autoloading and caching on subsequent views.
6438
		$local_options = get_transient( 'jetpack_idc_local' );
6439
		if ( false === $local_options ) {
6440
			$local_options = array(
6441
				'home'    => Functions::home_url(),
6442
				'siteurl' => Functions::site_url(),
6443
			);
6444
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6445
		}
6446
6447
		$options = array_merge( $local_options, $response );
6448
6449
		$returned_values = array();
6450
		foreach ( $options as $key => $option ) {
6451
			if ( 'error_code' === $key ) {
6452
				$returned_values[ $key ] = $option;
6453
				continue;
6454
			}
6455
6456
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6457
				continue;
6458
			}
6459
6460
			$returned_values[ $key ] = $normalized_url;
6461
		}
6462
6463
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6464
6465
		return $returned_values;
6466
	}
6467
6468
	/**
6469
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6470
	 * If set to true, the site will be put into staging mode.
6471
	 *
6472
	 * @since 4.3.2
6473
	 * @return bool
6474
	 */
6475
	public static function sync_idc_optin() {
6476
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6477
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6478
		} else {
6479
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6480
		}
6481
6482
		/**
6483
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6484
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6485
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6486
		 *
6487
		 * @since 4.3.2
6488
		 *
6489
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6490
		 */
6491
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6492
	}
6493
6494
	/**
6495
	 * Maybe Use a .min.css stylesheet, maybe not.
6496
	 *
6497
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6498
	 */
6499
	public static function maybe_min_asset( $url, $path, $plugin ) {
6500
		// Short out on things trying to find actual paths.
6501
		if ( ! $path || empty( $plugin ) ) {
6502
			return $url;
6503
		}
6504
6505
		$path = ltrim( $path, '/' );
6506
6507
		// Strip out the abspath.
6508
		$base = dirname( plugin_basename( $plugin ) );
6509
6510
		// Short out on non-Jetpack assets.
6511
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6512
			return $url;
6513
		}
6514
6515
		// File name parsing.
6516
		$file              = "{$base}/{$path}";
6517
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6518
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6519
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6520
		$extension         = array_shift( $file_name_parts_r );
6521
6522
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6523
			// Already pointing at the minified version.
6524
			if ( 'min' === $file_name_parts_r[0] ) {
6525
				return $url;
6526
			}
6527
6528
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6529
			if ( file_exists( $min_full_path ) ) {
6530
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6531
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6532
				if ( 'css' === $extension ) {
6533
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6534
					self::$min_assets[ $key ] = $path;
6535
				}
6536
			}
6537
		}
6538
6539
		return $url;
6540
	}
6541
6542
	/**
6543
	 * If the asset is minified, let's flag .min as the suffix.
6544
	 *
6545
	 * Attached to `style_loader_src` filter.
6546
	 *
6547
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6548
	 * @param string $handle The registered handle of the script in question.
6549
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6550
	 */
6551
	public static function set_suffix_on_min( $src, $handle ) {
6552
		if ( false === strpos( $src, '.min.css' ) ) {
6553
			return $src;
6554
		}
6555
6556
		if ( ! empty( self::$min_assets ) ) {
6557
			foreach ( self::$min_assets as $file => $path ) {
6558
				if ( false !== strpos( $src, $file ) ) {
6559
					wp_style_add_data( $handle, 'suffix', '.min' );
6560
					return $src;
6561
				}
6562
			}
6563
		}
6564
6565
		return $src;
6566
	}
6567
6568
	/**
6569
	 * Maybe inlines a stylesheet.
6570
	 *
6571
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6572
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6573
	 *
6574
	 * Attached to `style_loader_tag` filter.
6575
	 *
6576
	 * @param string $tag The tag that would link to the external asset.
6577
	 * @param string $handle The registered handle of the script in question.
6578
	 *
6579
	 * @return string
6580
	 */
6581
	public static function maybe_inline_style( $tag, $handle ) {
6582
		global $wp_styles;
6583
		$item = $wp_styles->registered[ $handle ];
6584
6585
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6586
			return $tag;
6587
		}
6588
6589
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6590
			$href = $matches[1];
6591
			// Strip off query string
6592
			if ( $pos = strpos( $href, '?' ) ) {
6593
				$href = substr( $href, 0, $pos );
6594
			}
6595
			// Strip off fragment
6596
			if ( $pos = strpos( $href, '#' ) ) {
6597
				$href = substr( $href, 0, $pos );
6598
			}
6599
		} else {
6600
			return $tag;
6601
		}
6602
6603
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6604
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6605
			return $tag;
6606
		}
6607
6608
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6609
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6610
			// And this isn't the pass that actually deals with the RTL version...
6611
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6612
				// Short out, as the RTL version will deal with it in a moment.
6613
				return $tag;
6614
			}
6615
		}
6616
6617
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6618
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6619
		if ( $css ) {
6620
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6621
			if ( empty( $item->extra['after'] ) ) {
6622
				wp_add_inline_style( $handle, $css );
6623
			} else {
6624
				array_unshift( $item->extra['after'], $css );
6625
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6626
			}
6627
		}
6628
6629
		return $tag;
6630
	}
6631
6632
	/**
6633
	 * Loads a view file from the views
6634
	 *
6635
	 * Data passed in with the $data parameter will be available in the
6636
	 * template file as $data['value']
6637
	 *
6638
	 * @param string $template - Template file to load
6639
	 * @param array  $data - Any data to pass along to the template
6640
	 * @return boolean - If template file was found
6641
	 **/
6642
	public function load_view( $template, $data = array() ) {
6643
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6644
6645
		if ( file_exists( $views_dir . $template ) ) {
6646
			require_once $views_dir . $template;
6647
			return true;
6648
		}
6649
6650
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6651
		return false;
6652
	}
6653
6654
	/**
6655
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6656
	 *
6657
	 * @todo Convert these to use apply_filters_deprecated and do_action_deprecated and remove custom code.
6658
	 */
6659
	public function deprecated_hooks() {
6660
		global $wp_filter;
6661
6662
		/*
6663
		 * Format:
6664
		 * deprecated_filter_name => replacement_name
6665
		 *
6666
		 * If there is no replacement, use null for replacement_name
6667
		 */
6668
		$deprecated_list = array(
6669
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6670
			'wpl_sharing_2014_1'                           => null,
6671
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6672
			'jetpack_identity_crisis_options_to_check'     => null,
6673
			'update_option_jetpack_single_user_site'       => null,
6674
			'audio_player_default_colors'                  => null,
6675
			'add_option_jetpack_featured_images_enabled'   => null,
6676
			'add_option_jetpack_update_details'            => null,
6677
			'add_option_jetpack_updates'                   => null,
6678
			'add_option_jetpack_network_name'              => null,
6679
			'add_option_jetpack_network_allow_new_registrations' => null,
6680
			'add_option_jetpack_network_add_new_users'     => null,
6681
			'add_option_jetpack_network_site_upload_space' => null,
6682
			'add_option_jetpack_network_upload_file_types' => null,
6683
			'add_option_jetpack_network_enable_administration_menus' => null,
6684
			'add_option_jetpack_is_multi_site'             => null,
6685
			'add_option_jetpack_is_main_network'           => null,
6686
			'add_option_jetpack_main_network_site'         => null,
6687
			'jetpack_sync_all_registered_options'          => null,
6688
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6689
			'jetpack_is_post_mailable'                     => null,
6690
			'jetpack_seo_site_host'                        => null,
6691
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6692
			'jetpack_holiday_snow_option_name'             => null,
6693
			'jetpack_holiday_chance_of_snow'               => null,
6694
			'jetpack_holiday_snow_js_url'                  => null,
6695
			'jetpack_is_holiday_snow_season'               => null,
6696
			'jetpack_holiday_snow_option_updated'          => null,
6697
			'jetpack_holiday_snowing'                      => null,
6698
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6699
			'jetpack_cache_plans'                          => null,
6700
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6701
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6702
			'jetpack_enable_site_verification'             => null,
6703
			// Removed in Jetpack 7.3.0
6704
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6705
			// Removed in Jetpack 7.9.0
6706
			'jetpack_pwa_manifest'                         => null,
6707
			'jetpack_pwa_background_color'                 => null,
6708
			// Removed in Jetpack 8.3.0.
6709
			'jetpack_check_mobile'                         => null,
6710
			'jetpack_mobile_stylesheet'                    => null,
6711
			'jetpack_mobile_template'                      => null,
6712
			'mobile_reject_mobile'                         => null,
6713
			'mobile_force_mobile'                          => null,
6714
			'mobile_app_promo_download'                    => null,
6715
			'mobile_setup'                                 => null,
6716
			'jetpack_mobile_footer_before'                 => null,
6717
			'wp_mobile_theme_footer'                       => null,
6718
			'minileven_credits'                            => null,
6719
			'jetpack_mobile_header_before'                 => null,
6720
			'jetpack_mobile_header_after'                  => null,
6721
			'jetpack_mobile_theme_menu'                    => null,
6722
			'minileven_show_featured_images'               => null,
6723
			'minileven_attachment_size'                    => null,
6724
		);
6725
6726
		// This is a silly loop depth. Better way?
6727
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6728
			if ( has_action( $hook ) ) {
6729
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6730
					foreach ( $values as $hooked ) {
6731
						if ( is_callable( $hooked['function'] ) ) {
6732
							$function_name = $hooked['function'];
6733
						} else {
6734
							$function_name = 'an anonymous function';
6735
						}
6736
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6737
					}
6738
				}
6739
			}
6740
		}
6741
6742
		$filter_deprecated_list = array(
6743
			'can_display_jetpack_manage_notice' => array(
6744
				'replacement' => null,
6745
				'version'     => 'jetpack-7.3.0',
6746
			),
6747
			'atd_http_post_timeout'             => array(
6748
				'replacement' => null,
6749
				'version'     => 'jetpack-7.3.0',
6750
			),
6751
			'atd_service_domain'                => array(
6752
				'replacement' => null,
6753
				'version'     => 'jetpack-7.3.0',
6754
			),
6755
			'atd_load_scripts'                  => array(
6756
				'replacement' => null,
6757
				'version'     => 'jetpack-7.3.0',
6758
			),
6759
		);
6760
6761
		foreach ( $filter_deprecated_list as $tag => $args ) {
6762
			if ( has_filter( $tag ) ) {
6763
				apply_filters_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6764
			}
6765
		}
6766
6767
		$action_deprecated_list = array(
6768
			'atd_http_post_error' => array(
6769
				'replacement' => null,
6770
				'version'     => 'jetpack-7.3.0',
6771
			),
6772
		);
6773
6774
		foreach ( $action_deprecated_list as $tag => $args ) {
6775
			if ( has_action( $tag ) ) {
6776
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6777
			}
6778
		}
6779
	}
6780
6781
	/**
6782
	 * Converts any url in a stylesheet, to the correct absolute url.
6783
	 *
6784
	 * Considerations:
6785
	 *  - Normal, relative URLs     `feh.png`
6786
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6787
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6788
	 *  - Absolute URLs             `http://domain.com/feh.png`
6789
	 *  - Domain root relative URLs `/feh.png`
6790
	 *
6791
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6792
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6793
	 *
6794
	 * @return mixed|string
6795
	 */
6796
	public static function absolutize_css_urls( $css, $css_file_url ) {
6797
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6798
		$css_dir = dirname( $css_file_url );
6799
		$p       = wp_parse_url( $css_dir );
6800
		$domain  = sprintf(
6801
			'%1$s//%2$s%3$s%4$s',
6802
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6803
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6804
			$p['host'],
6805
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6806
		);
6807
6808
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6809
			$find = $replace = array();
6810
			foreach ( $matches as $match ) {
6811
				$url = trim( $match['path'], "'\" \t" );
6812
6813
				// If this is a data url, we don't want to mess with it.
6814
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6815
					continue;
6816
				}
6817
6818
				// If this is an absolute or protocol-agnostic url,
6819
				// we don't want to mess with it.
6820
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6821
					continue;
6822
				}
6823
6824
				switch ( substr( $url, 0, 1 ) ) {
6825
					case '/':
6826
						$absolute = $domain . $url;
6827
						break;
6828
					default:
6829
						$absolute = $css_dir . '/' . $url;
6830
				}
6831
6832
				$find[]    = $match[0];
6833
				$replace[] = sprintf( 'url("%s")', $absolute );
6834
			}
6835
			$css = str_replace( $find, $replace, $css );
6836
		}
6837
6838
		return $css;
6839
	}
6840
6841
	/**
6842
	 * This methods removes all of the registered css files on the front end
6843
	 * from Jetpack in favor of using a single file. In effect "imploding"
6844
	 * all the files into one file.
6845
	 *
6846
	 * Pros:
6847
	 * - Uses only ONE css asset connection instead of 15
6848
	 * - Saves a minimum of 56k
6849
	 * - Reduces server load
6850
	 * - Reduces time to first painted byte
6851
	 *
6852
	 * Cons:
6853
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6854
	 *      should not cause any issues with themes.
6855
	 * - Plugins/themes dequeuing styles no longer do anything. See
6856
	 *      jetpack_implode_frontend_css filter for a workaround
6857
	 *
6858
	 * For some situations developers may wish to disable css imploding and
6859
	 * instead operate in legacy mode where each file loads seperately and
6860
	 * can be edited individually or dequeued. This can be accomplished with
6861
	 * the following line:
6862
	 *
6863
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6864
	 *
6865
	 * @since 3.2
6866
	 **/
6867
	public function implode_frontend_css( $travis_test = false ) {
6868
		$do_implode = true;
6869
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6870
			$do_implode = false;
6871
		}
6872
6873
		// Do not implode CSS when the page loads via the AMP plugin.
6874
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6875
			$do_implode = false;
6876
		}
6877
6878
		/**
6879
		 * Allow CSS to be concatenated into a single jetpack.css file.
6880
		 *
6881
		 * @since 3.2.0
6882
		 *
6883
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6884
		 */
6885
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6886
6887
		// Do not use the imploded file when default behavior was altered through the filter
6888
		if ( ! $do_implode ) {
6889
			return;
6890
		}
6891
6892
		// We do not want to use the imploded file in dev mode, or if not connected
6893
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6894
			if ( ! $travis_test ) {
6895
				return;
6896
			}
6897
		}
6898
6899
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6900
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6901
			return;
6902
		}
6903
6904
		/*
6905
		 * Now we assume Jetpack is connected and able to serve the single
6906
		 * file.
6907
		 *
6908
		 * In the future there will be a check here to serve the file locally
6909
		 * or potentially from the Jetpack CDN
6910
		 *
6911
		 * For now:
6912
		 * - Enqueue a single imploded css file
6913
		 * - Zero out the style_loader_tag for the bundled ones
6914
		 * - Be happy, drink scotch
6915
		 */
6916
6917
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6918
6919
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6920
6921
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6922
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6923
	}
6924
6925
	function concat_remove_style_loader_tag( $tag, $handle ) {
6926
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6927
			$tag = '';
6928
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6929
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6930
			}
6931
		}
6932
6933
		return $tag;
6934
	}
6935
6936
	/**
6937
	 * @deprecated
6938
	 * @see Automattic\Jetpack\Assets\add_aync_script
6939
	 */
6940
	public function script_add_async( $tag, $handle, $src ) {
6941
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6942
	}
6943
6944
	/*
6945
	 * Check the heartbeat data
6946
	 *
6947
	 * Organizes the heartbeat data by severity.  For example, if the site
6948
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6949
	 *
6950
	 * Data will be added to "caution" array, if it either:
6951
	 *  - Out of date Jetpack version
6952
	 *  - Out of date WP version
6953
	 *  - Out of date PHP version
6954
	 *
6955
	 * $return array $filtered_data
6956
	 */
6957
	public static function jetpack_check_heartbeat_data() {
6958
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6959
6960
		$good    = array();
6961
		$caution = array();
6962
		$bad     = array();
6963
6964
		foreach ( $raw_data as $stat => $value ) {
6965
6966
			// Check jetpack version
6967
			if ( 'version' == $stat ) {
6968
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6969
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6970
					continue;
6971
				}
6972
			}
6973
6974
			// Check WP version
6975
			if ( 'wp-version' == $stat ) {
6976
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6977
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6978
					continue;
6979
				}
6980
			}
6981
6982
			// Check PHP version
6983
			if ( 'php-version' == $stat ) {
6984
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6985
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6986
					continue;
6987
				}
6988
			}
6989
6990
			// Check ID crisis
6991
			if ( 'identitycrisis' == $stat ) {
6992
				if ( 'yes' == $value ) {
6993
					$bad[ $stat ] = $value;
6994
					continue;
6995
				}
6996
			}
6997
6998
			// The rest are good :)
6999
			$good[ $stat ] = $value;
7000
		}
7001
7002
		$filtered_data = array(
7003
			'good'    => $good,
7004
			'caution' => $caution,
7005
			'bad'     => $bad,
7006
		);
7007
7008
		return $filtered_data;
7009
	}
7010
7011
7012
	/*
7013
	 * This method is used to organize all options that can be reset
7014
	 * without disconnecting Jetpack.
7015
	 *
7016
	 * It is used in class.jetpack-cli.php to reset options
7017
	 *
7018
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
7019
	 *
7020
	 * @return array of options to delete.
7021
	 */
7022
	public static function get_jetpack_options_for_reset() {
7023
		return Jetpack_Options::get_options_for_reset();
7024
	}
7025
7026
	/*
7027
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
7028
	 * so we can bring them directly to their site in calypso.
7029
	 *
7030
	 * @param string | url
7031
	 * @return string | url without the guff
7032
	 */
7033 View Code Duplication
	public static function build_raw_urls( $url ) {
7034
		$strip_http = '/.*?:\/\//i';
7035
		$url        = preg_replace( $strip_http, '', $url );
7036
		$url        = str_replace( '/', '::', $url );
7037
		return $url;
7038
	}
7039
7040
	/**
7041
	 * Stores and prints out domains to prefetch for page speed optimization.
7042
	 *
7043
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7044
	 *
7045
	 * @param string|array $urls URLs to hint.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $urls not be string|array|null?

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

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

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

Loading history...
7046
	 */
7047
	public static function dns_prefetch( $urls = null ) {
7048
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7049
		if ( $urls ) {
7050
			Assets::add_resource_hint( $urls );
7051
		}
7052
	}
7053
7054
	public function wp_dashboard_setup() {
7055
		if ( self::is_active() ) {
7056
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7057
		}
7058
7059
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
7060
			$jetpack_logo = new Jetpack_Logo();
7061
			$widget_title = sprintf(
7062
				wp_kses(
7063
					/* translators: Placeholder is a Jetpack logo. */
7064
					__( 'Stats <span>by %s</span>', 'jetpack' ),
7065
					array( 'span' => array() )
7066
				),
7067
				$jetpack_logo->get_jp_emblem( true )
7068
			);
7069
7070
			wp_add_dashboard_widget(
7071
				'jetpack_summary_widget',
7072
				$widget_title,
7073
				array( __CLASS__, 'dashboard_widget' )
7074
			);
7075
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7076
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7077
7078
			// If we're inactive and not in development mode, sort our box to the top.
7079
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
7080
				global $wp_meta_boxes;
7081
7082
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7083
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7084
7085
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7086
			}
7087
		}
7088
	}
7089
7090
	/**
7091
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
7092
	 * @return mixed
7093
	 */
7094
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7095
		if ( ! is_array( $sorted ) ) {
7096
			return $sorted;
7097
		}
7098
7099
		foreach ( $sorted as $box_context => $ids ) {
7100
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7101
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7102
				continue;
7103
			}
7104
7105
			$ids_array = explode( ',', $ids );
7106
			$key       = array_search( 'dashboard_stats', $ids_array );
7107
7108
			if ( false !== $key ) {
7109
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7110
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7111
				$sorted[ $box_context ] = implode( ',', $ids_array );
7112
				// We've found it, stop searching, and just return.
7113
				break;
7114
			}
7115
		}
7116
7117
		return $sorted;
7118
	}
7119
7120
	public static function dashboard_widget() {
7121
		/**
7122
		 * Fires when the dashboard is loaded.
7123
		 *
7124
		 * @since 3.4.0
7125
		 */
7126
		do_action( 'jetpack_dashboard_widget' );
7127
	}
7128
7129
	public static function dashboard_widget_footer() {
7130
		?>
7131
		<footer>
7132
7133
		<div class="protect">
7134
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7135
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7136
				<p class="blocked-count">
7137
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7138
				</p>
7139
				<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>
7140
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
7141
				<a href="
7142
				<?php
7143
				echo esc_url(
7144
					wp_nonce_url(
7145
						self::admin_url(
7146
							array(
7147
								'action' => 'activate',
7148
								'module' => 'protect',
7149
							)
7150
						),
7151
						'jetpack_activate-protect'
7152
					)
7153
				);
7154
				?>
7155
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7156
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7157
				</a>
7158
			<?php else : ?>
7159
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7160
			<?php endif; ?>
7161
		</div>
7162
7163
		<div class="akismet">
7164
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7165
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7166
				<p class="blocked-count">
7167
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7168
				</p>
7169
				<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>
7170
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7171
				<a href="
7172
				<?php
7173
				echo esc_url(
7174
					wp_nonce_url(
7175
						add_query_arg(
7176
							array(
7177
								'action' => 'activate',
7178
								'plugin' => 'akismet/akismet.php',
7179
							),
7180
							admin_url( 'plugins.php' )
7181
						),
7182
						'activate-plugin_akismet/akismet.php'
7183
					)
7184
				);
7185
				?>
7186
							" class="button button-jetpack">
7187
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7188
				</a>
7189
			<?php else : ?>
7190
				<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>
7191
			<?php endif; ?>
7192
		</div>
7193
7194
		</footer>
7195
		<?php
7196
	}
7197
7198
	/*
7199
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7200
	 */
7201
	function jetpack_icon_user_connected( $columns ) {
7202
		$columns['user_jetpack'] = '';
7203
		return $columns;
7204
	}
7205
7206
	/*
7207
	 * Show Jetpack icon if the user is linked.
7208
	 */
7209
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7210
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7211
			$jetpack_logo = new Jetpack_Logo();
7212
			$emblem_html  = sprintf(
7213
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7214
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7215
				$jetpack_logo->get_jp_emblem()
7216
			);
7217
			return $emblem_html;
7218
		}
7219
7220
		return $val;
7221
	}
7222
7223
	/*
7224
	 * Style the Jetpack user column
7225
	 */
7226
	function jetpack_user_col_style() {
7227
		global $current_screen;
7228
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7229
			?>
7230
			<style>
7231
				.fixed .column-user_jetpack {
7232
					width: 21px;
7233
				}
7234
				.jp-emblem-user-admin svg {
7235
					width: 20px;
7236
					height: 20px;
7237
				}
7238
				.jp-emblem-user-admin path {
7239
					fill: #00BE28;
7240
				}
7241
			</style>
7242
			<?php
7243
		}
7244
	}
7245
7246
	/**
7247
	 * Checks if Akismet is active and working.
7248
	 *
7249
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7250
	 * that implied usage of methods present since more recent version.
7251
	 * See https://github.com/Automattic/jetpack/pull/9585
7252
	 *
7253
	 * @since  5.1.0
7254
	 *
7255
	 * @return bool True = Akismet available. False = Aksimet not available.
7256
	 */
7257
	public static function is_akismet_active() {
7258
		static $status = null;
7259
7260
		if ( ! is_null( $status ) ) {
7261
			return $status;
7262
		}
7263
7264
		// Check if a modern version of Akismet is active.
7265
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7266
			$status = false;
7267
			return $status;
7268
		}
7269
7270
		// Make sure there is a key known to Akismet at all before verifying key.
7271
		$akismet_key = Akismet::get_api_key();
7272
		if ( ! $akismet_key ) {
7273
			$status = false;
7274
			return $status;
7275
		}
7276
7277
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7278
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7279
7280
		// 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.
7281
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7282
		// We cache the result of the Akismet key verification for ten minutes.
7283
		if ( ! $akismet_key_state || $recheck ) {
7284
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7285
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7286
		}
7287
7288
		$status = 'valid' === $akismet_key_state;
7289
7290
		return $status;
7291
	}
7292
7293
	/**
7294
	 * @deprecated
7295
	 *
7296
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7297
	 */
7298
	public static function is_function_in_backtrace() {
7299
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7300
	}
7301
7302
	/**
7303
	 * Given a minified path, and a non-minified path, will return
7304
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7305
	 *
7306
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7307
	 * root Jetpack directory.
7308
	 *
7309
	 * @since 5.6.0
7310
	 *
7311
	 * @param string $min_path
7312
	 * @param string $non_min_path
7313
	 * @return string The URL to the file
7314
	 */
7315
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7316
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7317
	}
7318
7319
	/**
7320
	 * Checks for whether Jetpack Backup is enabled.
7321
	 * Will return true if the state of Backup is anything except "unavailable".
7322
	 *
7323
	 * @return bool|int|mixed
7324
	 */
7325
	public static function is_rewind_enabled() {
7326
		if ( ! self::is_active() ) {
7327
			return false;
7328
		}
7329
7330
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7331
		if ( false === $rewind_enabled ) {
7332
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7333
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7334
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7335
				&& ! empty( $rewind_data['state'] )
7336
				&& 'active' === $rewind_data['state'] )
7337
				? 1
7338
				: 0;
7339
7340
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7341
		}
7342
		return $rewind_enabled;
7343
	}
7344
7345
	/**
7346
	 * Return Calypso environment value; used for developing Jetpack and pairing
7347
	 * it with different Calypso enrionments, such as localhost.
7348
	 *
7349
	 * @since 7.4.0
7350
	 *
7351
	 * @return string Calypso environment
7352
	 */
7353
	public static function get_calypso_env() {
7354
		if ( isset( $_GET['calypso_env'] ) ) {
7355
			return sanitize_key( $_GET['calypso_env'] );
7356
		}
7357
7358
		if ( getenv( 'CALYPSO_ENV' ) ) {
7359
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7360
		}
7361
7362
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7363
			return sanitize_key( CALYPSO_ENV );
7364
		}
7365
7366
		return '';
7367
	}
7368
7369
	/**
7370
	 * Returns the hostname with protocol for Calypso.
7371
	 * Used for developing Jetpack with Calypso.
7372
	 *
7373
	 * @since 8.4.0
7374
	 *
7375
	 * @return string Calypso host.
7376
	 */
7377
	public static function get_calypso_host() {
7378
		$calypso_env = self::get_calypso_env();
7379
		switch ( $calypso_env ) {
7380
			case 'development':
7381
				return 'http://calypso.localhost:3000/';
7382
			case 'wpcalypso':
7383
				return 'https://wpcalypso.wordpress.com/';
7384
			case 'horizon':
7385
				return 'https://horizon.wordpress.com/';
7386
			default:
7387
				return 'https://wordpress.com/';
7388
		}
7389
	}
7390
7391
	/**
7392
	 * Checks whether or not TOS has been agreed upon.
7393
	 * Will return true if a user has clicked to register, or is already connected.
7394
	 */
7395
	public static function jetpack_tos_agreed() {
7396
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7397
7398
		$terms_of_service = new Terms_Of_Service();
7399
		return $terms_of_service->has_agreed();
7400
7401
	}
7402
7403
	/**
7404
	 * Handles activating default modules as well general cleanup for the new connection.
7405
	 *
7406
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7407
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7408
	 * @param boolean $send_state_messages          Whether to send state messages.
7409
	 * @return void
7410
	 */
7411
	public static function handle_post_authorization_actions(
7412
		$activate_sso = false,
7413
		$redirect_on_activation_error = false,
7414
		$send_state_messages = true
7415
	) {
7416
		$other_modules = $activate_sso
7417
			? array( 'sso' )
7418
			: array();
7419
7420
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7421
			self::delete_active_modules();
7422
7423
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7424
		} else {
7425
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7426
		}
7427
7428
		// Since this is a fresh connection, be sure to clear out IDC options
7429
		Jetpack_IDC::clear_all_idc_options();
7430
7431
		if ( $send_state_messages ) {
7432
			self::state( 'message', 'authorized' );
7433
		}
7434
	}
7435
7436
	/**
7437
	 * Returns a boolean for whether backups UI should be displayed or not.
7438
	 *
7439
	 * @return bool Should backups UI be displayed?
7440
	 */
7441
	public static function show_backups_ui() {
7442
		/**
7443
		 * Whether UI for backups should be displayed.
7444
		 *
7445
		 * @since 6.5.0
7446
		 *
7447
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7448
		 */
7449
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7450
	}
7451
7452
	/*
7453
	 * Deprecated manage functions
7454
	 */
7455
	function prepare_manage_jetpack_notice() {
7456
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7457
	}
7458
	function manage_activate_screen() {
7459
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7460
	}
7461
	function admin_jetpack_manage_notice() {
7462
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7463
	}
7464
	function opt_out_jetpack_manage_url() {
7465
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7466
	}
7467
	function opt_in_jetpack_manage_url() {
7468
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7469
	}
7470
	function opt_in_jetpack_manage_notice() {
7471
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7472
	}
7473
	function can_display_jetpack_manage_notice() {
7474
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7475
	}
7476
7477
	/**
7478
	 * Clean leftoveruser meta.
7479
	 *
7480
	 * Delete Jetpack-related user meta when it is no longer needed.
7481
	 *
7482
	 * @since 7.3.0
7483
	 *
7484
	 * @param int $user_id User ID being updated.
7485
	 */
7486
	public static function user_meta_cleanup( $user_id ) {
7487
		$meta_keys = array(
7488
			// AtD removed from Jetpack 7.3
7489
			'AtD_options',
7490
			'AtD_check_when',
7491
			'AtD_guess_lang',
7492
			'AtD_ignored_phrases',
7493
		);
7494
7495
		foreach ( $meta_keys as $meta_key ) {
7496
			if ( get_user_meta( $user_id, $meta_key ) ) {
7497
				delete_user_meta( $user_id, $meta_key );
7498
			}
7499
		}
7500
	}
7501
7502
	/**
7503
	 * Checks if a Jetpack site is both active and not in development.
7504
	 *
7505
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7506
	 *
7507
	 * @return bool True if Jetpack is active and not in development.
7508
	 */
7509
	public static function is_active_and_not_development_mode() {
7510
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7511
			return false;
7512
		}
7513
		return true;
7514
	}
7515
7516
	/**
7517
	 * Returns the list of products that we have available for purchase.
7518
	 */
7519
	public static function get_products_for_purchase() {
7520
		$products = array();
7521
		if ( ! is_multisite() ) {
7522
			$products[] = array(
7523
				'key'               => 'backup',
7524
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7525
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7526
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7527
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7528
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7529
				'options'           => array(
7530
					array(
7531
						'type'        => 'daily',
7532
						'slug'        => 'jetpack-backup-daily',
7533
						'key'         => 'jetpack_backup_daily',
7534
						'name'        => __( 'Daily Backups', 'jetpack' ),
7535
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7536
					),
7537
					array(
7538
						'type'        => 'realtime',
7539
						'slug'        => 'jetpack-backup-realtime',
7540
						'key'         => 'jetpack_backup_realtime',
7541
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7542
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7543
					),
7544
				),
7545
				'default_option'    => 'realtime',
7546
				'show_promotion'    => true,
7547
				'discount_percent'  => 70,
7548
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7549
			);
7550
7551
			$products[] = array(
7552
				'key'               => 'scan',
7553
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7554
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7555
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7556
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7557
				'show_promotion'    => true,
7558
				'discount_percent'  => 30,
7559
				'options'           => array(
7560
					array(
7561
						'type' => 'scan',
7562
						'slug' => 'jetpack-scan',
7563
						'key'  => 'jetpack_scan',
7564
						'name' => __( 'Daily Scan', 'jetpack' ),
7565
					),
7566
				),
7567
				'default_option'    => 'scan',
7568
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7569
			);
7570
		}
7571
7572
		$products[] = array(
7573
			'key'               => 'search',
7574
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7575
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7576
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7577
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7578
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7579
			'options'           => array(
7580
				array(
7581
					'type' => 'search',
7582
					'slug' => 'jetpack-search',
7583
					'key'  => 'jetpack_search',
7584
					'name' => __( 'Search', 'jetpack' ),
7585
				),
7586
			),
7587
			'tears'             => array(),
7588
			'default_option'    => 'search',
7589
			'show_promotion'    => false,
7590
			'included_in_plans' => array( 'search-plan' ),
7591
		);
7592
7593
		return $products;
7594
	}
7595
}
7596