Completed
Push — add/redirect-everything ( 18e8a6...50f94e )
by
unknown
65:52 queued 58:20
created

class.jetpack.php (68 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

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

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

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

Loading history...
845
	 */
846 View Code Duplication
	public function setup_xmlrpc_handlers(
847
		$request_params,
848
		$is_active,
849
		$is_signed,
850
		Jetpack_XMLRPC_Server $xmlrpc_server = null
851
	) {
852
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
853
854
		if ( ! $this->connection_manager ) {
855
			$this->connection_manager = new Connection_Manager();
856
		}
857
858
		return $this->connection_manager->setup_xmlrpc_handlers(
859
			$request_params,
860
			$is_active,
861
			$is_signed,
862
			$xmlrpc_server
863
		);
864
	}
865
866
	/**
867
	 * Initialize REST API registration connector.
868
	 *
869
	 * @deprecated since 7.7.0
870
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
871
	 */
872 View Code Duplication
	public function initialize_rest_api_registration_connector() {
873
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
874
875
		if ( ! $this->connection_manager ) {
876
			$this->connection_manager = new Connection_Manager();
877
		}
878
879
		$this->connection_manager->initialize_rest_api_registration_connector();
880
	}
881
882
	/**
883
	 * This is ported over from the manage module, which has been deprecated and baked in here.
884
	 *
885
	 * @param $domains
886
	 */
887
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
888
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
889
	}
890
891
	/**
892
	 * Return $domains, with 'wordpress.com' appended.
893
	 * This is ported over from the manage module, which has been deprecated and baked in here.
894
	 *
895
	 * @param $domains
896
	 * @return array
897
	 */
898
	function allow_wpcom_domain( $domains ) {
899
		if ( empty( $domains ) ) {
900
			$domains = array();
901
		}
902
		$domains[] = 'wordpress.com';
903
		return array_unique( $domains );
904
	}
905
906
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
907
		$post = get_post( $post_id );
908
909
		if ( empty( $post ) ) {
910
			return $default_url;
911
		}
912
913
		$post_type = $post->post_type;
914
915
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
916
		// https://en.support.wordpress.com/custom-post-types/
917
		$allowed_post_types = array(
918
			'post',
919
			'page',
920
			'jetpack-portfolio',
921
			'jetpack-testimonial',
922
		);
923
924
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
925
			return $default_url;
926
		}
927
928
		$site_slug = self::build_raw_urls( get_home_url() );
929
930
		return esc_url(
931
			self::build_redirect_url(
932
				'calypso-edit-' . $post_type,
933
				array(
934
					'site' => $site_slug,
935
					'path' => $post_id,
936
				)
937
			)
938
		);
939
	}
940
941
	function point_edit_comment_links_to_calypso( $url ) {
942
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
943
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
The variable $query_args does not exist. Did you forget to declare it?

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

Loading history...
944
945
		return esc_url(
946
			self::build_redirect_url(
947
				'calypso-edit-comment',
948
				array(
949
					'site' => self::build_raw_urls( get_home_url() ),
950
					'path' => $query_args['amp;c'],
951
				)
952
			)
953
		);
954
955
	}
956
957
	function jetpack_track_last_sync_callback( $params ) {
958
		/**
959
		 * Filter to turn off jitm caching
960
		 *
961
		 * @since 5.4.0
962
		 *
963
		 * @param bool false Whether to cache just in time messages
964
		 */
965
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
966
			return $params;
967
		}
968
969
		if ( is_array( $params ) && isset( $params[0] ) ) {
970
			$option = $params[0];
971
			if ( 'active_plugins' === $option ) {
972
				// use the cache if we can, but not terribly important if it gets evicted
973
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
974
			}
975
		}
976
977
		return $params;
978
	}
979
980
	function jetpack_connection_banner_callback() {
981
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
982
983
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
984
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
985
			wp_send_json_success();
986
		}
987
988
		wp_die();
989
	}
990
991
	/**
992
	 * Removes all XML-RPC methods that are not `jetpack.*`.
993
	 * Only used in our alternate XML-RPC endpoint, where we want to
994
	 * ensure that Core and other plugins' methods are not exposed.
995
	 *
996
	 * @deprecated since 7.7.0
997
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
998
	 *
999
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1000
	 * @return array Filtered $methods
1001
	 */
1002 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1003
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1004
1005
		if ( ! $this->connection_manager ) {
1006
			$this->connection_manager = new Connection_Manager();
1007
		}
1008
1009
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1010
	}
1011
1012
	/**
1013
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1014
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1015
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1016
	 * which is accessible via a different URI. Most of the below is copied directly
1017
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1018
	 *
1019
	 * @deprecated since 7.7.0
1020
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1021
	 */
1022 View Code Duplication
	public function alternate_xmlrpc() {
1023
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1024
1025
		if ( ! $this->connection_manager ) {
1026
			$this->connection_manager = new Connection_Manager();
1027
		}
1028
1029
		$this->connection_manager->alternate_xmlrpc();
1030
	}
1031
1032
	/**
1033
	 * The callback for the JITM ajax requests.
1034
	 *
1035
	 * @deprecated since 7.9.0
1036
	 */
1037
	function jetpack_jitm_ajax_callback() {
1038
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1039
	}
1040
1041
	/**
1042
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1043
	 */
1044
	function push_stats() {
1045
		if ( ! empty( $this->stats ) ) {
1046
			$this->do_stats( 'server_side' );
1047
		}
1048
	}
1049
1050
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1051
		$is_development_mode = ( new Status() )->is_development_mode();
1052
		switch ( $cap ) {
1053
			case 'jetpack_connect':
1054
			case 'jetpack_reconnect':
1055
				if ( $is_development_mode ) {
1056
					$caps = array( 'do_not_allow' );
1057
					break;
1058
				}
1059
				/**
1060
				 * Pass through. If it's not development mode, these should match disconnect.
1061
				 * Let users disconnect if it's development mode, just in case things glitch.
1062
				 */
1063
			case 'jetpack_disconnect':
1064
				/**
1065
				 * In multisite, can individual site admins manage their own connection?
1066
				 *
1067
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1068
				 */
1069
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1070
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1071
						/**
1072
						 * We need to update the option name -- it's terribly unclear which
1073
						 * direction the override goes.
1074
						 *
1075
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1076
						 */
1077
						$caps = array( 'do_not_allow' );
1078
						break;
1079
					}
1080
				}
1081
1082
				$caps = array( 'manage_options' );
1083
				break;
1084
			case 'jetpack_manage_modules':
1085
			case 'jetpack_activate_modules':
1086
			case 'jetpack_deactivate_modules':
1087
				$caps = array( 'manage_options' );
1088
				break;
1089
			case 'jetpack_configure_modules':
1090
				$caps = array( 'manage_options' );
1091
				break;
1092
			case 'jetpack_manage_autoupdates':
1093
				$caps = array(
1094
					'manage_options',
1095
					'update_plugins',
1096
				);
1097
				break;
1098
			case 'jetpack_network_admin_page':
1099
			case 'jetpack_network_settings_page':
1100
				$caps = array( 'manage_network_plugins' );
1101
				break;
1102
			case 'jetpack_network_sites_page':
1103
				$caps = array( 'manage_sites' );
1104
				break;
1105
			case 'jetpack_admin_page':
1106
				if ( $is_development_mode ) {
1107
					$caps = array( 'manage_options' );
1108
					break;
1109
				} else {
1110
					$caps = array( 'read' );
1111
				}
1112
				break;
1113
			case 'jetpack_connect_user':
1114
				if ( $is_development_mode ) {
1115
					$caps = array( 'do_not_allow' );
1116
					break;
1117
				}
1118
				$caps = array( 'read' );
1119
				break;
1120
		}
1121
		return $caps;
1122
	}
1123
1124
	/**
1125
	 * Require a Jetpack authentication.
1126
	 *
1127
	 * @deprecated since 7.7.0
1128
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1129
	 */
1130 View Code Duplication
	public function require_jetpack_authentication() {
1131
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1132
1133
		if ( ! $this->connection_manager ) {
1134
			$this->connection_manager = new Connection_Manager();
1135
		}
1136
1137
		$this->connection_manager->require_jetpack_authentication();
1138
	}
1139
1140
	/**
1141
	 * Load language files
1142
	 *
1143
	 * @action plugins_loaded
1144
	 */
1145
	public static function plugin_textdomain() {
1146
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1147
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
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
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1159
			wp_register_script(
1160
				'spin',
1161
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1162
				false,
1163
				'1.3'
1164
			);
1165
		}
1166
1167 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1168
			wp_register_script(
1169
				'jquery.spin',
1170
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1171
				array( 'jquery', 'spin' ),
1172
				'1.3'
1173
			);
1174
		}
1175
1176 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1177
			wp_register_script(
1178
				'jetpack-gallery-settings',
1179
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1180
				array( 'media-views' ),
1181
				'20121225'
1182
			);
1183
		}
1184
1185 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1186
			wp_register_script(
1187
				'jetpack-twitter-timeline',
1188
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1189
				array( 'jquery' ),
1190
				'4.0.0',
1191
				true
1192
			);
1193
		}
1194
1195
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1196
			wp_register_script(
1197
				'jetpack-facebook-embed',
1198
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1199
				array(),
1200
				null,
1201
				true
1202
			);
1203
1204
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1205
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1206
			if ( ! is_numeric( $fb_app_id ) ) {
1207
				$fb_app_id = '';
1208
			}
1209
			wp_localize_script(
1210
				'jetpack-facebook-embed',
1211
				'jpfbembed',
1212
				array(
1213
					'appid'  => $fb_app_id,
1214
					'locale' => $this->get_locale(),
1215
				)
1216
			);
1217
		}
1218
1219
		/**
1220
		 * As jetpack_register_genericons is by default fired off a hook,
1221
		 * the hook may have already fired by this point.
1222
		 * So, let's just trigger it manually.
1223
		 */
1224
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1225
		jetpack_register_genericons();
1226
1227
		/**
1228
		 * Register the social logos
1229
		 */
1230
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1231
		jetpack_register_social_logos();
1232
1233 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1234
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1235
		}
1236
	}
1237
1238
	/**
1239
	 * Guess locale from language code.
1240
	 *
1241
	 * @param string $lang Language code.
1242
	 * @return string|bool
1243
	 */
1244 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1245
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1246
			return 'en_US';
1247
		}
1248
1249
		if ( ! class_exists( 'GP_Locales' ) ) {
1250
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1251
				return false;
1252
			}
1253
1254
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1255
		}
1256
1257
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1258
			// WP.com: get_locale() returns 'it'
1259
			$locale = GP_Locales::by_slug( $lang );
1260
		} else {
1261
			// Jetpack: get_locale() returns 'it_IT';
1262
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1263
		}
1264
1265
		if ( ! $locale ) {
1266
			return false;
1267
		}
1268
1269
		if ( empty( $locale->facebook_locale ) ) {
1270
			if ( empty( $locale->wp_locale ) ) {
1271
				return false;
1272
			} else {
1273
				// Facebook SDK is smart enough to fall back to en_US if a
1274
				// locale isn't supported. Since supported Facebook locales
1275
				// can fall out of sync, we'll attempt to use the known
1276
				// wp_locale value and rely on said fallback.
1277
				return $locale->wp_locale;
1278
			}
1279
		}
1280
1281
		return $locale->facebook_locale;
1282
	}
1283
1284
	/**
1285
	 * Get the locale.
1286
	 *
1287
	 * @return string|bool
1288
	 */
1289
	function get_locale() {
1290
		$locale = $this->guess_locale_from_lang( get_locale() );
1291
1292
		if ( ! $locale ) {
1293
			$locale = 'en_US';
1294
		}
1295
1296
		return $locale;
1297
	}
1298
1299
	/**
1300
	 * Return the network_site_url so that .com knows what network this site is a part of.
1301
	 *
1302
	 * @param  bool $option
1303
	 * @return string
1304
	 */
1305
	public function jetpack_main_network_site_option( $option ) {
1306
		return network_site_url();
1307
	}
1308
	/**
1309
	 * Network Name.
1310
	 */
1311
	static function network_name( $option = null ) {
1312
		global $current_site;
1313
		return $current_site->site_name;
1314
	}
1315
	/**
1316
	 * Does the network allow new user and site registrations.
1317
	 *
1318
	 * @return string
1319
	 */
1320
	static function network_allow_new_registrations( $option = null ) {
1321
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1322
	}
1323
	/**
1324
	 * Does the network allow admins to add new users.
1325
	 *
1326
	 * @return boolian
1327
	 */
1328
	static function network_add_new_users( $option = null ) {
1329
		return (bool) get_site_option( 'add_new_users' );
1330
	}
1331
	/**
1332
	 * File upload psace left per site in MB.
1333
	 *  -1 means NO LIMIT.
1334
	 *
1335
	 * @return number
1336
	 */
1337
	static function network_site_upload_space( $option = null ) {
1338
		// value in MB
1339
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1340
	}
1341
1342
	/**
1343
	 * Network allowed file types.
1344
	 *
1345
	 * @return string
1346
	 */
1347
	static function network_upload_file_types( $option = null ) {
1348
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1349
	}
1350
1351
	/**
1352
	 * Maximum file upload size set by the network.
1353
	 *
1354
	 * @return number
1355
	 */
1356
	static function network_max_upload_file_size( $option = null ) {
1357
		// value in KB
1358
		return get_site_option( 'fileupload_maxk', 300 );
1359
	}
1360
1361
	/**
1362
	 * Lets us know if a site allows admins to manage the network.
1363
	 *
1364
	 * @return array
1365
	 */
1366
	static function network_enable_administration_menus( $option = null ) {
1367
		return get_site_option( 'menu_items' );
1368
	}
1369
1370
	/**
1371
	 * If a user has been promoted to or demoted from admin, we need to clear the
1372
	 * jetpack_other_linked_admins transient.
1373
	 *
1374
	 * @since 4.3.2
1375
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1376
	 *
1377
	 * @param int    $user_id   The user ID whose role changed.
1378
	 * @param string $role      The new role.
1379
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Should the type for parameter $old_roles not be array|null?

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2323
2324
		if ( $redirect ) {
2325
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2326
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2327
				$page = $_GET['page'];
2328
			}
2329
2330
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2331
			exit;
2332
		}
2333
	}
2334
2335
	/**
2336
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2337
	 * Make sure to tuck away module "library" files in a sub-directory.
2338
	 */
2339
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2340
		static $modules = null;
2341
2342
		if ( ! isset( $modules ) ) {
2343
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2344
			// Use the cache if we're on the front-end and it's available...
2345
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2346
				$modules = $available_modules_option[ JETPACK__VERSION ];
2347
			} else {
2348
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2349
2350
				$modules = array();
2351
2352
				foreach ( $files as $file ) {
2353
					if ( ! $headers = self::get_module( $file ) ) {
2354
						continue;
2355
					}
2356
2357
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2358
				}
2359
2360
				Jetpack_Options::update_option(
2361
					'available_modules',
2362
					array(
2363
						JETPACK__VERSION => $modules,
2364
					)
2365
				);
2366
			}
2367
		}
2368
2369
		/**
2370
		 * Filters the array of modules available to be activated.
2371
		 *
2372
		 * @since 2.4.0
2373
		 *
2374
		 * @param array $modules Array of available modules.
2375
		 * @param string $min_version Minimum version number required to use modules.
2376
		 * @param string $max_version Maximum version number required to use modules.
2377
		 */
2378
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2379
2380
		if ( ! $min_version && ! $max_version ) {
2381
			return array_keys( $mods );
2382
		}
2383
2384
		$r = array();
2385
		foreach ( $mods as $slug => $introduced ) {
2386
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2387
				continue;
2388
			}
2389
2390
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2391
				continue;
2392
			}
2393
2394
			$r[] = $slug;
2395
		}
2396
2397
		return $r;
2398
	}
2399
2400
	/**
2401
	 * Default modules loaded on activation.
2402
	 */
2403
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2404
		$return = array();
2405
2406
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2407
			$module_data = self::get_module( $module );
2408
2409
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2410
				case 'yes':
2411
					$return[] = $module;
2412
					break;
2413
				case 'public':
2414
					if ( Jetpack_Options::get_option( 'public' ) ) {
2415
						$return[] = $module;
2416
					}
2417
					break;
2418
				case 'no':
2419
				default:
2420
					break;
2421
			}
2422
		}
2423
		/**
2424
		 * Filters the array of default modules.
2425
		 *
2426
		 * @since 2.5.0
2427
		 *
2428
		 * @param array $return Array of default modules.
2429
		 * @param string $min_version Minimum version number required to use modules.
2430
		 * @param string $max_version Maximum version number required to use modules.
2431
		 */
2432
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2433
	}
2434
2435
	/**
2436
	 * Checks activated modules during auto-activation to determine
2437
	 * if any of those modules are being deprecated.  If so, close
2438
	 * them out, and add any replacement modules.
2439
	 *
2440
	 * Runs at priority 99 by default.
2441
	 *
2442
	 * This is run late, so that it can still activate a module if
2443
	 * the new module is a replacement for another that the user
2444
	 * currently has active, even if something at the normal priority
2445
	 * would kibosh everything.
2446
	 *
2447
	 * @since 2.6
2448
	 * @uses jetpack_get_default_modules filter
2449
	 * @param array $modules
2450
	 * @return array
2451
	 */
2452
	function handle_deprecated_modules( $modules ) {
2453
		$deprecated_modules = array(
2454
			'debug'            => null,  // Closed out and moved to the debugger library.
2455
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2456
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2457
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2458
		);
2459
2460
		// Don't activate SSO if they never completed activating WPCC.
2461
		if ( self::is_module_active( 'wpcc' ) ) {
2462
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2463
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2464
				$deprecated_modules['wpcc'] = null;
2465
			}
2466
		}
2467
2468
		foreach ( $deprecated_modules as $module => $replacement ) {
2469
			if ( self::is_module_active( $module ) ) {
2470
				self::deactivate_module( $module );
2471
				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...
2472
					$modules[] = $replacement;
2473
				}
2474
			}
2475
		}
2476
2477
		return array_unique( $modules );
2478
	}
2479
2480
	/**
2481
	 * Checks activated plugins during auto-activation to determine
2482
	 * if any of those plugins are in the list with a corresponding module
2483
	 * that is not compatible with the plugin. The module will not be allowed
2484
	 * to auto-activate.
2485
	 *
2486
	 * @since 2.6
2487
	 * @uses jetpack_get_default_modules filter
2488
	 * @param array $modules
2489
	 * @return array
2490
	 */
2491
	function filter_default_modules( $modules ) {
2492
2493
		$active_plugins = self::get_active_plugins();
2494
2495
		if ( ! empty( $active_plugins ) ) {
2496
2497
			// For each module we'd like to auto-activate...
2498
			foreach ( $modules as $key => $module ) {
2499
				// If there are potential conflicts for it...
2500
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2501
					// For each potential conflict...
2502
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2503
						// If that conflicting plugin is active...
2504
						if ( in_array( $plugin, $active_plugins ) ) {
2505
							// Remove that item from being auto-activated.
2506
							unset( $modules[ $key ] );
2507
						}
2508
					}
2509
				}
2510
			}
2511
		}
2512
2513
		return $modules;
2514
	}
2515
2516
	/**
2517
	 * Extract a module's slug from its full path.
2518
	 */
2519
	public static function get_module_slug( $file ) {
2520
		return str_replace( '.php', '', basename( $file ) );
2521
	}
2522
2523
	/**
2524
	 * Generate a module's path from its slug.
2525
	 */
2526
	public static function get_module_path( $slug ) {
2527
		/**
2528
		 * Filters the path of a modules.
2529
		 *
2530
		 * @since 7.4.0
2531
		 *
2532
		 * @param array $return The absolute path to a module's root php file
2533
		 * @param string $slug The module slug
2534
		 */
2535
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2536
	}
2537
2538
	/**
2539
	 * Load module data from module file. Headers differ from WordPress
2540
	 * plugin headers to avoid them being identified as standalone
2541
	 * plugins on the WordPress plugins page.
2542
	 */
2543
	public static function get_module( $module ) {
2544
		$headers = array(
2545
			'name'                      => 'Module Name',
2546
			'description'               => 'Module Description',
2547
			'sort'                      => 'Sort Order',
2548
			'recommendation_order'      => 'Recommendation Order',
2549
			'introduced'                => 'First Introduced',
2550
			'changed'                   => 'Major Changes In',
2551
			'deactivate'                => 'Deactivate',
2552
			'free'                      => 'Free',
2553
			'requires_connection'       => 'Requires Connection',
2554
			'auto_activate'             => 'Auto Activate',
2555
			'module_tags'               => 'Module Tags',
2556
			'feature'                   => 'Feature',
2557
			'additional_search_queries' => 'Additional Search Queries',
2558
			'plan_classes'              => 'Plans',
2559
		);
2560
2561
		$file = self::get_module_path( self::get_module_slug( $module ) );
2562
2563
		$mod = self::get_file_data( $file, $headers );
2564
		if ( empty( $mod['name'] ) ) {
2565
			return false;
2566
		}
2567
2568
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2569
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2570
		$mod['deactivate']           = empty( $mod['deactivate'] );
2571
		$mod['free']                 = empty( $mod['free'] );
2572
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2573
2574
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2575
			$mod['auto_activate'] = 'No';
2576
		} else {
2577
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2578
		}
2579
2580
		if ( $mod['module_tags'] ) {
2581
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2582
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2583
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2584
		} else {
2585
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2586
		}
2587
2588 View Code Duplication
		if ( $mod['plan_classes'] ) {
2589
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2590
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2591
		} else {
2592
			$mod['plan_classes'] = array( 'free' );
2593
		}
2594
2595 View Code Duplication
		if ( $mod['feature'] ) {
2596
			$mod['feature'] = explode( ',', $mod['feature'] );
2597
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2598
		} else {
2599
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2600
		}
2601
2602
		/**
2603
		 * Filters the feature array on a module.
2604
		 *
2605
		 * This filter allows you to control where each module is filtered: Recommended,
2606
		 * and the default "Other" listing.
2607
		 *
2608
		 * @since 3.5.0
2609
		 *
2610
		 * @param array   $mod['feature'] The areas to feature this module:
2611
		 *     'Recommended' shows on the main Jetpack admin screen.
2612
		 *     'Other' should be the default if no other value is in the array.
2613
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2614
		 * @param array   $mod All the currently assembled module data.
2615
		 */
2616
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2617
2618
		/**
2619
		 * Filter the returned data about a module.
2620
		 *
2621
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2622
		 * so please be careful.
2623
		 *
2624
		 * @since 3.6.0
2625
		 *
2626
		 * @param array   $mod    The details of the requested module.
2627
		 * @param string  $module The slug of the module, e.g. sharedaddy
2628
		 * @param string  $file   The path to the module source file.
2629
		 */
2630
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2631
	}
2632
2633
	/**
2634
	 * Like core's get_file_data implementation, but caches the result.
2635
	 */
2636
	public static function get_file_data( $file, $headers ) {
2637
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2638
		$file_name = basename( $file );
2639
2640
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2641
2642
		$file_data_option = get_transient( $cache_key );
2643
2644
		if ( ! is_array( $file_data_option ) ) {
2645
			delete_transient( $cache_key );
2646
			$file_data_option = false;
2647
		}
2648
2649
		if ( false === $file_data_option ) {
2650
			$file_data_option = array();
2651
		}
2652
2653
		$key           = md5( $file_name . serialize( $headers ) );
2654
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2655
2656
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2657
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2658
			return $file_data_option[ $key ];
2659
		}
2660
2661
		$data = get_file_data( $file, $headers );
2662
2663
		$file_data_option[ $key ] = $data;
2664
2665
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2666
2667
		return $data;
2668
	}
2669
2670
2671
	/**
2672
	 * Return translated module tag.
2673
	 *
2674
	 * @param string $tag Tag as it appears in each module heading.
2675
	 *
2676
	 * @return mixed
2677
	 */
2678
	public static function translate_module_tag( $tag ) {
2679
		return jetpack_get_module_i18n_tag( $tag );
2680
	}
2681
2682
	/**
2683
	 * Get i18n strings as a JSON-encoded string
2684
	 *
2685
	 * @return string The locale as JSON
2686
	 */
2687
	public static function get_i18n_data_json() {
2688
2689
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2690
		// JSON files with the file they should be included for. This is an md5
2691
		// of '_inc/build/admin.js'.
2692
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2693
2694
		$i18n_json =
2695
				   JETPACK__PLUGIN_DIR
2696
				   . 'languages/json/jetpack-'
2697
				   . get_user_locale()
2698
				   . '-'
2699
				   . $path_md5
2700
				   . '.json';
2701
2702
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2703
			$locale_data = @file_get_contents( $i18n_json );
2704
			if ( $locale_data ) {
2705
				return $locale_data;
2706
			}
2707
		}
2708
2709
		// Return valid empty Jed locale
2710
		return '{ "locale_data": { "messages": { "": {} } } }';
2711
	}
2712
2713
	/**
2714
	 * Add locale data setup to wp-i18n
2715
	 *
2716
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2717
	 *
2718
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2719
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2720
	 *
2721
	 * This method provides a safe way to request the setup multiple times but add the script at
2722
	 * most once.
2723
	 *
2724
	 * @since 6.7.0
2725
	 *
2726
	 * @return void
2727
	 */
2728
	public static function setup_wp_i18n_locale_data() {
2729
		static $script_added = false;
2730
		if ( ! $script_added ) {
2731
			$script_added = true;
2732
			wp_add_inline_script(
2733
				'wp-i18n',
2734
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2735
			);
2736
		}
2737
	}
2738
2739
	/**
2740
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2741
	 *
2742
	 * @since 3.9.2
2743
	 *
2744
	 * @param array $modules
2745
	 *
2746
	 * @return string|void
2747
	 */
2748
	public static function get_translated_modules( $modules ) {
2749
		foreach ( $modules as $index => $module ) {
2750
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2751
			if ( isset( $module['name'] ) ) {
2752
				$modules[ $index ]['name'] = $i18n_module['name'];
2753
			}
2754
			if ( isset( $module['description'] ) ) {
2755
				$modules[ $index ]['description']       = $i18n_module['description'];
2756
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2757
			}
2758
		}
2759
		return $modules;
2760
	}
2761
2762
	/**
2763
	 * Get a list of activated modules as an array of module slugs.
2764
	 */
2765
	public static function get_active_modules() {
2766
		$active = Jetpack_Options::get_option( 'active_modules' );
2767
2768
		if ( ! is_array( $active ) ) {
2769
			$active = array();
2770
		}
2771
2772
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2773
			$active[] = 'vaultpress';
2774
		} else {
2775
			$active = array_diff( $active, array( 'vaultpress' ) );
2776
		}
2777
2778
		// If protect is active on the main site of a multisite, it should be active on all sites.
2779
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2780
			$active[] = 'protect';
2781
		}
2782
2783
		/**
2784
		 * Allow filtering of the active modules.
2785
		 *
2786
		 * Gives theme and plugin developers the power to alter the modules that
2787
		 * are activated on the fly.
2788
		 *
2789
		 * @since 5.8.0
2790
		 *
2791
		 * @param array $active Array of active module slugs.
2792
		 */
2793
		$active = apply_filters( 'jetpack_active_modules', $active );
2794
2795
		return array_unique( $active );
2796
	}
2797
2798
	/**
2799
	 * Check whether or not a Jetpack module is active.
2800
	 *
2801
	 * @param string $module The slug of a Jetpack module.
2802
	 * @return bool
2803
	 *
2804
	 * @static
2805
	 */
2806
	public static function is_module_active( $module ) {
2807
		return in_array( $module, self::get_active_modules() );
2808
	}
2809
2810
	public static function is_module( $module ) {
2811
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2812
	}
2813
2814
	/**
2815
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2816
	 *
2817
	 * @param bool $catch True to start catching, False to stop.
2818
	 *
2819
	 * @static
2820
	 */
2821
	public static function catch_errors( $catch ) {
2822
		static $display_errors, $error_reporting;
2823
2824
		if ( $catch ) {
2825
			$display_errors  = @ini_set( 'display_errors', 1 );
2826
			$error_reporting = @error_reporting( E_ALL );
2827
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2828
		} else {
2829
			@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...
2830
			@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...
2831
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2832
		}
2833
	}
2834
2835
	/**
2836
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2837
	 */
2838
	public static function catch_errors_on_shutdown() {
2839
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2840
	}
2841
2842
	/**
2843
	 * Rewrite any string to make paths easier to read.
2844
	 *
2845
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2846
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2847
	 *
2848
	 * @param $string
2849
	 * @return mixed
2850
	 */
2851
	public static function alias_directories( $string ) {
2852
		// ABSPATH has a trailing slash.
2853
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2854
		// WP_CONTENT_DIR does not have a trailing slash.
2855
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2856
2857
		return $string;
2858
	}
2859
2860
	public static function activate_default_modules(
2861
		$min_version = false,
2862
		$max_version = false,
2863
		$other_modules = array(),
2864
		$redirect = null,
2865
		$send_state_messages = null
2866
	) {
2867
		$jetpack = self::init();
2868
2869
		if ( is_null( $redirect ) ) {
2870
			if (
2871
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2872
			||
2873
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2874
			||
2875
				( defined( 'WP_CLI' ) && WP_CLI )
2876
			||
2877
				( defined( 'DOING_CRON' ) && DOING_CRON )
2878
			||
2879
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2880
			) {
2881
				$redirect = false;
2882
			} elseif ( is_admin() ) {
2883
				$redirect = true;
2884
			} else {
2885
				$redirect = false;
2886
			}
2887
		}
2888
2889
		if ( is_null( $send_state_messages ) ) {
2890
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2891
		}
2892
2893
		$modules = self::get_default_modules( $min_version, $max_version );
2894
		$modules = array_merge( $other_modules, $modules );
2895
2896
		// Look for standalone plugins and disable if active.
2897
2898
		$to_deactivate = array();
2899
		foreach ( $modules as $module ) {
2900
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2901
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2902
			}
2903
		}
2904
2905
		$deactivated = array();
2906
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2907
			list( $probable_file, $probable_title ) = $deactivate_me;
2908
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2909
				$deactivated[] = $module;
2910
			}
2911
		}
2912
2913
		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...
2914
			if ( $send_state_messages ) {
2915
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2916
			}
2917
2918
			if ( $redirect ) {
2919
				$url = add_query_arg(
2920
					array(
2921
						'action'   => 'activate_default_modules',
2922
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2923
					),
2924
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2925
				);
2926
				wp_safe_redirect( $url );
2927
				exit;
2928
			}
2929
		}
2930
2931
		/**
2932
		 * Fires before default modules are activated.
2933
		 *
2934
		 * @since 1.9.0
2935
		 *
2936
		 * @param string $min_version Minimum version number required to use modules.
2937
		 * @param string $max_version Maximum version number required to use modules.
2938
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2939
		 */
2940
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2941
2942
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2943
		if ( $send_state_messages ) {
2944
			self::restate();
2945
			self::catch_errors( true );
2946
		}
2947
2948
		$active = self::get_active_modules();
2949
2950
		foreach ( $modules as $module ) {
2951
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2952
				$active[] = $module;
2953
				self::update_active_modules( $active );
2954
				continue;
2955
			}
2956
2957
			if ( $send_state_messages && in_array( $module, $active ) ) {
2958
				$module_info = self::get_module( $module );
2959 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2960
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2961
					if ( $active_state = self::state( $state ) ) {
2962
						$active_state = explode( ',', $active_state );
2963
					} else {
2964
						$active_state = array();
2965
					}
2966
					$active_state[] = $module;
2967
					self::state( $state, implode( ',', $active_state ) );
2968
				}
2969
				continue;
2970
			}
2971
2972
			$file = self::get_module_path( $module );
2973
			if ( ! file_exists( $file ) ) {
2974
				continue;
2975
			}
2976
2977
			// we'll override this later if the plugin can be included without fatal error
2978
			if ( $redirect ) {
2979
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2980
			}
2981
2982
			if ( $send_state_messages ) {
2983
				self::state( 'error', 'module_activation_failed' );
2984
				self::state( 'module', $module );
2985
			}
2986
2987
			ob_start();
2988
			require_once $file;
2989
2990
			$active[] = $module;
2991
2992 View Code Duplication
			if ( $send_state_messages ) {
2993
2994
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2995
				if ( $active_state = self::state( $state ) ) {
2996
					$active_state = explode( ',', $active_state );
2997
				} else {
2998
					$active_state = array();
2999
				}
3000
				$active_state[] = $module;
3001
				self::state( $state, implode( ',', $active_state ) );
3002
			}
3003
3004
			self::update_active_modules( $active );
3005
3006
			ob_end_clean();
3007
		}
3008
3009
		if ( $send_state_messages ) {
3010
			self::state( 'error', false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3012
		}
3013
3014
		self::catch_errors( false );
3015
		/**
3016
		 * Fires when default modules are activated.
3017
		 *
3018
		 * @since 1.9.0
3019
		 *
3020
		 * @param string $min_version Minimum version number required to use modules.
3021
		 * @param string $max_version Maximum version number required to use modules.
3022
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3023
		 */
3024
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3025
	}
3026
3027
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3028
		/**
3029
		 * Fires before a module is activated.
3030
		 *
3031
		 * @since 2.6.0
3032
		 *
3033
		 * @param string $module Module slug.
3034
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3035
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3036
		 */
3037
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3038
3039
		$jetpack = self::init();
3040
3041
		if ( ! strlen( $module ) ) {
3042
			return false;
3043
		}
3044
3045
		if ( ! self::is_module( $module ) ) {
3046
			return false;
3047
		}
3048
3049
		// If it's already active, then don't do it again
3050
		$active = self::get_active_modules();
3051
		foreach ( $active as $act ) {
3052
			if ( $act == $module ) {
3053
				return true;
3054
			}
3055
		}
3056
3057
		$module_data = self::get_module( $module );
3058
3059
		$is_development_mode = ( new Status() )->is_development_mode();
3060
		if ( ! self::is_active() ) {
3061
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3062
				return false;
3063
			}
3064
3065
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3066
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3067
				return false;
3068
			}
3069
		}
3070
3071
		// Check and see if the old plugin is active
3072
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3073
			// Deactivate the old plugin
3074
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3075
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3076
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3077
				self::state( 'deactivated_plugins', $module );
3078
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3079
				exit;
3080
			}
3081
		}
3082
3083
		// Protect won't work with mis-configured IPs
3084
		if ( 'protect' === $module ) {
3085
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3086
			if ( ! jetpack_protect_get_ip() ) {
3087
				self::state( 'message', 'protect_misconfigured_ip' );
3088
				return false;
3089
			}
3090
		}
3091
3092
		if ( ! Jetpack_Plan::supports( $module ) ) {
3093
			return false;
3094
		}
3095
3096
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3097
		self::state( 'module', $module );
3098
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3099
3100
		self::catch_errors( true );
3101
		ob_start();
3102
		require self::get_module_path( $module );
3103
		/** This action is documented in class.jetpack.php */
3104
		do_action( 'jetpack_activate_module', $module );
3105
		$active[] = $module;
3106
		self::update_active_modules( $active );
3107
3108
		self::state( 'error', false ); // the override
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3109
		ob_end_clean();
3110
		self::catch_errors( false );
3111
3112
		if ( $redirect ) {
3113
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3114
		}
3115
		if ( $exit ) {
3116
			exit;
3117
		}
3118
		return true;
3119
	}
3120
3121
	function activate_module_actions( $module ) {
3122
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3123
	}
3124
3125
	public static function deactivate_module( $module ) {
3126
		/**
3127
		 * Fires when a module is deactivated.
3128
		 *
3129
		 * @since 1.9.0
3130
		 *
3131
		 * @param string $module Module slug.
3132
		 */
3133
		do_action( 'jetpack_pre_deactivate_module', $module );
3134
3135
		$jetpack = self::init();
0 ignored issues
show
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3136
3137
		$active = self::get_active_modules();
3138
		$new    = array_filter( array_diff( $active, (array) $module ) );
3139
3140
		return self::update_active_modules( $new );
3141
	}
3142
3143
	public static function enable_module_configurable( $module ) {
3144
		$module = self::get_module_slug( $module );
3145
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3146
	}
3147
3148
	/**
3149
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3150
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3151
	 *
3152
	 * @param string $module Module slug
3153
	 * @return string $url module configuration URL
3154
	 */
3155
	public static function module_configuration_url( $module ) {
3156
		$module      = self::get_module_slug( $module );
3157
		$default_url = self::admin_url() . "#/settings?term=$module";
3158
		/**
3159
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3160
		 *
3161
		 * @since 6.9.0
3162
		 *
3163
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3164
		 */
3165
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3166
3167
		return $url;
3168
	}
3169
3170
	/* Installation */
3171
	public static function bail_on_activation( $message, $deactivate = true ) {
3172
		?>
3173
<!doctype html>
3174
<html>
3175
<head>
3176
<meta charset="<?php bloginfo( 'charset' ); ?>">
3177
<style>
3178
* {
3179
	text-align: center;
3180
	margin: 0;
3181
	padding: 0;
3182
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3183
}
3184
p {
3185
	margin-top: 1em;
3186
	font-size: 18px;
3187
}
3188
</style>
3189
<body>
3190
<p><?php echo esc_html( $message ); ?></p>
3191
</body>
3192
</html>
3193
		<?php
3194
		if ( $deactivate ) {
3195
			$plugins = get_option( 'active_plugins' );
3196
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3197
			$update  = false;
3198
			foreach ( $plugins as $i => $plugin ) {
3199
				if ( $plugin === $jetpack ) {
3200
					$plugins[ $i ] = false;
3201
					$update        = true;
3202
				}
3203
			}
3204
3205
			if ( $update ) {
3206
				update_option( 'active_plugins', array_filter( $plugins ) );
3207
			}
3208
		}
3209
		exit;
3210
	}
3211
3212
	/**
3213
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3214
	 *
3215
	 * @static
3216
	 */
3217
	public static function plugin_activation( $network_wide ) {
3218
		Jetpack_Options::update_option( 'activated', 1 );
3219
3220
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3221
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3222
		}
3223
3224
		if ( $network_wide ) {
3225
			self::state( 'network_nag', true );
0 ignored issues
show
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3226
		}
3227
3228
		// For firing one-off events (notices) immediately after activation
3229
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3230
3231
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3232
3233
		Health::on_jetpack_activated();
3234
3235
		self::plugin_initialize();
3236
	}
3237
3238
	public static function get_activation_source( $referer_url ) {
3239
3240
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3241
			return array( 'wp-cli', null );
3242
		}
3243
3244
		$referer = wp_parse_url( $referer_url );
3245
3246
		$source_type  = 'unknown';
3247
		$source_query = null;
3248
3249
		if ( ! is_array( $referer ) ) {
3250
			return array( $source_type, $source_query );
3251
		}
3252
3253
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3254
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3255
3256
		if ( isset( $referer['query'] ) ) {
3257
			parse_str( $referer['query'], $query_parts );
3258
		} else {
3259
			$query_parts = array();
3260
		}
3261
3262
		if ( $plugins_path === $referer['path'] ) {
3263
			$source_type = 'list';
3264
		} elseif ( $plugins_install_path === $referer['path'] ) {
3265
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3266
			switch ( $tab ) {
3267
				case 'popular':
3268
					$source_type = 'popular';
3269
					break;
3270
				case 'recommended':
3271
					$source_type = 'recommended';
3272
					break;
3273
				case 'favorites':
3274
					$source_type = 'favorites';
3275
					break;
3276
				case 'search':
3277
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3278
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3279
					break;
3280
				default:
3281
					$source_type = 'featured';
3282
			}
3283
		}
3284
3285
		return array( $source_type, $source_query );
3286
	}
3287
3288
	/**
3289
	 * Runs before bumping version numbers up to a new version
3290
	 *
3291
	 * @param  string $version    Version:timestamp
3292
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3293
	 * @return null              [description]
3294
	 */
3295
	public static function do_version_bump( $version, $old_version ) {
3296
		if ( ! $old_version ) { // For new sites
3297
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3298
		}
3299
	}
3300
3301
	/**
3302
	 * Sets the internal version number and activation state.
3303
	 *
3304
	 * @static
3305
	 */
3306
	public static function plugin_initialize() {
3307
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3308
			Jetpack_Options::update_option( 'activated', 2 );
3309
		}
3310
3311 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3312
			$version = $old_version = JETPACK__VERSION . ':' . time();
3313
			/** This action is documented in class.jetpack.php */
3314
			do_action( 'updating_jetpack_version', $version, false );
3315
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3316
		}
3317
3318
		self::load_modules();
3319
3320
		Jetpack_Options::delete_option( 'do_activate' );
3321
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3322
	}
3323
3324
	/**
3325
	 * Removes all connection options
3326
	 *
3327
	 * @static
3328
	 */
3329
	public static function plugin_deactivation() {
3330
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3331
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3332
			Jetpack_Network::init()->deactivate();
3333
		} else {
3334
			self::disconnect( false );
3335
			// Jetpack_Heartbeat::init()->deactivate();
3336
		}
3337
	}
3338
3339
	/**
3340
	 * Disconnects from the Jetpack servers.
3341
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3342
	 *
3343
	 * @static
3344
	 */
3345
	public static function disconnect( $update_activated_state = true ) {
3346
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3347
		$connection = self::connection();
3348
		$connection->clean_nonces( true );
3349
3350
		// If the site is in an IDC because sync is not allowed,
3351
		// let's make sure to not disconnect the production site.
3352
		if ( ! self::validate_sync_error_idc_option() ) {
3353
			$tracking = new Tracking();
3354
			$tracking->record_user_event( 'disconnect_site', array() );
3355
3356
			$connection->disconnect_site_wpcom();
3357
		}
3358
3359
		$connection->delete_all_connection_tokens();
3360
		Jetpack_IDC::clear_all_idc_options();
3361
3362
		if ( $update_activated_state ) {
3363
			Jetpack_Options::update_option( 'activated', 4 );
3364
		}
3365
3366
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3367
			// Check then record unique disconnection if site has never been disconnected previously
3368
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3369
				$jetpack_unique_connection['disconnected'] = 1;
3370
			} else {
3371
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3372
					// track unique disconnect
3373
					$jetpack = self::init();
3374
3375
					$jetpack->stat( 'connections', 'unique-disconnect' );
3376
					$jetpack->do_stats( 'server_side' );
3377
				}
3378
				// increment number of times disconnected
3379
				$jetpack_unique_connection['disconnected'] += 1;
3380
			}
3381
3382
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3383
		}
3384
3385
		// Delete all the sync related data. Since it could be taking up space.
3386
		Sender::get_instance()->uninstall();
3387
3388
		// Disable the Heartbeat cron
3389
		Jetpack_Heartbeat::init()->deactivate();
3390
	}
3391
3392
	/**
3393
	 * Unlinks the current user from the linked WordPress.com user.
3394
	 *
3395
	 * @deprecated since 7.7
3396
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3397
	 *
3398
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
3399
	 * @return Boolean Whether the disconnection of the user was successful.
3400
	 */
3401
	public static function unlink_user( $user_id = null ) {
3402
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3403
		return Connection_Manager::disconnect_user( $user_id );
3404
	}
3405
3406
	/**
3407
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3408
	 */
3409
	public static function try_registration() {
3410
		$terms_of_service = new Terms_Of_Service();
3411
		// The user has agreed to the TOS at some point by now.
3412
		$terms_of_service->agree();
3413
3414
		// Let's get some testing in beta versions and such.
3415
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3416
			// Before attempting to connect, let's make sure that the domains are viable.
3417
			$domains_to_check = array_unique(
3418
				array(
3419
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3420
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3421
				)
3422
			);
3423
			foreach ( $domains_to_check as $domain ) {
3424
				$result = self::connection()->is_usable_domain( $domain );
3425
				if ( is_wp_error( $result ) ) {
3426
					return $result;
3427
				}
3428
			}
3429
		}
3430
3431
		$result = self::register();
3432
3433
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3434
		if ( ! $result || is_wp_error( $result ) ) {
3435
			return $result;
3436
		} else {
3437
			return true;
3438
		}
3439
	}
3440
3441
	/**
3442
	 * Tracking an internal event log. Try not to put too much chaff in here.
3443
	 *
3444
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3445
	 */
3446
	public static function log( $code, $data = null ) {
3447
		// only grab the latest 200 entries
3448
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3449
3450
		// Append our event to the log
3451
		$log_entry = array(
3452
			'time'    => time(),
3453
			'user_id' => get_current_user_id(),
3454
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3455
			'code'    => $code,
3456
		);
3457
		// Don't bother storing it unless we've got some.
3458
		if ( ! is_null( $data ) ) {
3459
			$log_entry['data'] = $data;
3460
		}
3461
		$log[] = $log_entry;
3462
3463
		// Try add_option first, to make sure it's not autoloaded.
3464
		// @todo: Add an add_option method to Jetpack_Options
3465
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3466
			Jetpack_Options::update_option( 'log', $log );
3467
		}
3468
3469
		/**
3470
		 * Fires when Jetpack logs an internal event.
3471
		 *
3472
		 * @since 3.0.0
3473
		 *
3474
		 * @param array $log_entry {
3475
		 *  Array of details about the log entry.
3476
		 *
3477
		 *  @param string time Time of the event.
3478
		 *  @param int user_id ID of the user who trigerred the event.
3479
		 *  @param int blog_id Jetpack Blog ID.
3480
		 *  @param string code Unique name for the event.
3481
		 *  @param string data Data about the event.
3482
		 * }
3483
		 */
3484
		do_action( 'jetpack_log_entry', $log_entry );
3485
	}
3486
3487
	/**
3488
	 * Get the internal event log.
3489
	 *
3490
	 * @param $event (string) - only return the specific log events
3491
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3492
	 *
3493
	 * @return array of log events || WP_Error for invalid params
3494
	 */
3495
	public static function get_log( $event = false, $num = false ) {
3496
		if ( $event && ! is_string( $event ) ) {
3497
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

Loading history...
3498
		}
3499
3500
		if ( $num && ! is_numeric( $num ) ) {
3501
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

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

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

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

Loading history...
3502
		}
3503
3504
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3505
3506
		// If nothing set - act as it did before, otherwise let's start customizing the output
3507
		if ( ! $num && ! $event ) {
3508
			return $entire_log;
3509
		} else {
3510
			$entire_log = array_reverse( $entire_log );
3511
		}
3512
3513
		$custom_log_output = array();
3514
3515
		if ( $event ) {
3516
			foreach ( $entire_log as $log_event ) {
3517
				if ( $event == $log_event['code'] ) {
3518
					$custom_log_output[] = $log_event;
3519
				}
3520
			}
3521
		} else {
3522
			$custom_log_output = $entire_log;
3523
		}
3524
3525
		if ( $num ) {
3526
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3527
		}
3528
3529
		return $custom_log_output;
3530
	}
3531
3532
	/**
3533
	 * Log modification of important settings.
3534
	 */
3535
	public static function log_settings_change( $option, $old_value, $value ) {
3536
		switch ( $option ) {
3537
			case 'jetpack_sync_non_public_post_stati':
3538
				self::log( $option, $value );
3539
				break;
3540
		}
3541
	}
3542
3543
	/**
3544
	 * Return stat data for WPCOM sync
3545
	 */
3546
	public static function get_stat_data( $encode = true, $extended = true ) {
3547
		$data = Jetpack_Heartbeat::generate_stats_array();
3548
3549
		if ( $extended ) {
3550
			$additional_data = self::get_additional_stat_data();
3551
			$data            = array_merge( $data, $additional_data );
3552
		}
3553
3554
		if ( $encode ) {
3555
			return json_encode( $data );
3556
		}
3557
3558
		return $data;
3559
	}
3560
3561
	/**
3562
	 * Get additional stat data to sync to WPCOM
3563
	 */
3564
	public static function get_additional_stat_data( $prefix = '' ) {
3565
		$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...
3566
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3567
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3568
		$return[ "{$prefix}site-count" ]    = 0;
3569
3570
		if ( function_exists( 'get_blog_count' ) ) {
3571
			$return[ "{$prefix}site-count" ] = get_blog_count();
3572
		}
3573
		return $return;
3574
	}
3575
3576
	private static function get_site_user_count() {
3577
		global $wpdb;
3578
3579
		if ( function_exists( 'wp_is_large_network' ) ) {
3580
			if ( wp_is_large_network( 'users' ) ) {
3581
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3582
			}
3583
		}
3584
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3585
			// It wasn't there, so regenerate the data and save the transient
3586
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3587
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3588
		}
3589
		return $user_count;
3590
	}
3591
3592
	/* Admin Pages */
3593
3594
	function admin_init() {
3595
		// If the plugin is not connected, display a connect message.
3596
		if (
3597
			// the plugin was auto-activated and needs its candy
3598
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3599
		||
3600
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3601
			! Jetpack_Options::get_option( 'activated' )
3602
		) {
3603
			self::plugin_initialize();
3604
		}
3605
3606
		$is_development_mode = ( new Status() )->is_development_mode();
3607
		if ( ! self::is_active() && ! $is_development_mode ) {
3608
			Jetpack_Connection_Banner::init();
3609
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3610
			// Upgrade: 1.1 -> 1.1.1
3611
			// Check and see if host can verify the Jetpack servers' SSL certificate
3612
			$args       = array();
3613
			$connection = self::connection();
3614
			Client::_wp_remote_request(
3615
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3616
				$args,
3617
				true
3618
			);
3619
		}
3620
3621
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3622
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3623
		}
3624
3625
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3626
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3627
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3628
3629
		if ( self::is_active() || $is_development_mode ) {
3630
			// Artificially throw errors in certain whitelisted cases during plugin activation
3631
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3632
		}
3633
3634
		// Add custom column in wp-admin/users.php to show whether user is linked.
3635
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3636
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3637
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3638
	}
3639
3640
	function admin_body_class( $admin_body_class = '' ) {
3641
		$classes = explode( ' ', trim( $admin_body_class ) );
3642
3643
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3644
3645
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3646
		return " $admin_body_class ";
3647
	}
3648
3649
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3650
		return $admin_body_class . ' jetpack-pagestyles ';
3651
	}
3652
3653
	/**
3654
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3655
	 * This function artificially throws errors for such cases (whitelisted).
3656
	 *
3657
	 * @param string $plugin The activated plugin.
3658
	 */
3659
	function throw_error_on_activate_plugin( $plugin ) {
3660
		$active_modules = self::get_active_modules();
3661
3662
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3663
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3664
			$throw = false;
3665
3666
			// Try and make sure it really was the stats plugin
3667
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3668
				if ( 'stats.php' == basename( $plugin ) ) {
3669
					$throw = true;
3670
				}
3671
			} else {
3672
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3673
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3674
					$throw = true;
3675
				}
3676
			}
3677
3678
			if ( $throw ) {
3679
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3680
			}
3681
		}
3682
	}
3683
3684
	function intercept_plugin_error_scrape_init() {
3685
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3686
	}
3687
3688
	function intercept_plugin_error_scrape( $action, $result ) {
3689
		if ( ! $result ) {
3690
			return;
3691
		}
3692
3693
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3694
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3695
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3696
			}
3697
		}
3698
	}
3699
3700
	/**
3701
	 * Register the remote file upload request handlers, if needed.
3702
	 *
3703
	 * @access public
3704
	 */
3705
	public function add_remote_request_handlers() {
3706
		// Remote file uploads are allowed only via AJAX requests.
3707
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3708
			return;
3709
		}
3710
3711
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3712
		$remote_request_actions = array(
3713
			'jetpack_upload_file',
3714
			'jetpack_update_file',
3715
		);
3716
3717
		// phpcs:ignore WordPress.Security.NonceVerification
3718
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3719
			return;
3720
		}
3721
3722
		// Require Jetpack authentication for the remote file upload AJAX requests.
3723
		if ( ! $this->connection_manager ) {
3724
			$this->connection_manager = new Connection_Manager();
3725
		}
3726
3727
		$this->connection_manager->require_jetpack_authentication();
3728
3729
		// Register the remote file upload AJAX handlers.
3730
		foreach ( $remote_request_actions as $action ) {
3731
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3732
		}
3733
	}
3734
3735
	/**
3736
	 * Handler for Jetpack remote file uploads.
3737
	 *
3738
	 * @access public
3739
	 */
3740
	public function remote_request_handlers() {
3741
		$action = current_filter();
0 ignored issues
show
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3742
3743
		switch ( current_filter() ) {
3744
			case 'wp_ajax_nopriv_jetpack_upload_file':
3745
				$response = $this->upload_handler();
3746
				break;
3747
3748
			case 'wp_ajax_nopriv_jetpack_update_file':
3749
				$response = $this->upload_handler( true );
3750
				break;
3751
			default:
3752
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
The call to Jetpack_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...
3753
				break;
3754
		}
3755
3756
		if ( ! $response ) {
3757
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
The call to Jetpack_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...
3758
		}
3759
3760
		if ( is_wp_error( $response ) ) {
3761
			$status_code       = $response->get_error_data();
0 ignored issues
show
The method get_error_data() does not seem to exist on object<Jetpack_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...
3762
			$error             = $response->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<Jetpack_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...
3763
			$error_description = $response->get_error_message();
0 ignored issues
show
The method get_error_message() does not seem to exist on object<Jetpack_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...
3764
3765
			if ( ! is_int( $status_code ) ) {
3766
				$status_code = 400;
3767
			}
3768
3769
			status_header( $status_code );
3770
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3771
		}
3772
3773
		status_header( 200 );
3774
		if ( true === $response ) {
3775
			exit;
3776
		}
3777
3778
		die( json_encode( (object) $response ) );
3779
	}
3780
3781
	/**
3782
	 * Uploads a file gotten from the global $_FILES.
3783
	 * If `$update_media_item` is true and `post_id` is defined
3784
	 * the attachment file of the media item (gotten through of the post_id)
3785
	 * will be updated instead of add a new one.
3786
	 *
3787
	 * @param  boolean $update_media_item - update media attachment
3788
	 * @return array - An array describing the uploadind files process
3789
	 */
3790
	function upload_handler( $update_media_item = false ) {
3791
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3792
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
The call to Jetpack_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...
3793
		}
3794
3795
		$user = wp_authenticate( '', '' );
3796
		if ( ! $user || is_wp_error( $user ) ) {
3797
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
The call to Jetpack_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...
3798
		}
3799
3800
		wp_set_current_user( $user->ID );
3801
3802
		if ( ! current_user_can( 'upload_files' ) ) {
3803
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
The call to Jetpack_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...
3804
		}
3805
3806
		if ( empty( $_FILES ) ) {
3807
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
The call to Jetpack_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...
3808
		}
3809
3810
		foreach ( array_keys( $_FILES ) as $files_key ) {
3811
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3812
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
The call to Jetpack_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...
3813
			}
3814
		}
3815
3816
		$media_keys = array_keys( $_FILES['media'] );
3817
3818
		$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...
3819
		if ( ! $token || is_wp_error( $token ) ) {
3820
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
The call to Jetpack_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...
3821
		}
3822
3823
		$uploaded_files = array();
3824
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3825
		unset( $GLOBALS['post'] );
3826
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3827
			$file = array();
3828
			foreach ( $media_keys as $media_key ) {
3829
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3830
			}
3831
3832
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3833
3834
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3835
			if ( $hmac_provided !== $hmac_file ) {
3836
				$uploaded_files[ $index ] = (object) array(
3837
					'error'             => 'invalid_hmac',
3838
					'error_description' => 'The corresponding HMAC for this file does not match',
3839
				);
3840
				continue;
3841
			}
3842
3843
			$_FILES['.jetpack.upload.'] = $file;
3844
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3845
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3846
				$post_id = 0;
3847
			}
3848
3849
			if ( $update_media_item ) {
3850
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3851
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
The call to Jetpack_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...
3852
				}
3853
3854
				$media_array = $_FILES['media'];
3855
3856
				$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...
3857
				$file_array['type']     = $media_array['type'][0];
3858
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3859
				$file_array['error']    = $media_array['error'][0];
3860
				$file_array['size']     = $media_array['size'][0];
3861
3862
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3863
3864
				if ( is_wp_error( $edited_media_item ) ) {
3865
					return $edited_media_item;
3866
				}
3867
3868
				$response = (object) array(
3869
					'id'   => (string) $post_id,
3870
					'file' => (string) $edited_media_item->post_title,
3871
					'url'  => (string) wp_get_attachment_url( $post_id ),
3872
					'type' => (string) $edited_media_item->post_mime_type,
3873
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3874
				);
3875
3876
				return (array) array( $response );
3877
			}
3878
3879
			$attachment_id = media_handle_upload(
3880
				'.jetpack.upload.',
3881
				$post_id,
3882
				array(),
3883
				array(
3884
					'action' => 'jetpack_upload_file',
3885
				)
3886
			);
3887
3888
			if ( ! $attachment_id ) {
3889
				$uploaded_files[ $index ] = (object) array(
3890
					'error'             => 'unknown',
3891
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3892
				);
3893
			} elseif ( is_wp_error( $attachment_id ) ) {
3894
				$uploaded_files[ $index ] = (object) array(
3895
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3896
					'error_description' => $attachment_id->get_error_message(),
3897
				);
3898
			} else {
3899
				$attachment               = get_post( $attachment_id );
3900
				$uploaded_files[ $index ] = (object) array(
3901
					'id'   => (string) $attachment_id,
3902
					'file' => $attachment->post_title,
3903
					'url'  => wp_get_attachment_url( $attachment_id ),
3904
					'type' => $attachment->post_mime_type,
3905
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3906
				);
3907
				// Zip files uploads are not supported unless they are done for installation purposed
3908
				// lets delete them in case something goes wrong in this whole process
3909
				if ( 'application/zip' === $attachment->post_mime_type ) {
3910
					// Schedule a cleanup for 2 hours from now in case of failed install.
3911
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3912
				}
3913
			}
3914
		}
3915
		if ( ! is_null( $global_post ) ) {
3916
			$GLOBALS['post'] = $global_post;
3917
		}
3918
3919
		return $uploaded_files;
3920
	}
3921
3922
	/**
3923
	 * Add help to the Jetpack page
3924
	 *
3925
	 * @since Jetpack (1.2.3)
3926
	 * @return false if not the Jetpack page
3927
	 */
3928
	function admin_help() {
3929
		$current_screen = get_current_screen();
3930
3931
		// Overview
3932
		$current_screen->add_help_tab(
3933
			array(
3934
				'id'      => 'home',
3935
				'title'   => __( 'Home', 'jetpack' ),
3936
				'content' =>
3937
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3938
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3939
					'<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>',
3940
			)
3941
		);
3942
3943
		// Screen Content
3944
		if ( current_user_can( 'manage_options' ) ) {
3945
			$current_screen->add_help_tab(
3946
				array(
3947
					'id'      => 'settings',
3948
					'title'   => __( 'Settings', 'jetpack' ),
3949
					'content' =>
3950
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3951
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3952
						'<ol>' .
3953
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3954
							'<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>' .
3955
						'</ol>' .
3956
						'<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>',
3957
				)
3958
			);
3959
		}
3960
3961
		// Help Sidebar
3962
		$current_screen->set_help_sidebar(
3963
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3964
			'<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3965
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3966
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3967
		);
3968
	}
3969
3970
	function admin_menu_css() {
3971
		wp_enqueue_style( 'jetpack-icons' );
3972
	}
3973
3974
	function admin_menu_order() {
3975
		return true;
3976
	}
3977
3978 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3979
		$jp_menu_order = array();
3980
3981
		foreach ( $menu_order as $index => $item ) {
3982
			if ( $item != 'jetpack' ) {
3983
				$jp_menu_order[] = $item;
3984
			}
3985
3986
			if ( $index == 0 ) {
3987
				$jp_menu_order[] = 'jetpack';
3988
			}
3989
		}
3990
3991
		return $jp_menu_order;
3992
	}
3993
3994
	function admin_banner_styles() {
3995
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3996
3997 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3998
			wp_register_style(
3999
				'jetpack-dops-style',
4000
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4001
				array(),
4002
				JETPACK__VERSION
4003
			);
4004
		}
4005
4006
		wp_enqueue_style(
4007
			'jetpack',
4008
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4009
			array( 'jetpack-dops-style' ),
4010
			JETPACK__VERSION . '-20121016'
4011
		);
4012
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4013
		wp_style_add_data( 'jetpack', 'suffix', $min );
4014
	}
4015
4016
	function plugin_action_links( $actions ) {
4017
4018
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4019
4020
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4021
			return array_merge(
4022
				$jetpack_home,
4023
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4024
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4025
				$actions
4026
			);
4027
		}
4028
4029
		return array_merge( $jetpack_home, $actions );
4030
	}
4031
4032
	/*
4033
	 * Registration flow:
4034
	 * 1 - ::admin_page_load() action=register
4035
	 * 2 - ::try_registration()
4036
	 * 3 - ::register()
4037
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4038
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4039
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4040
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4041
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4042
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4043
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4044
	 *       jetpack_id, jetpack_secret, jetpack_public
4045
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4046
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4047
	 * 5 - user logs in with WP.com account
4048
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4049
	 *		- Manager::authorize()
4050
	 *		- Manager::get_token()
4051
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4052
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4053
	 *			- which responds with access_token, token_type, scope
4054
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4055
	 *		- Jetpack::activate_default_modules()
4056
	 *     		- Deactivates deprecated plugins
4057
	 *     		- Activates all default modules
4058
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4059
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4060
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4061
	 *     Done!
4062
	 */
4063
4064
	/**
4065
	 * Handles the page load events for the Jetpack admin page
4066
	 */
4067
	function admin_page_load() {
4068
		$error = false;
4069
4070
		// Make sure we have the right body class to hook stylings for subpages off of.
4071
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4072
4073
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4074
			// Should only be used in intermediate redirects to preserve state across redirects
4075
			self::restate();
4076
		}
4077
4078
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4079
			// @todo: Add validation against a known whitelist
4080
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4081
			// User clicked in the iframe to link their accounts
4082
			if ( ! self::is_user_connected() ) {
4083
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4084
4085
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4086
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4087
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4088
4089
				if ( isset( $_GET['notes_iframe'] ) ) {
4090
					$connect_url .= '&notes_iframe';
4091
				}
4092
				wp_redirect( $connect_url );
4093
				exit;
4094
			} else {
4095
				if ( ! isset( $_GET['calypso_env'] ) ) {
4096
					self::state( 'message', 'already_authorized' );
4097
					wp_safe_redirect( self::admin_url() );
4098
					exit;
4099
				} else {
4100
					$connect_url  = $this->build_connect_url( true, false, $from );
4101
					$connect_url .= '&already_authorized=true';
4102
					wp_redirect( $connect_url );
4103
					exit;
4104
				}
4105
			}
4106
		}
4107
4108
		if ( isset( $_GET['action'] ) ) {
4109
			switch ( $_GET['action'] ) {
4110
				case 'authorize':
4111
					if ( self::is_active() && self::is_user_connected() ) {
4112
						self::state( 'message', 'already_authorized' );
4113
						wp_safe_redirect( self::admin_url() );
4114
						exit;
4115
					}
4116
					self::log( 'authorize' );
4117
					$client_server = new Jetpack_Client_Server();
4118
					$client_server->client_authorize();
4119
					exit;
4120
				case 'register':
4121
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4122
						$error = 'cheatin';
4123
						break;
4124
					}
4125
					check_admin_referer( 'jetpack-register' );
4126
					self::log( 'register' );
4127
					self::maybe_set_version_option();
4128
					$registered = self::try_registration();
4129 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4130
						$error = $registered->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

Loading history...
4133
4134
						/**
4135
						 * Jetpack registration Error.
4136
						 *
4137
						 * @since 7.5.0
4138
						 *
4139
						 * @param string|int $error The error code.
4140
						 * @param \WP_Error $registered The error object.
4141
						 */
4142
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4143
						break;
4144
					}
4145
4146
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4147
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4148
4149
					/**
4150
					 * Jetpack registration Success.
4151
					 *
4152
					 * @since 7.5.0
4153
					 *
4154
					 * @param string $from 'from' GET parameter;
4155
					 */
4156
					do_action( 'jetpack_connection_register_success', $from );
4157
4158
					$url = $this->build_connect_url( true, $redirect, $from );
4159
4160
					if ( ! empty( $_GET['onboarding'] ) ) {
4161
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4162
					}
4163
4164
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4165
						$url = add_query_arg( 'auth_approved', 'true', $url );
4166
					}
4167
4168
					wp_redirect( $url );
4169
					exit;
4170
				case 'activate':
4171
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4172
						$error = 'cheatin';
4173
						break;
4174
					}
4175
4176
					$module = stripslashes( $_GET['module'] );
4177
					check_admin_referer( "jetpack_activate-$module" );
4178
					self::log( 'activate', $module );
4179
					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...
4180
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4181
					}
4182
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4183
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4184
					exit;
4185
				case 'activate_default_modules':
4186
					check_admin_referer( 'activate_default_modules' );
4187
					self::log( 'activate_default_modules' );
4188
					self::restate();
4189
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4190
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4191
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4192
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4193
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4194
					exit;
4195
				case 'disconnect':
4196
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4197
						$error = 'cheatin';
4198
						break;
4199
					}
4200
4201
					check_admin_referer( 'jetpack-disconnect' );
4202
					self::log( 'disconnect' );
4203
					self::disconnect();
4204
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4205
					exit;
4206
				case 'reconnect':
4207
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4208
						$error = 'cheatin';
4209
						break;
4210
					}
4211
4212
					check_admin_referer( 'jetpack-reconnect' );
4213
					self::log( 'reconnect' );
4214
					$this->disconnect();
4215
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4216
					exit;
4217 View Code Duplication
				case 'deactivate':
4218
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4219
						$error = 'cheatin';
4220
						break;
4221
					}
4222
4223
					$modules = stripslashes( $_GET['module'] );
4224
					check_admin_referer( "jetpack_deactivate-$modules" );
4225
					foreach ( explode( ',', $modules ) as $module ) {
4226
						self::log( 'deactivate', $module );
4227
						self::deactivate_module( $module );
4228
						self::state( 'message', 'module_deactivated' );
4229
					}
4230
					self::state( 'module', $modules );
4231
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4232
					exit;
4233
				case 'unlink':
4234
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4235
					check_admin_referer( 'jetpack-unlink' );
4236
					self::log( 'unlink' );
4237
					Connection_Manager::disconnect_user();
4238
					self::state( 'message', 'unlinked' );
4239
					if ( 'sub-unlink' == $redirect ) {
4240
						wp_safe_redirect( admin_url() );
4241
					} else {
4242
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4243
					}
4244
					exit;
4245
				case 'onboard':
4246
					if ( ! current_user_can( 'manage_options' ) ) {
4247
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4248
					} else {
4249
						self::create_onboarding_token();
4250
						$url = $this->build_connect_url( true );
4251
4252
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4253
							$url = add_query_arg( 'onboarding', $token, $url );
4254
						}
4255
4256
						$calypso_env = $this->get_calypso_env();
4257
						if ( ! empty( $calypso_env ) ) {
4258
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4259
						}
4260
4261
						wp_redirect( $url );
4262
						exit;
4263
					}
4264
					exit;
4265
				default:
4266
					/**
4267
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4268
					 *
4269
					 * @since 2.6.0
4270
					 *
4271
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4272
					 */
4273
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4274
			}
4275
		}
4276
4277
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4278
			self::activate_new_modules( true );
4279
		}
4280
4281
		$message_code = self::state( 'message' );
4282
		if ( self::state( 'optin-manage' ) ) {
4283
			$activated_manage = $message_code;
4284
			$message_code     = 'jetpack-manage';
4285
		}
4286
4287
		switch ( $message_code ) {
4288
			case 'jetpack-manage':
4289
				$sites_url = esc_url( self::build_redirect_url( 'calypso-sites' ) );
4290
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4291
				$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>';
4292
				if ( $activated_manage ) {
0 ignored issues
show
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4293
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4294
				}
4295
				break;
4296
4297
		}
4298
4299
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4300
4301
		if ( ! empty( $deactivated_plugins ) ) {
4302
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4303
			$deactivated_titles  = array();
4304
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4305
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4306
					continue;
4307
				}
4308
4309
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4310
			}
4311
4312
			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...
4313
				if ( $this->message ) {
4314
					$this->message .= "<br /><br />\n";
4315
				}
4316
4317
				$this->message .= wp_sprintf(
4318
					_n(
4319
						'Jetpack contains the most recent version of the old %l plugin.',
4320
						'Jetpack contains the most recent versions of the old %l plugins.',
4321
						count( $deactivated_titles ),
4322
						'jetpack'
4323
					),
4324
					$deactivated_titles
4325
				);
4326
4327
				$this->message .= "<br />\n";
4328
4329
				$this->message .= _n(
4330
					'The old version has been deactivated and can be removed from your site.',
4331
					'The old versions have been deactivated and can be removed from your site.',
4332
					count( $deactivated_titles ),
4333
					'jetpack'
4334
				);
4335
			}
4336
		}
4337
4338
		$this->privacy_checks = self::state( 'privacy_checks' );
4339
4340
		if ( $this->message || $this->error || $this->privacy_checks ) {
4341
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4342
		}
4343
4344
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4345
	}
4346
4347
	function admin_notices() {
4348
4349
		if ( $this->error ) {
4350
			?>
4351
<div id="message" class="jetpack-message jetpack-err">
4352
	<div class="squeezer">
4353
		<h2>
4354
			<?php
4355
			echo wp_kses(
4356
				$this->error,
4357
				array(
4358
					'a'      => array( 'href' => array() ),
4359
					'small'  => true,
4360
					'code'   => true,
4361
					'strong' => true,
4362
					'br'     => true,
4363
					'b'      => true,
4364
				)
4365
			);
4366
			?>
4367
			</h2>
4368
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4369
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4370
<?php	endif; ?>
4371
	</div>
4372
</div>
4373
			<?php
4374
		}
4375
4376
		if ( $this->message ) {
4377
			?>
4378
<div id="message" class="jetpack-message">
4379
	<div class="squeezer">
4380
		<h2>
4381
			<?php
4382
			echo wp_kses(
4383
				$this->message,
4384
				array(
4385
					'strong' => array(),
4386
					'a'      => array( 'href' => true ),
4387
					'br'     => true,
4388
				)
4389
			);
4390
			?>
4391
			</h2>
4392
	</div>
4393
</div>
4394
			<?php
4395
		}
4396
4397
		if ( $this->privacy_checks ) :
4398
			$module_names = $module_slugs = array();
4399
4400
			$privacy_checks = explode( ',', $this->privacy_checks );
4401
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4402
			foreach ( $privacy_checks as $module_slug ) {
4403
				$module = self::get_module( $module_slug );
4404
				if ( ! $module ) {
4405
					continue;
4406
				}
4407
4408
				$module_slugs[] = $module_slug;
4409
				$module_names[] = "<strong>{$module['name']}</strong>";
4410
			}
4411
4412
			$module_slugs = join( ',', $module_slugs );
4413
			?>
4414
<div id="message" class="jetpack-message jetpack-err">
4415
	<div class="squeezer">
4416
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4417
		<p>
4418
			<?php
4419
			echo wp_kses(
4420
				wptexturize(
4421
					wp_sprintf(
4422
						_nx(
4423
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4424
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4425
							count( $privacy_checks ),
4426
							'%l = list of Jetpack module/feature names',
4427
							'jetpack'
4428
						),
4429
						$module_names
4430
					)
4431
				),
4432
				array( 'strong' => true )
4433
			);
4434
4435
			echo "\n<br />\n";
4436
4437
			echo wp_kses(
4438
				sprintf(
4439
					_nx(
4440
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4441
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4442
						count( $privacy_checks ),
4443
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4444
						'jetpack'
4445
					),
4446
					wp_nonce_url(
4447
						self::admin_url(
4448
							array(
4449
								'page'   => 'jetpack',
4450
								'action' => 'deactivate',
4451
								'module' => urlencode( $module_slugs ),
4452
							)
4453
						),
4454
						"jetpack_deactivate-$module_slugs"
4455
					),
4456
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4457
				),
4458
				array(
4459
					'a' => array(
4460
						'href'  => true,
4461
						'title' => true,
4462
					),
4463
				)
4464
			);
4465
			?>
4466
		</p>
4467
	</div>
4468
</div>
4469
			<?php
4470
endif;
4471
	}
4472
4473
	/**
4474
	 * We can't always respond to a signed XML-RPC request with a
4475
	 * helpful error message. In some circumstances, doing so could
4476
	 * leak information.
4477
	 *
4478
	 * Instead, track that the error occurred via a Jetpack_Option,
4479
	 * and send that data back in the heartbeat.
4480
	 * All this does is increment a number, but it's enough to find
4481
	 * trends.
4482
	 *
4483
	 * @param WP_Error $xmlrpc_error The error produced during
4484
	 *                               signature validation.
4485
	 */
4486
	function track_xmlrpc_error( $xmlrpc_error ) {
4487
		$code = is_wp_error( $xmlrpc_error )
4488
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

Loading history...
4489
			: 'should-not-happen';
4490
4491
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4492
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4493
			// No need to update the option if we already have
4494
			// this code stored.
4495
			return;
4496
		}
4497
		$xmlrpc_errors[ $code ] = true;
4498
4499
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4500
	}
4501
4502
	/**
4503
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4504
	 */
4505
	function stat( $group, $detail ) {
4506
		if ( ! isset( $this->stats[ $group ] ) ) {
4507
			$this->stats[ $group ] = array();
4508
		}
4509
		$this->stats[ $group ][] = $detail;
4510
	}
4511
4512
	/**
4513
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4514
	 */
4515
	function do_stats( $method = '' ) {
4516
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4517
			foreach ( $this->stats as $group => $stats ) {
4518
				if ( is_array( $stats ) && count( $stats ) ) {
4519
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4520
					if ( 'server_side' === $method ) {
4521
						self::do_server_side_stat( $args );
4522
					} else {
4523
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4524
					}
4525
				}
4526
				unset( $this->stats[ $group ] );
4527
			}
4528
		}
4529
	}
4530
4531
	/**
4532
	 * Runs stats code for a one-off, server-side.
4533
	 *
4534
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4535
	 *
4536
	 * @return bool If it worked.
4537
	 */
4538
	static function do_server_side_stat( $args ) {
4539
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4540
		if ( is_wp_error( $response ) ) {
4541
			return false;
4542
		}
4543
4544
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4545
			return false;
4546
		}
4547
4548
		return true;
4549
	}
4550
4551
	/**
4552
	 * Builds the stats url.
4553
	 *
4554
	 * @param $args array|string The arguments to append to the URL.
4555
	 *
4556
	 * @return string The URL to be pinged.
4557
	 */
4558
	static function build_stats_url( $args ) {
4559
		$defaults = array(
4560
			'v'    => 'wpcom2',
4561
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4562
		);
4563
		$args     = wp_parse_args( $args, $defaults );
4564
		/**
4565
		 * Filter the URL used as the Stats tracking pixel.
4566
		 *
4567
		 * @since 2.3.2
4568
		 *
4569
		 * @param string $url Base URL used as the Stats tracking pixel.
4570
		 */
4571
		$base_url = apply_filters(
4572
			'jetpack_stats_base_url',
4573
			'https://pixel.wp.com/g.gif'
4574
		);
4575
		$url      = add_query_arg( $args, $base_url );
4576
		return $url;
4577
	}
4578
4579
	/**
4580
	 * Get the role of the current user.
4581
	 *
4582
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4583
	 *
4584
	 * @access public
4585
	 * @static
4586
	 *
4587
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4588
	 */
4589
	public static function translate_current_user_to_role() {
4590
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4591
4592
		$roles = new Roles();
4593
		return $roles->translate_current_user_to_role();
4594
	}
4595
4596
	/**
4597
	 * Get the role of a particular user.
4598
	 *
4599
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4600
	 *
4601
	 * @access public
4602
	 * @static
4603
	 *
4604
	 * @param \WP_User $user User object.
4605
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4606
	 */
4607
	public static function translate_user_to_role( $user ) {
4608
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4609
4610
		$roles = new Roles();
4611
		return $roles->translate_user_to_role( $user );
4612
	}
4613
4614
	/**
4615
	 * Get the minimum capability for a role.
4616
	 *
4617
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4618
	 *
4619
	 * @access public
4620
	 * @static
4621
	 *
4622
	 * @param string $role Role name.
4623
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4624
	 */
4625
	public static function translate_role_to_cap( $role ) {
4626
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4627
4628
		$roles = new Roles();
4629
		return $roles->translate_role_to_cap( $role );
4630
	}
4631
4632
	/**
4633
	 * Sign a user role with the master access token.
4634
	 * If not specified, will default to the current user.
4635
	 *
4636
	 * @deprecated since 7.7
4637
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4638
	 *
4639
	 * @access public
4640
	 * @static
4641
	 *
4642
	 * @param string $role    User role.
4643
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
4644
	 * @return string Signed user role.
4645
	 */
4646
	public static function sign_role( $role, $user_id = null ) {
4647
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4648
		return self::connection()->sign_role( $role, $user_id );
4649
	}
4650
4651
	/**
4652
	 * Builds a URL to the Jetpack connection auth page
4653
	 *
4654
	 * @since 3.9.5
4655
	 *
4656
	 * @param bool        $raw If true, URL will not be escaped.
4657
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4658
	 *                              If string, will be a custom redirect.
4659
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4660
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4661
	 *
4662
	 * @return string Connect URL
4663
	 */
4664
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4665
		$site_id    = Jetpack_Options::get_option( 'id' );
4666
		$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...
4667
4668
		if ( $register || ! $blog_token || ! $site_id ) {
4669
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4670
4671
			if ( ! empty( $redirect ) ) {
4672
				$url = add_query_arg(
4673
					'redirect',
4674
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4675
					$url
4676
				);
4677
			}
4678
4679
			if ( is_network_admin() ) {
4680
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4681
			}
4682
4683
			$calypso_env = self::get_calypso_env();
4684
4685
			if ( ! empty( $calypso_env ) ) {
4686
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4687
			}
4688
		} else {
4689
4690
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4691
			// because otherwise this logic can get us in to a loop.
4692
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4693
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4694
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4695
4696
				$response = Client::wpcom_json_api_request_as_blog(
4697
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4698
					'1.1'
4699
				);
4700
4701
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4702
4703
					// Generating a register URL instead to refresh the existing token
4704
					return $this->build_connect_url( $raw, $redirect, $from, true );
4705
				}
4706
			}
4707
4708
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4664 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...
4709
		}
4710
4711
		if ( $from ) {
4712
			$url = add_query_arg( 'from', $from, $url );
4713
		}
4714
4715
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4716
		/**
4717
		 * Filter the URL used when connecting a user to a WordPress.com account.
4718
		 *
4719
		 * @since 8.1.0
4720
		 *
4721
		 * @param string $url Connection URL.
4722
		 * @param bool   $raw If true, URL will not be escaped.
4723
		 */
4724
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4725
	}
4726
4727
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4728
4729
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4730
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4731
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4732
4733
		if ( $iframe ) {
4734
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4735
		}
4736
4737
		$c8n = self::connection();
4738
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
$redirect is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4739
4740
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4741
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4742
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4743
4744
		if ( $iframe ) {
4745
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4746
		}
4747
4748
		return $url;
4749
	}
4750
4751
	/**
4752
	 * Filters the connection URL parameter array.
4753
	 *
4754
	 * @param Array $args default URL parameters used by the package.
4755
	 * @return Array the modified URL arguments array.
4756
	 */
4757
	public static function filter_connect_request_body( $args ) {
4758
		if (
4759
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4760
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4761
		) {
4762
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4763
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4764
				? $gp_locale->slug
4765
				: '';
4766
		}
4767
4768
		$tracking        = new Tracking();
4769
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4770
4771
		$args = array_merge(
4772
			$args,
4773
			array(
4774
				'_ui' => $tracks_identity['_ui'],
4775
				'_ut' => $tracks_identity['_ut'],
4776
			)
4777
		);
4778
4779
		$calypso_env = self::get_calypso_env();
4780
4781
		if ( ! empty( $calypso_env ) ) {
4782
			$args['calypso_env'] = $calypso_env;
4783
		}
4784
4785
		return $args;
4786
	}
4787
4788
	/**
4789
	 * Filters the URL that will process the connection data. It can be different from the URL
4790
	 * that we send the user to after everything is done.
4791
	 *
4792
	 * @param String $processing_url the default redirect URL used by the package.
4793
	 * @return String the modified URL.
4794
	 */
4795
	public static function filter_connect_processing_url( $processing_url ) {
4796
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4797
		return $processing_url;
4798
	}
4799
4800
	/**
4801
	 * Filters the redirection URL that is used for connect requests. The redirect
4802
	 * URL should return the user back to the Jetpack console.
4803
	 *
4804
	 * @param String $redirect the default redirect URL used by the package.
4805
	 * @return String the modified URL.
4806
	 */
4807
	public static function filter_connect_redirect_url( $redirect ) {
4808
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4809
		$redirect           = $redirect
4810
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4811
			: $jetpack_admin_page;
4812
4813
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4814
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4815
		}
4816
4817
		return $redirect;
4818
	}
4819
4820
	/**
4821
	 * This action fires at the beginning of the Manager::authorize method.
4822
	 */
4823
	public static function authorize_starting() {
4824
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4825
		// Checking if site has been active/connected previously before recording unique connection.
4826
		if ( ! $jetpack_unique_connection ) {
4827
			// jetpack_unique_connection option has never been set.
4828
			$jetpack_unique_connection = array(
4829
				'connected'    => 0,
4830
				'disconnected' => 0,
4831
				'version'      => '3.6.1',
4832
			);
4833
4834
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4835
4836
			// Track unique connection.
4837
			$jetpack = self::init();
4838
4839
			$jetpack->stat( 'connections', 'unique-connection' );
4840
			$jetpack->do_stats( 'server_side' );
4841
		}
4842
4843
		// Increment number of times connected.
4844
		$jetpack_unique_connection['connected'] += 1;
4845
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4846
	}
4847
4848
	/**
4849
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4850
	 * linked.
4851
	 */
4852
	public static function authorize_ending_linked() {
4853
		// Don't activate anything since we are just connecting a user.
4854
		self::state( 'message', 'linked' );
4855
	}
4856
4857
	/**
4858
	 * This action fires at the end of the Manager::authorize method when the master user is
4859
	 * authorized.
4860
	 *
4861
	 * @param array $data The request data.
4862
	 */
4863
	public static function authorize_ending_authorized( $data ) {
4864
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4865
		self::invalidate_onboarding_token();
4866
4867
		// If redirect_uri is SSO, ensure SSO module is enabled.
4868
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4869
4870
		/** This filter is documented in class.jetpack-cli.php */
4871
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4872
4873
		$activate_sso = (
4874
			isset( $redirect_options['action'] ) &&
4875
			'jetpack-sso' === $redirect_options['action'] &&
4876
			$jetpack_start_enable_sso
4877
		);
4878
4879
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4880
4881
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4882
	}
4883
4884
	/**
4885
	 * Get our assumed site creation date.
4886
	 * Calculated based on the earlier date of either:
4887
	 * - Earliest admin user registration date.
4888
	 * - Earliest date of post of any post type.
4889
	 *
4890
	 * @since 7.2.0
4891
	 * @deprecated since 7.8.0
4892
	 *
4893
	 * @return string Assumed site creation date and time.
4894
	 */
4895
	public static function get_assumed_site_creation_date() {
4896
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4897
		return self::connection()->get_assumed_site_creation_date();
4898
	}
4899
4900 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4901
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4902
4903
		if ( $activation_source_name ) {
4904
			$args['_as'] = urlencode( $activation_source_name );
4905
		}
4906
4907
		if ( $activation_source_keyword ) {
4908
			$args['_ak'] = urlencode( $activation_source_keyword );
4909
		}
4910
	}
4911
4912
	function build_reconnect_url( $raw = false ) {
4913
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4914
		return $raw ? $url : esc_url( $url );
4915
	}
4916
4917
	public static function admin_url( $args = null ) {
4918
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4919
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4920
		return $url;
4921
	}
4922
4923
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4924
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4925
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4926
	}
4927
4928
	function dismiss_jetpack_notice() {
4929
4930
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4931
			return;
4932
		}
4933
4934
		switch ( $_GET['jetpack-notice'] ) {
4935
			case 'dismiss':
4936
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4937
4938
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4939
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4940
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4941
				}
4942
				break;
4943
		}
4944
	}
4945
4946
	public static function sort_modules( $a, $b ) {
4947
		if ( $a['sort'] == $b['sort'] ) {
4948
			return 0;
4949
		}
4950
4951
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4952
	}
4953
4954
	function ajax_recheck_ssl() {
4955
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4956
		$result = self::permit_ssl( true );
4957
		wp_send_json(
4958
			array(
4959
				'enabled' => $result,
4960
				'message' => get_transient( 'jetpack_https_test_message' ),
4961
			)
4962
		);
4963
	}
4964
4965
	/* Client API */
4966
4967
	/**
4968
	 * Returns the requested Jetpack API URL
4969
	 *
4970
	 * @deprecated since 7.7
4971
	 * @return string
4972
	 */
4973
	public static function api_url( $relative_url ) {
4974
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4975
		$connection = self::connection();
4976
		return $connection->api_url( $relative_url );
4977
	}
4978
4979
	/**
4980
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
4981
	 *
4982
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4983
	 */
4984
	public static function fix_url_for_bad_hosts( $url ) {
4985
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
4986
		return Connection_Utils::fix_url_for_bad_hosts( $url );
4987
	}
4988
4989
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4990
		// Default to a blog token.
4991
		$token_type = 'blog';
4992
4993
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4994
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4995
			if ( ! empty( $_GET['onboarding'] ) ) {
4996
				$jpo = $_GET;
4997
			} else {
4998
				$jpo = json_decode( $request_data, true );
4999
			}
5000
5001
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5002
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5003
5004
			if (
5005
				isset( $jpo_user )
5006
				&& isset( $jpo_token )
5007
				&& is_email( $jpo_user )
5008
				&& ctype_alnum( $jpo_token )
5009
				&& isset( $_GET['rest_route'] )
5010
				&& self::validate_onboarding_token_action(
5011
					$jpo_token,
5012
					$_GET['rest_route']
5013
				)
5014
			) {
5015
				$jp_user = get_user_by( 'email', $jpo_user );
5016
				if ( is_a( $jp_user, 'WP_User' ) ) {
5017
					wp_set_current_user( $jp_user->ID );
5018
					$user_can = is_multisite()
5019
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5020
						: current_user_can( 'manage_options' );
5021
					if ( $user_can ) {
5022
						$token_type              = 'user';
5023
						$token->external_user_id = $jp_user->ID;
5024
					}
5025
				}
5026
			}
5027
5028
			$token_data['type']    = $token_type;
5029
			$token_data['user_id'] = $token->external_user_id;
5030
		}
5031
5032
		return $token_data;
5033
	}
5034
5035
	/**
5036
	 * Create a random secret for validating onboarding payload
5037
	 *
5038
	 * @return string Secret token
5039
	 */
5040
	public static function create_onboarding_token() {
5041
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5042
			$token = wp_generate_password( 32, false );
5043
			Jetpack_Options::update_option( 'onboarding', $token );
5044
		}
5045
5046
		return $token;
5047
	}
5048
5049
	/**
5050
	 * Remove the onboarding token
5051
	 *
5052
	 * @return bool True on success, false on failure
5053
	 */
5054
	public static function invalidate_onboarding_token() {
5055
		return Jetpack_Options::delete_option( 'onboarding' );
5056
	}
5057
5058
	/**
5059
	 * Validate an onboarding token for a specific action
5060
	 *
5061
	 * @return boolean True if token/action pair is accepted, false if not
5062
	 */
5063
	public static function validate_onboarding_token_action( $token, $action ) {
5064
		// Compare tokens, bail if tokens do not match
5065
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5066
			return false;
5067
		}
5068
5069
		// List of valid actions we can take
5070
		$valid_actions = array(
5071
			'/jetpack/v4/settings',
5072
		);
5073
5074
		// Whitelist the action
5075
		if ( ! in_array( $action, $valid_actions ) ) {
5076
			return false;
5077
		}
5078
5079
		return true;
5080
	}
5081
5082
	/**
5083
	 * Checks to see if the URL is using SSL to connect with Jetpack
5084
	 *
5085
	 * @since 2.3.3
5086
	 * @return boolean
5087
	 */
5088
	public static function permit_ssl( $force_recheck = false ) {
5089
		// Do some fancy tests to see if ssl is being supported
5090
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5091
			$message = '';
5092
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5093
				$ssl = 0;
5094
			} else {
5095
				switch ( JETPACK_CLIENT__HTTPS ) {
5096
					case 'NEVER':
5097
						$ssl     = 0;
5098
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5099
						break;
5100
					case 'ALWAYS':
5101
					case 'AUTO':
5102
					default:
5103
						$ssl = 1;
5104
						break;
5105
				}
5106
5107
				// If it's not 'NEVER', test to see
5108
				if ( $ssl ) {
5109
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5110
						$ssl     = 0;
5111
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5112
					} else {
5113
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5114
						if ( is_wp_error( $response ) ) {
5115
							$ssl     = 0;
5116
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5117
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5118
							$ssl     = 0;
5119
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5120
						}
5121
					}
5122
				}
5123
			}
5124
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5125
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5126
		}
5127
5128
		return (bool) $ssl;
5129
	}
5130
5131
	/*
5132
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5133
	 */
5134
	public function alert_auto_ssl_fail() {
5135
		if ( ! current_user_can( 'manage_options' ) ) {
5136
			return;
5137
		}
5138
5139
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5140
		?>
5141
5142
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5143
			<div class="jp-banner__content">
5144
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5145
				<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>
5146
				<p>
5147
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5148
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5149
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5150
				</p>
5151
				<p>
5152
					<?php
5153
					printf(
5154
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5155
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5156
						esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' )
5157
					);
5158
					?>
5159
				</p>
5160
			</div>
5161
		</div>
5162
		<style>
5163
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5164
		</style>
5165
		<script type="text/javascript">
5166
			jQuery( document ).ready( function( $ ) {
5167
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5168
					var $this = $( this );
5169
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5170
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5171
					e.preventDefault();
5172
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5173
					$.post( ajaxurl, data )
5174
					  .done( function( response ) {
5175
						  if ( response.enabled ) {
5176
							  $( '#jetpack-ssl-warning' ).hide();
5177
						  } else {
5178
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5179
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5180
						  }
5181
					  }.bind( $this ) );
5182
				} );
5183
			} );
5184
		</script>
5185
5186
		<?php
5187
	}
5188
5189
	/**
5190
	 * Returns the Jetpack XML-RPC API
5191
	 *
5192
	 * @deprecated 8.0 Use Connection_Manager instead.
5193
	 * @return string
5194
	 */
5195
	public static function xmlrpc_api_url() {
5196
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5197
		return self::connection()->xmlrpc_api_url();
5198
	}
5199
5200
	/**
5201
	 * Returns the connection manager object.
5202
	 *
5203
	 * @return Automattic\Jetpack\Connection\Manager
5204
	 */
5205
	public static function connection() {
5206
		$jetpack = static::init();
5207
5208
		// If the connection manager hasn't been instantiated, do that now.
5209
		if ( ! $jetpack->connection_manager ) {
5210
			$jetpack->connection_manager = new Connection_Manager();
5211
		}
5212
5213
		return $jetpack->connection_manager;
5214
	}
5215
5216
	/**
5217
	 * Creates two secret tokens and the end of life timestamp for them.
5218
	 *
5219
	 * Note these tokens are unique per call, NOT static per site for connecting.
5220
	 *
5221
	 * @since 2.6
5222
	 * @param String  $action  The action name.
5223
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be false|integer?

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

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

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

Loading history...
5224
	 * @param Integer $exp     Expiration time in seconds.
5225
	 * @return array
5226
	 */
5227
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5228
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5229
	}
5230
5231
	public static function get_secrets( $action, $user_id ) {
5232
		$secrets = self::connection()->get_secrets( $action, $user_id );
5233
5234
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5235
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

Loading history...
5236
		}
5237
5238
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5239
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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

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

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

Loading history...
5240
		}
5241
5242
		return $secrets;
5243
	}
5244
5245
	/**
5246
	 * @deprecated 7.5 Use Connection_Manager instead.
5247
	 *
5248
	 * @param $action
5249
	 * @param $user_id
5250
	 */
5251
	public static function delete_secrets( $action, $user_id ) {
5252
		return self::connection()->delete_secrets( $action, $user_id );
5253
	}
5254
5255
	/**
5256
	 * Builds the timeout limit for queries talking with the wpcom servers.
5257
	 *
5258
	 * Based on local php max_execution_time in php.ini
5259
	 *
5260
	 * @since 2.6
5261
	 * @return int
5262
	 * @deprecated
5263
	 **/
5264
	public function get_remote_query_timeout_limit() {
5265
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5266
		return self::get_max_execution_time();
5267
	}
5268
5269
	/**
5270
	 * Builds the timeout limit for queries talking with the wpcom servers.
5271
	 *
5272
	 * Based on local php max_execution_time in php.ini
5273
	 *
5274
	 * @since 5.4
5275
	 * @return int
5276
	 **/
5277
	public static function get_max_execution_time() {
5278
		$timeout = (int) ini_get( 'max_execution_time' );
5279
5280
		// Ensure exec time set in php.ini
5281
		if ( ! $timeout ) {
5282
			$timeout = 30;
5283
		}
5284
		return $timeout;
5285
	}
5286
5287
	/**
5288
	 * Sets a minimum request timeout, and returns the current timeout
5289
	 *
5290
	 * @since 5.4
5291
	 **/
5292 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5293
		$timeout = self::get_max_execution_time();
5294
		if ( $timeout < $min_timeout ) {
5295
			$timeout = $min_timeout;
5296
			set_time_limit( $timeout );
5297
		}
5298
		return $timeout;
5299
	}
5300
5301
	/**
5302
	 * Takes the response from the Jetpack register new site endpoint and
5303
	 * verifies it worked properly.
5304
	 *
5305
	 * @since 2.6
5306
	 * @deprecated since 7.7.0
5307
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5308
	 **/
5309
	public function validate_remote_register_response() {
5310
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5311
	}
5312
5313
	/**
5314
	 * @return bool|WP_Error
5315
	 */
5316
	public static function register() {
5317
		$tracking = new Tracking();
5318
		$tracking->record_user_event( 'jpc_register_begin' );
5319
5320
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5321
5322
		$connection   = self::connection();
5323
		$registration = $connection->register();
5324
5325
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5326
5327
		if ( ! $registration || is_wp_error( $registration ) ) {
5328
			return $registration;
5329
		}
5330
5331
		return true;
5332
	}
5333
5334
	/**
5335
	 * Filters the registration request body to include tracking properties.
5336
	 *
5337
	 * @param Array $properties
5338
	 * @return Array amended properties.
5339
	 */
5340 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5341
		$tracking        = new Tracking();
5342
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5343
5344
		return array_merge(
5345
			$properties,
5346
			array(
5347
				'_ui' => $tracks_identity['_ui'],
5348
				'_ut' => $tracks_identity['_ut'],
5349
			)
5350
		);
5351
	}
5352
5353
	/**
5354
	 * Filters the token request body to include tracking properties.
5355
	 *
5356
	 * @param Array $properties
5357
	 * @return Array amended properties.
5358
	 */
5359 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5360
		$tracking        = new Tracking();
5361
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5362
5363
		return array_merge(
5364
			$properties,
5365
			array(
5366
				'_ui' => $tracks_identity['_ui'],
5367
				'_ut' => $tracks_identity['_ut'],
5368
			)
5369
		);
5370
	}
5371
5372
	/**
5373
	 * If the db version is showing something other that what we've got now, bump it to current.
5374
	 *
5375
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5376
	 */
5377
	public static function maybe_set_version_option() {
5378
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5379
		if ( JETPACK__VERSION != $version ) {
5380
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5381
5382
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5383
				/** This action is documented in class.jetpack.php */
5384
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5385
			}
5386
5387
			return true;
5388
		}
5389
		return false;
5390
	}
5391
5392
	/* Client Server API */
5393
5394
	/**
5395
	 * Loads the Jetpack XML-RPC client.
5396
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5397
	 *
5398
	 * @deprecated since 7.7.0
5399
	 */
5400
	public static function load_xml_rpc_client() {
5401
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5402
	}
5403
5404
	/**
5405
	 * Resets the saved authentication state in between testing requests.
5406
	 */
5407
	public function reset_saved_auth_state() {
5408
		$this->rest_authentication_status = null;
5409
5410
		if ( ! $this->connection_manager ) {
5411
			$this->connection_manager = new Connection_Manager();
5412
		}
5413
5414
		$this->connection_manager->reset_saved_auth_state();
5415
	}
5416
5417
	/**
5418
	 * Verifies the signature of the current request.
5419
	 *
5420
	 * @deprecated since 7.7.0
5421
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5422
	 *
5423
	 * @return false|array
5424
	 */
5425
	public function verify_xml_rpc_signature() {
5426
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5427
		return self::connection()->verify_xml_rpc_signature();
5428
	}
5429
5430
	/**
5431
	 * Verifies the signature of the current request.
5432
	 *
5433
	 * This function has side effects and should not be used. Instead,
5434
	 * use the memoized version `->verify_xml_rpc_signature()`.
5435
	 *
5436
	 * @deprecated since 7.7.0
5437
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5438
	 * @internal
5439
	 */
5440
	private function internal_verify_xml_rpc_signature() {
5441
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5442
	}
5443
5444
	/**
5445
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5446
	 *
5447
	 * @deprecated since 7.7.0
5448
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5449
	 *
5450
	 * @param \WP_User|mixed $user     User object if authenticated.
5451
	 * @param string         $username Username.
5452
	 * @param string         $password Password string.
5453
	 * @return \WP_User|mixed Authenticated user or error.
5454
	 */
5455 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5456
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5457
5458
		if ( ! $this->connection_manager ) {
5459
			$this->connection_manager = new Connection_Manager();
5460
		}
5461
5462
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5463
	}
5464
5465
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5466
	// Uses the existing XMLRPC request signing implementation.
5467
	function wp_rest_authenticate( $user ) {
5468
		if ( ! empty( $user ) ) {
5469
			// Another authentication method is in effect.
5470
			return $user;
5471
		}
5472
5473
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5474
			// Nothing to do for this authentication method.
5475
			return null;
5476
		}
5477
5478
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5479
			// Nothing to do for this authentication method.
5480
			return null;
5481
		}
5482
5483
		// Ensure that we always have the request body available.  At this
5484
		// point, the WP REST API code to determine the request body has not
5485
		// run yet.  That code may try to read from 'php://input' later, but
5486
		// this can only be done once per request in PHP versions prior to 5.6.
5487
		// So we will go ahead and perform this read now if needed, and save
5488
		// the request body where both the Jetpack signature verification code
5489
		// and the WP REST API code can see it.
5490
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5491
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5492
		}
5493
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5494
5495
		// Only support specific request parameters that have been tested and
5496
		// are known to work with signature verification.  A different method
5497
		// can be passed to the WP REST API via the '?_method=' parameter if
5498
		// needed.
5499
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5500
			$this->rest_authentication_status = new WP_Error(
5501
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5502
				__( 'This request method is not supported.', 'jetpack' ),
5503
				array( 'status' => 400 )
5504
			);
5505
			return null;
5506
		}
5507
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5508
			$this->rest_authentication_status = new WP_Error(
5509
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5510
				__( 'This request method does not support body parameters.', 'jetpack' ),
5511
				array( 'status' => 400 )
5512
			);
5513
			return null;
5514
		}
5515
5516
		if ( ! $this->connection_manager ) {
5517
			$this->connection_manager = new Connection_Manager();
5518
		}
5519
5520
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5521
5522
		if (
5523
			$verified &&
5524
			isset( $verified['type'] ) &&
5525
			'user' === $verified['type'] &&
5526
			! empty( $verified['user_id'] )
5527
		) {
5528
			// Authentication successful.
5529
			$this->rest_authentication_status = true;
5530
			return $verified['user_id'];
5531
		}
5532
5533
		// Something else went wrong.  Probably a signature error.
5534
		$this->rest_authentication_status = new WP_Error(
5535
			'rest_invalid_signature',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5536
			__( 'The request is not signed correctly.', 'jetpack' ),
5537
			array( 'status' => 400 )
5538
		);
5539
		return null;
5540
	}
5541
5542
	/**
5543
	 * Report authentication status to the WP REST API.
5544
	 *
5545
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5546
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5547
	 */
5548
	public function wp_rest_authentication_errors( $value ) {
5549
		if ( $value !== null ) {
5550
			return $value;
5551
		}
5552
		return $this->rest_authentication_status;
5553
	}
5554
5555
	/**
5556
	 * Add our nonce to this request.
5557
	 *
5558
	 * @deprecated since 7.7.0
5559
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5560
	 *
5561
	 * @param int    $timestamp Timestamp of the request.
5562
	 * @param string $nonce     Nonce string.
5563
	 */
5564 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5565
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5566
5567
		if ( ! $this->connection_manager ) {
5568
			$this->connection_manager = new Connection_Manager();
5569
		}
5570
5571
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5572
	}
5573
5574
	/**
5575
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5576
	 * Capture it here so we can verify the signature later.
5577
	 *
5578
	 * @deprecated since 7.7.0
5579
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5580
	 *
5581
	 * @param array $methods XMLRPC methods.
5582
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5583
	 */
5584 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5585
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5586
5587
		if ( ! $this->connection_manager ) {
5588
			$this->connection_manager = new Connection_Manager();
5589
		}
5590
5591
		return $this->connection_manager->xmlrpc_methods( $methods );
5592
	}
5593
5594
	/**
5595
	 * Register additional public XMLRPC methods.
5596
	 *
5597
	 * @deprecated since 7.7.0
5598
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5599
	 *
5600
	 * @param array $methods Public XMLRPC methods.
5601
	 * @return array Public XMLRPC methods, with the getOptions one.
5602
	 */
5603 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5604
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5605
5606
		if ( ! $this->connection_manager ) {
5607
			$this->connection_manager = new Connection_Manager();
5608
		}
5609
5610
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5611
	}
5612
5613
	/**
5614
	 * Handles a getOptions XMLRPC method call.
5615
	 *
5616
	 * @deprecated since 7.7.0
5617
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5618
	 *
5619
	 * @param array $args method call arguments.
5620
	 * @return array an amended XMLRPC server options array.
5621
	 */
5622 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5623
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5624
5625
		if ( ! $this->connection_manager ) {
5626
			$this->connection_manager = new Connection_Manager();
5627
		}
5628
5629
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

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

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

Loading history...
5630
	}
5631
5632
	/**
5633
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5634
	 *
5635
	 * @deprecated since 7.7.0
5636
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5637
	 *
5638
	 * @param array $options Standard Core options.
5639
	 * @return array Amended options.
5640
	 */
5641 View Code Duplication
	public function xmlrpc_options( $options ) {
5642
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5643
5644
		if ( ! $this->connection_manager ) {
5645
			$this->connection_manager = new Connection_Manager();
5646
		}
5647
5648
		return $this->connection_manager->xmlrpc_options( $options );
5649
	}
5650
5651
	/**
5652
	 * Cleans nonces that were saved when calling ::add_nonce.
5653
	 *
5654
	 * @deprecated since 7.7.0
5655
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5656
	 *
5657
	 * @param bool $all whether to clean even non-expired nonces.
5658
	 */
5659
	public static function clean_nonces( $all = false ) {
5660
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5661
		return self::connection()->clean_nonces( $all );
5662
	}
5663
5664
	/**
5665
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5666
	 * SET: state( $key, $value );
5667
	 * GET: $value = state( $key );
5668
	 *
5669
	 * @param string $key
0 ignored issues
show
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5671
	 * @param bool   $restate private
5672
	 */
5673
	public static function state( $key = null, $value = null, $restate = false ) {
5674
		static $state = array();
5675
		static $path, $domain;
5676
		if ( ! isset( $path ) ) {
5677
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5678
			$admin_url = self::admin_url();
5679
			$bits      = wp_parse_url( $admin_url );
5680
5681
			if ( is_array( $bits ) ) {
5682
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5683
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5684
			} else {
5685
				$path = $domain = null;
5686
			}
5687
		}
5688
5689
		// Extract state from cookies and delete cookies
5690
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5691
			$yum = $_COOKIE['jetpackState'];
5692
			unset( $_COOKIE['jetpackState'] );
5693
			foreach ( $yum as $k => $v ) {
5694
				if ( strlen( $v ) ) {
5695
					$state[ $k ] = $v;
5696
				}
5697
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5698
			}
5699
		}
5700
5701
		if ( $restate ) {
5702
			foreach ( $state as $k => $v ) {
5703
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5704
			}
5705
			return;
5706
		}
5707
5708
		// Get a state variable
5709
		if ( isset( $key ) && ! isset( $value ) ) {
5710
			if ( array_key_exists( $key, $state ) ) {
5711
				return $state[ $key ];
5712
			}
5713
			return null;
5714
		}
5715
5716
		// Set a state variable
5717
		if ( isset( $key ) && isset( $value ) ) {
5718
			if ( is_array( $value ) && isset( $value[0] ) ) {
5719
				$value = $value[0];
5720
			}
5721
			$state[ $key ] = $value;
5722
			if ( ! headers_sent() ) {
5723
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5724
			}
5725
		}
5726
	}
5727
5728
	public static function restate() {
5729
		self::state( null, null, true );
5730
	}
5731
5732
	public static function check_privacy( $file ) {
5733
		static $is_site_publicly_accessible = null;
5734
5735
		if ( is_null( $is_site_publicly_accessible ) ) {
5736
			$is_site_publicly_accessible = false;
5737
5738
			$rpc = new Jetpack_IXR_Client();
5739
5740
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5741
			if ( $success ) {
5742
				$response = $rpc->getResponse();
5743
				if ( $response ) {
5744
					$is_site_publicly_accessible = true;
5745
				}
5746
			}
5747
5748
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5749
		}
5750
5751
		if ( $is_site_publicly_accessible ) {
5752
			return;
5753
		}
5754
5755
		$module_slug = self::get_module_slug( $file );
5756
5757
		$privacy_checks = self::state( 'privacy_checks' );
5758
		if ( ! $privacy_checks ) {
5759
			$privacy_checks = $module_slug;
5760
		} else {
5761
			$privacy_checks .= ",$module_slug";
5762
		}
5763
5764
		self::state( 'privacy_checks', $privacy_checks );
5765
	}
5766
5767
	/**
5768
	 * Helper method for multicall XMLRPC.
5769
	 *
5770
	 * @param ...$args Args for the async_call.
5771
	 */
5772
	public static function xmlrpc_async_call( ...$args ) {
5773
		global $blog_id;
5774
		static $clients = array();
5775
5776
		$client_blog_id = is_multisite() ? $blog_id : 0;
5777
5778
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5779
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5780
			if ( function_exists( 'ignore_user_abort' ) ) {
5781
				ignore_user_abort( true );
5782
			}
5783
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5784
		}
5785
5786
		if ( ! empty( $args[0] ) ) {
5787
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5788
		} elseif ( is_multisite() ) {
5789
			foreach ( $clients as $client_blog_id => $client ) {
5790
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5791
					continue;
5792
				}
5793
5794
				$switch_success = switch_to_blog( $client_blog_id, true );
5795
				if ( ! $switch_success ) {
5796
					continue;
5797
				}
5798
5799
				flush();
5800
				$client->query();
5801
5802
				restore_current_blog();
5803
			}
5804
		} else {
5805
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5806
				flush();
5807
				$clients[0]->query();
5808
			}
5809
		}
5810
	}
5811
5812
	public static function staticize_subdomain( $url ) {
5813
5814
		// Extract hostname from URL
5815
		$host = wp_parse_url( $url, PHP_URL_HOST );
5816
5817
		// Explode hostname on '.'
5818
		$exploded_host = explode( '.', $host );
5819
5820
		// Retrieve the name and TLD
5821
		if ( count( $exploded_host ) > 1 ) {
5822
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5823
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5824
			// Rebuild domain excluding subdomains
5825
			$domain = $name . '.' . $tld;
5826
		} else {
5827
			$domain = $host;
5828
		}
5829
		// Array of Automattic domains
5830
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5831
5832
		// Return $url if not an Automattic domain
5833
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5834
			return $url;
5835
		}
5836
5837
		if ( is_ssl() ) {
5838
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5839
		}
5840
5841
		srand( crc32( basename( $url ) ) );
5842
		$static_counter = rand( 0, 2 );
5843
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5844
5845
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5846
	}
5847
5848
	/* JSON API Authorization */
5849
5850
	/**
5851
	 * Handles the login action for Authorizing the JSON API
5852
	 */
5853
	function login_form_json_api_authorization() {
5854
		$this->verify_json_api_authorization_request();
5855
5856
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5857
5858
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5859
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5860
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5861
	}
5862
5863
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5864
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5865
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5866
			return $url;
5867
		}
5868
5869
		$parsed_url = wp_parse_url( $url );
5870
		$url        = strtok( $url, '?' );
5871
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5872
		if ( ! empty( $parsed_url['query'] ) ) {
5873
			$url .= "&{$parsed_url['query']}";
5874
		}
5875
5876
		return $url;
5877
	}
5878
5879
	// Make sure the POSTed request is handled by the same action
5880
	function preserve_action_in_login_form_for_json_api_authorization() {
5881
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5882
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5883
	}
5884
5885
	// If someone logs in to approve API access, store the Access Code in usermeta
5886
	function store_json_api_authorization_token( $user_login, $user ) {
5887
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5888
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5889
		$token = wp_generate_password( 32, false );
5890
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5891
	}
5892
5893
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5894
	function allow_wpcom_public_api_domain( $domains ) {
5895
		$domains[] = 'public-api.wordpress.com';
5896
		return $domains;
5897
	}
5898
5899
	static function is_redirect_encoded( $redirect_url ) {
5900
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5901
	}
5902
5903
	// Add all wordpress.com environments to the safe redirect whitelist
5904
	function allow_wpcom_environments( $domains ) {
5905
		$domains[] = 'wordpress.com';
5906
		$domains[] = 'wpcalypso.wordpress.com';
5907
		$domains[] = 'horizon.wordpress.com';
5908
		$domains[] = 'calypso.localhost';
5909
		return $domains;
5910
	}
5911
5912
	// Add the Access Code details to the public-api.wordpress.com redirect
5913
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5914
		return add_query_arg(
5915
			urlencode_deep(
5916
				array(
5917
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5918
					'jetpack-user-id' => (int) $user->ID,
5919
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5920
				)
5921
			),
5922
			$redirect_to
5923
		);
5924
	}
5925
5926
5927
	/**
5928
	 * Verifies the request by checking the signature
5929
	 *
5930
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5931
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5932
	 *
5933
	 * @param null|array $environment
5934
	 */
5935
	function verify_json_api_authorization_request( $environment = null ) {
5936
		$environment = is_null( $environment )
5937
			? $_REQUEST
5938
			: $environment;
5939
5940
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5941
		$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...
5942
		if ( ! $token || empty( $token->secret ) ) {
5943
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5944
		}
5945
5946
		$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' );
5947
5948
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5949
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5950
			/**
5951
			 * Jetpack authorisation request Error.
5952
			 *
5953
			 * @since 7.5.0
5954
			 */
5955
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5956
			$die_error = sprintf(
5957
				/* translators: %s is a URL */
5958
				__( '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' ),
5959
				'https://jetpack.com/support/double-encoding/'
5960
			);
5961
		}
5962
5963
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5964
5965
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5966
			$signature = $jetpack_signature->sign_request(
5967
				$environment['token'],
5968
				$environment['timestamp'],
5969
				$environment['nonce'],
5970
				'',
5971
				'GET',
5972
				$environment['jetpack_json_api_original_query'],
5973
				null,
5974
				true
5975
			);
5976
		} else {
5977
			$signature = $jetpack_signature->sign_current_request(
5978
				array(
5979
					'body'   => null,
5980
					'method' => 'GET',
5981
				)
5982
			);
5983
		}
5984
5985
		if ( ! $signature ) {
5986
			wp_die( $die_error );
5987
		} elseif ( is_wp_error( $signature ) ) {
5988
			wp_die( $die_error );
5989
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5990
			if ( is_ssl() ) {
5991
				// 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
5992
				$signature = $jetpack_signature->sign_current_request(
5993
					array(
5994
						'scheme' => 'http',
5995
						'body'   => null,
5996
						'method' => 'GET',
5997
					)
5998
				);
5999
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6000
					wp_die( $die_error );
6001
				}
6002
			} else {
6003
				wp_die( $die_error );
6004
			}
6005
		}
6006
6007
		$timestamp = (int) $environment['timestamp'];
6008
		$nonce     = stripslashes( (string) $environment['nonce'] );
6009
6010
		if ( ! $this->connection_manager ) {
6011
			$this->connection_manager = new Connection_Manager();
6012
		}
6013
6014
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6015
			// De-nonce the nonce, at least for 5 minutes.
6016
			// 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)
6017
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6018
			if ( $old_nonce_time < time() - 300 ) {
6019
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6020
			}
6021
		}
6022
6023
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6024
		$data_filters = array(
6025
			'state'        => 'opaque',
6026
			'client_id'    => 'int',
6027
			'client_title' => 'string',
6028
			'client_image' => 'url',
6029
		);
6030
6031
		foreach ( $data_filters as $key => $sanitation ) {
6032
			if ( ! isset( $data->$key ) ) {
6033
				wp_die( $die_error );
6034
			}
6035
6036
			switch ( $sanitation ) {
6037
				case 'int':
6038
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6039
					break;
6040
				case 'opaque':
6041
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6042
					break;
6043
				case 'string':
6044
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6045
					break;
6046
				case 'url':
6047
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6048
					break;
6049
			}
6050
		}
6051
6052
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6053
			wp_die( $die_error );
6054
		}
6055
	}
6056
6057
	function login_message_json_api_authorization( $message ) {
6058
		return '<p class="message">' . sprintf(
6059
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6060
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6061
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6062
	}
6063
6064
	/**
6065
	 * Get $content_width, but with a <s>twist</s> filter.
6066
	 */
6067
	public static function get_content_width() {
6068
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6069
			? $GLOBALS['content_width']
6070
			: false;
6071
		/**
6072
		 * Filter the Content Width value.
6073
		 *
6074
		 * @since 2.2.3
6075
		 *
6076
		 * @param string $content_width Content Width value.
6077
		 */
6078
		return apply_filters( 'jetpack_content_width', $content_width );
6079
	}
6080
6081
	/**
6082
	 * Pings the WordPress.com Mirror Site for the specified options.
6083
	 *
6084
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6085
	 *
6086
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6087
	 */
6088
	public function get_cloud_site_options( $option_names ) {
6089
		$option_names = array_filter( (array) $option_names, 'is_string' );
6090
6091
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6092
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6093
		if ( $xml->isError() ) {
6094
			return array(
6095
				'error_code' => $xml->getErrorCode(),
6096
				'error_msg'  => $xml->getErrorMessage(),
6097
			);
6098
		}
6099
		$cloud_site_options = $xml->getResponse();
6100
6101
		return $cloud_site_options;
6102
	}
6103
6104
	/**
6105
	 * Checks if the site is currently in an identity crisis.
6106
	 *
6107
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6108
	 */
6109
	public static function check_identity_crisis() {
6110
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6111
			return false;
6112
		}
6113
6114
		return Jetpack_Options::get_option( 'sync_error_idc' );
6115
	}
6116
6117
	/**
6118
	 * Checks whether the home and siteurl specifically are whitelisted
6119
	 * Written so that we don't have re-check $key and $value params every time
6120
	 * we want to check if this site is whitelisted, for example in footer.php
6121
	 *
6122
	 * @since  3.8.0
6123
	 * @return bool True = already whitelisted False = not whitelisted
6124
	 */
6125
	public static function is_staging_site() {
6126
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6127
		return ( new Status() )->is_staging_site();
6128
	}
6129
6130
	/**
6131
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6132
	 *
6133
	 * @since 4.4.0
6134
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6135
	 *
6136
	 * @return bool
6137
	 */
6138
	public static function validate_sync_error_idc_option() {
6139
		$is_valid = false;
6140
6141
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6142
		if ( false === $idc_allowed ) {
6143
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6144
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6145
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6146
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6147
				$transient_duration = HOUR_IN_SECONDS;
6148
			} else {
6149
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6150
				$idc_allowed        = '1';
6151
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6152
			}
6153
6154
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6155
		}
6156
6157
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6158
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6159
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6160
			$local_options = self::get_sync_error_idc_option();
6161
			// Ensure all values are set.
6162
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6163
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6164
					$is_valid = true;
6165
				}
6166
			}
6167
6168
		}
6169
6170
		/**
6171
		 * Filters whether the sync_error_idc option is valid.
6172
		 *
6173
		 * @since 4.4.0
6174
		 *
6175
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6176
		 */
6177
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6178
6179
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6180
			// Since the option exists, and did not validate, delete it
6181
			Jetpack_Options::delete_option( 'sync_error_idc' );
6182
		}
6183
6184
		return $is_valid;
6185
	}
6186
6187
	/**
6188
	 * Normalizes a url by doing three things:
6189
	 *  - Strips protocol
6190
	 *  - Strips www
6191
	 *  - Adds a trailing slash
6192
	 *
6193
	 * @since 4.4.0
6194
	 * @param string $url
6195
	 * @return WP_Error|string
6196
	 */
6197
	public static function normalize_url_protocol_agnostic( $url ) {
6198
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6199
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6200
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
6201
		}
6202
6203
		// Strip www and protocols
6204
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6205
		return $url;
6206
	}
6207
6208
	/**
6209
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6210
	 *
6211
	 * @since 4.4.0
6212
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6213
	 *
6214
	 * @param array $response
6215
	 * @return array Array of the local urls, wpcom urls, and error code
6216
	 */
6217
	public static function get_sync_error_idc_option( $response = array() ) {
6218
		// Since the local options will hit the database directly, store the values
6219
		// in a transient to allow for autoloading and caching on subsequent views.
6220
		$local_options = get_transient( 'jetpack_idc_local' );
6221
		if ( false === $local_options ) {
6222
			$local_options = array(
6223
				'home'    => Functions::home_url(),
6224
				'siteurl' => Functions::site_url(),
6225
			);
6226
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6227
		}
6228
6229
		$options = array_merge( $local_options, $response );
6230
6231
		$returned_values = array();
6232
		foreach ( $options as $key => $option ) {
6233
			if ( 'error_code' === $key ) {
6234
				$returned_values[ $key ] = $option;
6235
				continue;
6236
			}
6237
6238
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6239
				continue;
6240
			}
6241
6242
			$returned_values[ $key ] = $normalized_url;
6243
		}
6244
6245
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6246
6247
		return $returned_values;
6248
	}
6249
6250
	/**
6251
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6252
	 * If set to true, the site will be put into staging mode.
6253
	 *
6254
	 * @since 4.3.2
6255
	 * @return bool
6256
	 */
6257
	public static function sync_idc_optin() {
6258
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6259
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6260
		} else {
6261
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6262
		}
6263
6264
		/**
6265
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6266
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6267
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6268
		 *
6269
		 * @since 4.3.2
6270
		 *
6271
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6272
		 */
6273
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6274
	}
6275
6276
	/**
6277
	 * Maybe Use a .min.css stylesheet, maybe not.
6278
	 *
6279
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6280
	 */
6281
	public static function maybe_min_asset( $url, $path, $plugin ) {
6282
		// Short out on things trying to find actual paths.
6283
		if ( ! $path || empty( $plugin ) ) {
6284
			return $url;
6285
		}
6286
6287
		$path = ltrim( $path, '/' );
6288
6289
		// Strip out the abspath.
6290
		$base = dirname( plugin_basename( $plugin ) );
6291
6292
		// Short out on non-Jetpack assets.
6293
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6294
			return $url;
6295
		}
6296
6297
		// File name parsing.
6298
		$file              = "{$base}/{$path}";
6299
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6300
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6301
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6302
		$extension         = array_shift( $file_name_parts_r );
6303
6304
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6305
			// Already pointing at the minified version.
6306
			if ( 'min' === $file_name_parts_r[0] ) {
6307
				return $url;
6308
			}
6309
6310
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6311
			if ( file_exists( $min_full_path ) ) {
6312
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6313
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6314
				if ( 'css' === $extension ) {
6315
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6316
					self::$min_assets[ $key ] = $path;
6317
				}
6318
			}
6319
		}
6320
6321
		return $url;
6322
	}
6323
6324
	/**
6325
	 * If the asset is minified, let's flag .min as the suffix.
6326
	 *
6327
	 * Attached to `style_loader_src` filter.
6328
	 *
6329
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

Loading history...
6332
	 */
6333
	public static function set_suffix_on_min( $src, $handle ) {
6334
		if ( false === strpos( $src, '.min.css' ) ) {
6335
			return $src;
6336
		}
6337
6338
		if ( ! empty( self::$min_assets ) ) {
6339
			foreach ( self::$min_assets as $file => $path ) {
6340
				if ( false !== strpos( $src, $file ) ) {
6341
					wp_style_add_data( $handle, 'suffix', '.min' );
6342
					return $src;
6343
				}
6344
			}
6345
		}
6346
6347
		return $src;
6348
	}
6349
6350
	/**
6351
	 * Maybe inlines a stylesheet.
6352
	 *
6353
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6354
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6355
	 *
6356
	 * Attached to `style_loader_tag` filter.
6357
	 *
6358
	 * @param string $tag The tag that would link to the external asset.
6359
	 * @param string $handle The registered handle of the script in question.
6360
	 *
6361
	 * @return string
6362
	 */
6363
	public static function maybe_inline_style( $tag, $handle ) {
6364
		global $wp_styles;
6365
		$item = $wp_styles->registered[ $handle ];
6366
6367
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6368
			return $tag;
6369
		}
6370
6371
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6372
			$href = $matches[1];
6373
			// Strip off query string
6374
			if ( $pos = strpos( $href, '?' ) ) {
6375
				$href = substr( $href, 0, $pos );
6376
			}
6377
			// Strip off fragment
6378
			if ( $pos = strpos( $href, '#' ) ) {
6379
				$href = substr( $href, 0, $pos );
6380
			}
6381
		} else {
6382
			return $tag;
6383
		}
6384
6385
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6386
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6387
			return $tag;
6388
		}
6389
6390
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6391
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6392
			// And this isn't the pass that actually deals with the RTL version...
6393
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6394
				// Short out, as the RTL version will deal with it in a moment.
6395
				return $tag;
6396
			}
6397
		}
6398
6399
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6400
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6401
		if ( $css ) {
6402
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6403
			if ( empty( $item->extra['after'] ) ) {
6404
				wp_add_inline_style( $handle, $css );
6405
			} else {
6406
				array_unshift( $item->extra['after'], $css );
6407
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6408
			}
6409
		}
6410
6411
		return $tag;
6412
	}
6413
6414
	/**
6415
	 * Loads a view file from the views
6416
	 *
6417
	 * Data passed in with the $data parameter will be available in the
6418
	 * template file as $data['value']
6419
	 *
6420
	 * @param string $template - Template file to load
6421
	 * @param array  $data - Any data to pass along to the template
6422
	 * @return boolean - If template file was found
6423
	 **/
6424
	public function load_view( $template, $data = array() ) {
6425
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6426
6427
		if ( file_exists( $views_dir . $template ) ) {
6428
			require_once $views_dir . $template;
6429
			return true;
6430
		}
6431
6432
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6433
		return false;
6434
	}
6435
6436
	/**
6437
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6438
	 */
6439
	public function deprecated_hooks() {
6440
		global $wp_filter;
6441
6442
		/*
6443
		 * Format:
6444
		 * deprecated_filter_name => replacement_name
6445
		 *
6446
		 * If there is no replacement, use null for replacement_name
6447
		 */
6448
		$deprecated_list = array(
6449
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6450
			'wpl_sharing_2014_1'                           => null,
6451
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6452
			'jetpack_identity_crisis_options_to_check'     => null,
6453
			'update_option_jetpack_single_user_site'       => null,
6454
			'audio_player_default_colors'                  => null,
6455
			'add_option_jetpack_featured_images_enabled'   => null,
6456
			'add_option_jetpack_update_details'            => null,
6457
			'add_option_jetpack_updates'                   => null,
6458
			'add_option_jetpack_network_name'              => null,
6459
			'add_option_jetpack_network_allow_new_registrations' => null,
6460
			'add_option_jetpack_network_add_new_users'     => null,
6461
			'add_option_jetpack_network_site_upload_space' => null,
6462
			'add_option_jetpack_network_upload_file_types' => null,
6463
			'add_option_jetpack_network_enable_administration_menus' => null,
6464
			'add_option_jetpack_is_multi_site'             => null,
6465
			'add_option_jetpack_is_main_network'           => null,
6466
			'add_option_jetpack_main_network_site'         => null,
6467
			'jetpack_sync_all_registered_options'          => null,
6468
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6469
			'jetpack_is_post_mailable'                     => null,
6470
			'jetpack_seo_site_host'                        => null,
6471
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6472
			'jetpack_holiday_snow_option_name'             => null,
6473
			'jetpack_holiday_chance_of_snow'               => null,
6474
			'jetpack_holiday_snow_js_url'                  => null,
6475
			'jetpack_is_holiday_snow_season'               => null,
6476
			'jetpack_holiday_snow_option_updated'          => null,
6477
			'jetpack_holiday_snowing'                      => null,
6478
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6479
			'jetpack_cache_plans'                          => null,
6480
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6481
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6482
			'jetpack_enable_site_verification'             => null,
6483
			'can_display_jetpack_manage_notice'            => null,
6484
			// Removed in Jetpack 7.3.0
6485
			'atd_load_scripts'                             => null,
6486
			'atd_http_post_timeout'                        => null,
6487
			'atd_http_post_error'                          => null,
6488
			'atd_service_domain'                           => null,
6489
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6490
			// Removed in Jetpack 7.9.0
6491
			'jetpack_pwa_manifest'                         => null,
6492
			'jetpack_pwa_background_color'                 => null,
6493
			// Removed in Jetpack 8.3.0.
6494
			'jetpack_check_mobile'                         => null,
6495
			'jetpack_mobile_stylesheet'                    => null,
6496
			'jetpack_mobile_template'                      => null,
6497
			'mobile_reject_mobile'                         => null,
6498
			'mobile_force_mobile'                          => null,
6499
			'mobile_app_promo_download'                    => null,
6500
			'mobile_setup'                                 => null,
6501
			'jetpack_mobile_footer_before'                 => null,
6502
			'wp_mobile_theme_footer'                       => null,
6503
			'minileven_credits'                            => null,
6504
			'jetpack_mobile_header_before'                 => null,
6505
			'jetpack_mobile_header_after'                  => null,
6506
			'jetpack_mobile_theme_menu'                    => null,
6507
			'minileven_show_featured_images'               => null,
6508
			'minileven_attachment_size'                    => null,
6509
		);
6510
6511
		// This is a silly loop depth. Better way?
6512
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6513
			if ( has_action( $hook ) ) {
6514
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6515
					foreach ( $values as $hooked ) {
6516
						if ( is_callable( $hooked['function'] ) ) {
6517
							$function_name = 'an anonymous function';
6518
						} else {
6519
							$function_name = $hooked['function'];
6520
						}
6521
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6522
					}
6523
				}
6524
			}
6525
		}
6526
	}
6527
6528
	/**
6529
	 * Converts any url in a stylesheet, to the correct absolute url.
6530
	 *
6531
	 * Considerations:
6532
	 *  - Normal, relative URLs     `feh.png`
6533
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6534
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6535
	 *  - Absolute URLs             `http://domain.com/feh.png`
6536
	 *  - Domain root relative URLs `/feh.png`
6537
	 *
6538
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6539
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6540
	 *
6541
	 * @return mixed|string
6542
	 */
6543
	public static function absolutize_css_urls( $css, $css_file_url ) {
6544
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6545
		$css_dir = dirname( $css_file_url );
6546
		$p       = wp_parse_url( $css_dir );
6547
		$domain  = sprintf(
6548
			'%1$s//%2$s%3$s%4$s',
6549
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6550
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6551
			$p['host'],
6552
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6553
		);
6554
6555
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6556
			$find = $replace = array();
6557
			foreach ( $matches as $match ) {
6558
				$url = trim( $match['path'], "'\" \t" );
6559
6560
				// If this is a data url, we don't want to mess with it.
6561
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6562
					continue;
6563
				}
6564
6565
				// If this is an absolute or protocol-agnostic url,
6566
				// we don't want to mess with it.
6567
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6568
					continue;
6569
				}
6570
6571
				switch ( substr( $url, 0, 1 ) ) {
6572
					case '/':
6573
						$absolute = $domain . $url;
6574
						break;
6575
					default:
6576
						$absolute = $css_dir . '/' . $url;
6577
				}
6578
6579
				$find[]    = $match[0];
6580
				$replace[] = sprintf( 'url("%s")', $absolute );
6581
			}
6582
			$css = str_replace( $find, $replace, $css );
6583
		}
6584
6585
		return $css;
6586
	}
6587
6588
	/**
6589
	 * This methods removes all of the registered css files on the front end
6590
	 * from Jetpack in favor of using a single file. In effect "imploding"
6591
	 * all the files into one file.
6592
	 *
6593
	 * Pros:
6594
	 * - Uses only ONE css asset connection instead of 15
6595
	 * - Saves a minimum of 56k
6596
	 * - Reduces server load
6597
	 * - Reduces time to first painted byte
6598
	 *
6599
	 * Cons:
6600
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6601
	 *      should not cause any issues with themes.
6602
	 * - Plugins/themes dequeuing styles no longer do anything. See
6603
	 *      jetpack_implode_frontend_css filter for a workaround
6604
	 *
6605
	 * For some situations developers may wish to disable css imploding and
6606
	 * instead operate in legacy mode where each file loads seperately and
6607
	 * can be edited individually or dequeued. This can be accomplished with
6608
	 * the following line:
6609
	 *
6610
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6611
	 *
6612
	 * @since 3.2
6613
	 **/
6614
	public function implode_frontend_css( $travis_test = false ) {
6615
		$do_implode = true;
6616
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6617
			$do_implode = false;
6618
		}
6619
6620
		// Do not implode CSS when the page loads via the AMP plugin.
6621
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6622
			$do_implode = false;
6623
		}
6624
6625
		/**
6626
		 * Allow CSS to be concatenated into a single jetpack.css file.
6627
		 *
6628
		 * @since 3.2.0
6629
		 *
6630
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6631
		 */
6632
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6633
6634
		// Do not use the imploded file when default behavior was altered through the filter
6635
		if ( ! $do_implode ) {
6636
			return;
6637
		}
6638
6639
		// We do not want to use the imploded file in dev mode, or if not connected
6640
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6641
			if ( ! $travis_test ) {
6642
				return;
6643
			}
6644
		}
6645
6646
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6647
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6648
			return;
6649
		}
6650
6651
		/*
6652
		 * Now we assume Jetpack is connected and able to serve the single
6653
		 * file.
6654
		 *
6655
		 * In the future there will be a check here to serve the file locally
6656
		 * or potentially from the Jetpack CDN
6657
		 *
6658
		 * For now:
6659
		 * - Enqueue a single imploded css file
6660
		 * - Zero out the style_loader_tag for the bundled ones
6661
		 * - Be happy, drink scotch
6662
		 */
6663
6664
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6665
6666
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6667
6668
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6669
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6670
	}
6671
6672
	function concat_remove_style_loader_tag( $tag, $handle ) {
6673
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6674
			$tag = '';
6675
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6676
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6677
			}
6678
		}
6679
6680
		return $tag;
6681
	}
6682
6683
	/**
6684
	 * Add an async attribute to scripts that can be loaded asynchronously.
6685
	 * https://www.w3schools.com/tags/att_script_async.asp
6686
	 *
6687
	 * @since 7.7.0
6688
	 *
6689
	 * @param string $tag    The <script> tag for the enqueued script.
6690
	 * @param string $handle The script's registered handle.
6691
	 * @param string $src    The script's source URL.
6692
	 */
6693
	public function script_add_async( $tag, $handle, $src ) {
6694
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6695
			return preg_replace( '/^<script /i', '<script async ', $tag );
6696
		}
6697
6698
		return $tag;
6699
	}
6700
6701
	/*
6702
	 * Check the heartbeat data
6703
	 *
6704
	 * Organizes the heartbeat data by severity.  For example, if the site
6705
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6706
	 *
6707
	 * Data will be added to "caution" array, if it either:
6708
	 *  - Out of date Jetpack version
6709
	 *  - Out of date WP version
6710
	 *  - Out of date PHP version
6711
	 *
6712
	 * $return array $filtered_data
6713
	 */
6714
	public static function jetpack_check_heartbeat_data() {
6715
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6716
6717
		$good    = array();
6718
		$caution = array();
6719
		$bad     = array();
6720
6721
		foreach ( $raw_data as $stat => $value ) {
6722
6723
			// Check jetpack version
6724
			if ( 'version' == $stat ) {
6725
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6726
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6727
					continue;
6728
				}
6729
			}
6730
6731
			// Check WP version
6732
			if ( 'wp-version' == $stat ) {
6733
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6734
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6735
					continue;
6736
				}
6737
			}
6738
6739
			// Check PHP version
6740
			if ( 'php-version' == $stat ) {
6741
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6742
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6743
					continue;
6744
				}
6745
			}
6746
6747
			// Check ID crisis
6748
			if ( 'identitycrisis' == $stat ) {
6749
				if ( 'yes' == $value ) {
6750
					$bad[ $stat ] = $value;
6751
					continue;
6752
				}
6753
			}
6754
6755
			// The rest are good :)
6756
			$good[ $stat ] = $value;
6757
		}
6758
6759
		$filtered_data = array(
6760
			'good'    => $good,
6761
			'caution' => $caution,
6762
			'bad'     => $bad,
6763
		);
6764
6765
		return $filtered_data;
6766
	}
6767
6768
6769
	/*
6770
	 * This method is used to organize all options that can be reset
6771
	 * without disconnecting Jetpack.
6772
	 *
6773
	 * It is used in class.jetpack-cli.php to reset options
6774
	 *
6775
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6776
	 *
6777
	 * @return array of options to delete.
6778
	 */
6779
	public static function get_jetpack_options_for_reset() {
6780
		return Jetpack_Options::get_options_for_reset();
6781
	}
6782
6783
	/*
6784
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6785
	 * so we can bring them directly to their site in calypso.
6786
	 *
6787
	 * @param string | url
6788
	 * @return string | url without the guff
6789
	 */
6790
	public static function build_raw_urls( $url ) {
6791
		$strip_http = '/.*?:\/\//i';
6792
		$url        = preg_replace( $strip_http, '', $url );
6793
		$url        = str_replace( '/', '::', $url );
6794
		return $url;
6795
	}
6796
6797
	/**
6798
	 * Builds an URL using the jetpack.com/redirect service
6799
	 *
6800
	 * Note to WP.com: Changes to this method must be synced to wpcom
6801
	 *
6802
	 * @since 8.4.0
6803
	 *
6804
	 * @param string        $source The URL handler registered in the server
6805
	 * @param array|string  $args {
6806
	 *
6807
	 * 		Additional arguments to build the url
6808
	 *
6809
	 * 		@param string $site URL of the current site
0 ignored issues
show
There is no parameter named $site. 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...
6810
	 * 		@param string $path Additional path to be appended to the URL
0 ignored issues
show
There is no parameter named $path. 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...
6811
	 * 		@param string $query Query parameters to be added to the URL
0 ignored issues
show
There is no parameter named $query. 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...
6812
	 * 		@param string $anchor Anchor to be added to the URL
0 ignored issues
show
There is no parameter named $anchor. 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...
6813
6814
	 * }
6815
	 *
6816
	 *
6817
	 * @return string The built URL
6818
	 */
6819
	public static function build_redirect_url( $source, $args = array() ) {
6820
6821
		$url           = 'https://jetpack.com/redirect';
6822
		$args          = wp_parse_args( $args );
6823
		$accepted_args = array( 'site', 'path', 'query', 'anchor' );
6824
6825
		$to_be_added = array(
6826
			'source' => rawurlencode( $source ),
6827
		);
6828
6829
		foreach ( $args as $arg_name => $arg_value ) {
6830
6831
			if ( ! in_array( $arg_name, $accepted_args, true ) || empty( $arg_value ) ) {
6832
				continue;
6833
			}
6834
6835
			$to_be_added[ $arg_name ] = rawurlencode( $arg_value );
6836
6837
		}
6838
6839
		if ( ! empty( $to_be_added ) ) {
6840
			$url = add_query_arg( $to_be_added, $url );
6841
		}
6842
6843
		return $url;
6844
	}
6845
6846
	/**
6847
	 * Stores and prints out domains to prefetch for page speed optimization.
6848
	 *
6849
	 * @param mixed $new_urls
6850
	 */
6851
	public static function dns_prefetch( $new_urls = null ) {
6852
		static $prefetch_urls = array();
6853
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6854
			echo "\r\n";
6855
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6856
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6857
			}
6858
		} elseif ( ! empty( $new_urls ) ) {
6859
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6860
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6861
			}
6862
			foreach ( (array) $new_urls as $this_new_url ) {
6863
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6864
			}
6865
			$prefetch_urls = array_unique( $prefetch_urls );
6866
		}
6867
	}
6868
6869
	public function wp_dashboard_setup() {
6870
		if ( self::is_active() ) {
6871
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6872
		}
6873
6874
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6875
			$jetpack_logo = new Jetpack_Logo();
6876
			$widget_title = sprintf(
6877
				wp_kses(
6878
					/* translators: Placeholder is a Jetpack logo. */
6879
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6880
					array( 'span' => array() )
6881
				),
6882
				$jetpack_logo->get_jp_emblem( true )
6883
			);
6884
6885
			wp_add_dashboard_widget(
6886
				'jetpack_summary_widget',
6887
				$widget_title,
6888
				array( __CLASS__, 'dashboard_widget' )
6889
			);
6890
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6891
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6892
6893
			// If we're inactive and not in development mode, sort our box to the top.
6894
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6895
				global $wp_meta_boxes;
6896
6897
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6898
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6899
6900
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6901
			}
6902
		}
6903
	}
6904
6905
	/**
6906
	 * @param mixed $result Value for the user's option
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
6907
	 * @return mixed
6908
	 */
6909
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6910
		if ( ! is_array( $sorted ) ) {
6911
			return $sorted;
6912
		}
6913
6914
		foreach ( $sorted as $box_context => $ids ) {
6915
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6916
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6917
				continue;
6918
			}
6919
6920
			$ids_array = explode( ',', $ids );
6921
			$key       = array_search( 'dashboard_stats', $ids_array );
6922
6923
			if ( false !== $key ) {
6924
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6925
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6926
				$sorted[ $box_context ] = implode( ',', $ids_array );
6927
				// We've found it, stop searching, and just return.
6928
				break;
6929
			}
6930
		}
6931
6932
		return $sorted;
6933
	}
6934
6935
	public static function dashboard_widget() {
6936
		/**
6937
		 * Fires when the dashboard is loaded.
6938
		 *
6939
		 * @since 3.4.0
6940
		 */
6941
		do_action( 'jetpack_dashboard_widget' );
6942
	}
6943
6944
	public static function dashboard_widget_footer() {
6945
		?>
6946
		<footer>
6947
6948
		<div class="protect">
6949
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6950
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6951
				<p class="blocked-count">
6952
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6953
				</p>
6954
				<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>
6955
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6956
				<a href="
6957
				<?php
6958
				echo esc_url(
6959
					wp_nonce_url(
6960
						self::admin_url(
6961
							array(
6962
								'action' => 'activate',
6963
								'module' => 'protect',
6964
							)
6965
						),
6966
						'jetpack_activate-protect'
6967
					)
6968
				);
6969
				?>
6970
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6971
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6972
				</a>
6973
			<?php else : ?>
6974
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6975
			<?php endif; ?>
6976
		</div>
6977
6978
		<div class="akismet">
6979
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6980
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6981
				<p class="blocked-count">
6982
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6983
				</p>
6984
				<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>
6985
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6986
				<a href="
6987
				<?php
6988
				echo esc_url(
6989
					wp_nonce_url(
6990
						add_query_arg(
6991
							array(
6992
								'action' => 'activate',
6993
								'plugin' => 'akismet/akismet.php',
6994
							),
6995
							admin_url( 'plugins.php' )
6996
						),
6997
						'activate-plugin_akismet/akismet.php'
6998
					)
6999
				);
7000
				?>
7001
							" class="button button-jetpack">
7002
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7003
				</a>
7004
			<?php else : ?>
7005
				<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>
7006
			<?php endif; ?>
7007
		</div>
7008
7009
		</footer>
7010
		<?php
7011
	}
7012
7013
	/*
7014
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7015
	 */
7016
	function jetpack_icon_user_connected( $columns ) {
7017
		$columns['user_jetpack'] = '';
7018
		return $columns;
7019
	}
7020
7021
	/*
7022
	 * Show Jetpack icon if the user is linked.
7023
	 */
7024
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7025
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7026
			$jetpack_logo = new Jetpack_Logo();
7027
			$emblem_html  = sprintf(
7028
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7029
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7030
				$jetpack_logo->get_jp_emblem()
7031
			);
7032
			return $emblem_html;
7033
		}
7034
7035
		return $val;
7036
	}
7037
7038
	/*
7039
	 * Style the Jetpack user column
7040
	 */
7041
	function jetpack_user_col_style() {
7042
		global $current_screen;
7043
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7044
			?>
7045
			<style>
7046
				.fixed .column-user_jetpack {
7047
					width: 21px;
7048
				}
7049
				.jp-emblem-user-admin svg {
7050
					width: 20px;
7051
					height: 20px;
7052
				}
7053
				.jp-emblem-user-admin path {
7054
					fill: #00BE28;
7055
				}
7056
			</style>
7057
			<?php
7058
		}
7059
	}
7060
7061
	/**
7062
	 * Checks if Akismet is active and working.
7063
	 *
7064
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7065
	 * that implied usage of methods present since more recent version.
7066
	 * See https://github.com/Automattic/jetpack/pull/9585
7067
	 *
7068
	 * @since  5.1.0
7069
	 *
7070
	 * @return bool True = Akismet available. False = Aksimet not available.
7071
	 */
7072
	public static function is_akismet_active() {
7073
		static $status = null;
7074
7075
		if ( ! is_null( $status ) ) {
7076
			return $status;
7077
		}
7078
7079
		// Check if a modern version of Akismet is active.
7080
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7081
			$status = false;
7082
			return $status;
7083
		}
7084
7085
		// Make sure there is a key known to Akismet at all before verifying key.
7086
		$akismet_key = Akismet::get_api_key();
7087
		if ( ! $akismet_key ) {
7088
			$status = false;
7089
			return $status;
7090
		}
7091
7092
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7093
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7094
7095
		// 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.
7096
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7097
		// We cache the result of the Akismet key verification for ten minutes.
7098
		if ( ! $akismet_key_state || $recheck ) {
7099
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7100
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7101
		}
7102
7103
		$status = 'valid' === $akismet_key_state;
7104
7105
		return $status;
7106
	}
7107
7108
	/**
7109
	 * @deprecated
7110
	 *
7111
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7112
	 */
7113
	public static function is_function_in_backtrace() {
7114
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7115
	}
7116
7117
	/**
7118
	 * Given a minified path, and a non-minified path, will return
7119
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7120
	 *
7121
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7122
	 * root Jetpack directory.
7123
	 *
7124
	 * @since 5.6.0
7125
	 *
7126
	 * @param string $min_path
7127
	 * @param string $non_min_path
7128
	 * @return string The URL to the file
7129
	 */
7130
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7131
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7132
	}
7133
7134
	/**
7135
	 * Checks for whether Jetpack Backup & Scan is enabled.
7136
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7137
	 *
7138
	 * @return bool|int|mixed
7139
	 */
7140
	public static function is_rewind_enabled() {
7141
		if ( ! self::is_active() ) {
7142
			return false;
7143
		}
7144
7145
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7146
		if ( false === $rewind_enabled ) {
7147
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7148
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7149
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7150
				&& ! empty( $rewind_data['state'] )
7151
				&& 'active' === $rewind_data['state'] )
7152
				? 1
7153
				: 0;
7154
7155
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7156
		}
7157
		return $rewind_enabled;
7158
	}
7159
7160
	/**
7161
	 * Return Calypso environment value; used for developing Jetpack and pairing
7162
	 * it with different Calypso enrionments, such as localhost.
7163
	 *
7164
	 * @since 7.4.0
7165
	 *
7166
	 * @return string Calypso environment
7167
	 */
7168
	public static function get_calypso_env() {
7169
		if ( isset( $_GET['calypso_env'] ) ) {
7170
			return sanitize_key( $_GET['calypso_env'] );
7171
		}
7172
7173
		if ( getenv( 'CALYPSO_ENV' ) ) {
7174
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7175
		}
7176
7177
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7178
			return sanitize_key( CALYPSO_ENV );
7179
		}
7180
7181
		return '';
7182
	}
7183
7184
	/**
7185
	 * Checks whether or not TOS has been agreed upon.
7186
	 * Will return true if a user has clicked to register, or is already connected.
7187
	 */
7188
	public static function jetpack_tos_agreed() {
7189
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7190
7191
		$terms_of_service = new Terms_Of_Service();
7192
		return $terms_of_service->has_agreed();
7193
7194
	}
7195
7196
	/**
7197
	 * Handles activating default modules as well general cleanup for the new connection.
7198
	 *
7199
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7200
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7201
	 * @param boolean $send_state_messages          Whether to send state messages.
7202
	 * @return void
7203
	 */
7204
	public static function handle_post_authorization_actions(
7205
		$activate_sso = false,
7206
		$redirect_on_activation_error = false,
7207
		$send_state_messages = true
7208
	) {
7209
		$other_modules = $activate_sso
7210
			? array( 'sso' )
7211
			: array();
7212
7213
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7214
			self::delete_active_modules();
7215
7216
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7217
		} else {
7218
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7219
		}
7220
7221
		// Since this is a fresh connection, be sure to clear out IDC options
7222
		Jetpack_IDC::clear_all_idc_options();
7223
7224
		if ( $send_state_messages ) {
7225
			self::state( 'message', 'authorized' );
7226
		}
7227
	}
7228
7229
	/**
7230
	 * Returns a boolean for whether backups UI should be displayed or not.
7231
	 *
7232
	 * @return bool Should backups UI be displayed?
7233
	 */
7234
	public static function show_backups_ui() {
7235
		/**
7236
		 * Whether UI for backups should be displayed.
7237
		 *
7238
		 * @since 6.5.0
7239
		 *
7240
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7241
		 */
7242
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7243
	}
7244
7245
	/*
7246
	 * Deprecated manage functions
7247
	 */
7248
	function prepare_manage_jetpack_notice() {
7249
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7250
	}
7251
	function manage_activate_screen() {
7252
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7253
	}
7254
	function admin_jetpack_manage_notice() {
7255
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7256
	}
7257
	function opt_out_jetpack_manage_url() {
7258
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7259
	}
7260
	function opt_in_jetpack_manage_url() {
7261
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7262
	}
7263
	function opt_in_jetpack_manage_notice() {
7264
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7265
	}
7266
	function can_display_jetpack_manage_notice() {
7267
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7268
	}
7269
7270
	/**
7271
	 * Clean leftoveruser meta.
7272
	 *
7273
	 * Delete Jetpack-related user meta when it is no longer needed.
7274
	 *
7275
	 * @since 7.3.0
7276
	 *
7277
	 * @param int $user_id User ID being updated.
7278
	 */
7279
	public static function user_meta_cleanup( $user_id ) {
7280
		$meta_keys = array(
7281
			// AtD removed from Jetpack 7.3
7282
			'AtD_options',
7283
			'AtD_check_when',
7284
			'AtD_guess_lang',
7285
			'AtD_ignored_phrases',
7286
		);
7287
7288
		foreach ( $meta_keys as $meta_key ) {
7289
			if ( get_user_meta( $user_id, $meta_key ) ) {
7290
				delete_user_meta( $user_id, $meta_key );
7291
			}
7292
		}
7293
	}
7294
7295
	/**
7296
	 * Checks if a Jetpack site is both active and not in development.
7297
	 *
7298
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7299
	 *
7300
	 * @return bool True if Jetpack is active and not in development.
7301
	 */
7302
	public static function is_active_and_not_development_mode() {
7303
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7304
			return false;
7305
		}
7306
		return true;
7307
	}
7308
}
7309