Completed
Push — add/debug-mocker ( 986c7c...aaec4a )
by
unknown
08:37
created

Jetpack::jetpack_tos_agreed()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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