Completed
Push — instant-search-master ( 9522da...404687 )
by
unknown
07:50 queued 10s
created

Jetpack::add_configure_hook()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 26
rs 9.504
c 0
b 0
f 0
1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\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
				// Minileven deprecation. 8.3.0.
439
				if ( get_option( 'wp_mobile_custom_css' ) ) {
440
					delete_option( 'wp_mobile_custom_css' );
441
				}
442
				if ( Jetpack_Options::get_option( 'wp_mobile_excerpt' ) ) {
443
					Jetpack_Options::delete_option( 'wp_mobile_excerpt' );
444
				}
445
				if ( Jetpack_Options::get_option( 'wp_mobile_featured_images' ) ) {
446
					Jetpack_Options::delete_option( 'wp_mobile_featured_images' );
447
				}
448
				if ( Jetpack_Options::get_option( 'wp_mobile_app_promos' ) ) {
449
					Jetpack_Options::delete_option( 'wp_mobile_app_promos' );
450
				}
451
452
				if ( did_action( 'wp_loaded' ) ) {
453
					self::upgrade_on_load();
454
				} else {
455
					add_action(
456
						'wp_loaded',
457
						array( __CLASS__, 'upgrade_on_load' )
458
					);
459
				}
460
			}
461
		}
462
	}
463
464
	/**
465
	 * Runs upgrade routines that need to have modules loaded.
466
	 */
467
	static function upgrade_on_load() {
468
469
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
470
		// This can happen in case Jetpack has been just upgraded and is
471
		// being initialized late during the page load. In this case we wait
472
		// until the next proper admin page load with Jetpack active.
473
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
474
			delete_transient( self::$plugin_upgrade_lock_key );
475
476
			return;
477
		}
478
479
		self::maybe_set_version_option();
480
481
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
482
			Jetpack_Widget_Conditions::migrate_post_type_rules();
483
		}
484
485
		if (
486
			class_exists( 'Jetpack_Sitemap_Manager' )
487
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
488
		) {
489
			do_action( 'jetpack_sitemaps_purge_data' );
490
		}
491
492
		// Delete old stats cache
493
		delete_option( 'jetpack_restapi_stats_cache' );
494
495
		delete_transient( self::$plugin_upgrade_lock_key );
496
	}
497
498
	/**
499
	 * Saves all the currently active modules to options.
500
	 * Also fires Action hooks for each newly activated and deactivated module.
501
	 *
502
	 * @param $modules Array Array of active modules to be saved in options.
503
	 *
504
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
The doc-type $success could not be parsed: Unknown type name "$success" at position 0. (view supported doc-types)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2293
2294
		if ( $redirect ) {
2295
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2296
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2297
				$page = $_GET['page'];
2298
			}
2299
2300
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2301
			exit;
2302
		}
2303
	}
2304
2305
	/**
2306
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2307
	 * Make sure to tuck away module "library" files in a sub-directory.
2308
	 */
2309
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2310
		static $modules = null;
2311
2312
		if ( ! isset( $modules ) ) {
2313
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2314
			// Use the cache if we're on the front-end and it's available...
2315
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2316
				$modules = $available_modules_option[ JETPACK__VERSION ];
2317
			} else {
2318
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2319
2320
				$modules = array();
2321
2322
				foreach ( $files as $file ) {
2323
					if ( ! $headers = self::get_module( $file ) ) {
2324
						continue;
2325
					}
2326
2327
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2328
				}
2329
2330
				Jetpack_Options::update_option(
2331
					'available_modules',
2332
					array(
2333
						JETPACK__VERSION => $modules,
2334
					)
2335
				);
2336
			}
2337
		}
2338
2339
		/**
2340
		 * Filters the array of modules available to be activated.
2341
		 *
2342
		 * @since 2.4.0
2343
		 *
2344
		 * @param array $modules Array of available modules.
2345
		 * @param string $min_version Minimum version number required to use modules.
2346
		 * @param string $max_version Maximum version number required to use modules.
2347
		 */
2348
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2349
2350
		if ( ! $min_version && ! $max_version ) {
2351
			return array_keys( $mods );
2352
		}
2353
2354
		$r = array();
2355
		foreach ( $mods as $slug => $introduced ) {
2356
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2357
				continue;
2358
			}
2359
2360
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2361
				continue;
2362
			}
2363
2364
			$r[] = $slug;
2365
		}
2366
2367
		return $r;
2368
	}
2369
2370
	/**
2371
	 * Default modules loaded on activation.
2372
	 */
2373
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2374
		$return = array();
2375
2376
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2377
			$module_data = self::get_module( $module );
2378
2379
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2380
				case 'yes':
2381
					$return[] = $module;
2382
					break;
2383
				case 'public':
2384
					if ( Jetpack_Options::get_option( 'public' ) ) {
2385
						$return[] = $module;
2386
					}
2387
					break;
2388
				case 'no':
2389
				default:
2390
					break;
2391
			}
2392
		}
2393
		/**
2394
		 * Filters the array of default modules.
2395
		 *
2396
		 * @since 2.5.0
2397
		 *
2398
		 * @param array $return Array of default modules.
2399
		 * @param string $min_version Minimum version number required to use modules.
2400
		 * @param string $max_version Maximum version number required to use modules.
2401
		 */
2402
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2403
	}
2404
2405
	/**
2406
	 * Checks activated modules during auto-activation to determine
2407
	 * if any of those modules are being deprecated.  If so, close
2408
	 * them out, and add any replacement modules.
2409
	 *
2410
	 * Runs at priority 99 by default.
2411
	 *
2412
	 * This is run late, so that it can still activate a module if
2413
	 * the new module is a replacement for another that the user
2414
	 * currently has active, even if something at the normal priority
2415
	 * would kibosh everything.
2416
	 *
2417
	 * @since 2.6
2418
	 * @uses jetpack_get_default_modules filter
2419
	 * @param array $modules
2420
	 * @return array
2421
	 */
2422
	function handle_deprecated_modules( $modules ) {
2423
		$deprecated_modules = array(
2424
			'debug'            => null,  // Closed out and moved to the debugger library.
2425
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2426
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2427
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2428
		);
2429
2430
		// Don't activate SSO if they never completed activating WPCC.
2431
		if ( self::is_module_active( 'wpcc' ) ) {
2432
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2433
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2434
				$deprecated_modules['wpcc'] = null;
2435
			}
2436
		}
2437
2438
		foreach ( $deprecated_modules as $module => $replacement ) {
2439
			if ( self::is_module_active( $module ) ) {
2440
				self::deactivate_module( $module );
2441
				if ( $replacement ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $replacement of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3079
		ob_end_clean();
3080
		self::catch_errors( false );
3081
3082
		if ( $redirect ) {
3083
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3084
		}
3085
		if ( $exit ) {
3086
			exit;
3087
		}
3088
		return true;
3089
	}
3090
3091
	function activate_module_actions( $module ) {
3092
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3093
	}
3094
3095
	public static function deactivate_module( $module ) {
3096
		/**
3097
		 * Fires when a module is deactivated.
3098
		 *
3099
		 * @since 1.9.0
3100
		 *
3101
		 * @param string $module Module slug.
3102
		 */
3103
		do_action( 'jetpack_pre_deactivate_module', $module );
3104
3105
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3106
3107
		$active = self::get_active_modules();
3108
		$new    = array_filter( array_diff( $active, (array) $module ) );
3109
3110
		return self::update_active_modules( $new );
3111
	}
3112
3113
	public static function enable_module_configurable( $module ) {
3114
		$module = self::get_module_slug( $module );
3115
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3116
	}
3117
3118
	/**
3119
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3120
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3121
	 *
3122
	 * @param string $module Module slug
3123
	 * @return string $url module configuration URL
3124
	 */
3125
	public static function module_configuration_url( $module ) {
3126
		$module      = self::get_module_slug( $module );
3127
		$default_url = self::admin_url() . "#/settings?term=$module";
3128
		/**
3129
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3130
		 *
3131
		 * @since 6.9.0
3132
		 *
3133
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3134
		 */
3135
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3136
3137
		return $url;
3138
	}
3139
3140
	/* Installation */
3141
	public static function bail_on_activation( $message, $deactivate = true ) {
3142
		?>
3143
<!doctype html>
3144
<html>
3145
<head>
3146
<meta charset="<?php bloginfo( 'charset' ); ?>">
3147
<style>
3148
* {
3149
	text-align: center;
3150
	margin: 0;
3151
	padding: 0;
3152
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3153
}
3154
p {
3155
	margin-top: 1em;
3156
	font-size: 18px;
3157
}
3158
</style>
3159
<body>
3160
<p><?php echo esc_html( $message ); ?></p>
3161
</body>
3162
</html>
3163
		<?php
3164
		if ( $deactivate ) {
3165
			$plugins = get_option( 'active_plugins' );
3166
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3167
			$update  = false;
3168
			foreach ( $plugins as $i => $plugin ) {
3169
				if ( $plugin === $jetpack ) {
3170
					$plugins[ $i ] = false;
3171
					$update        = true;
3172
				}
3173
			}
3174
3175
			if ( $update ) {
3176
				update_option( 'active_plugins', array_filter( $plugins ) );
3177
			}
3178
		}
3179
		exit;
3180
	}
3181
3182
	/**
3183
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3184
	 *
3185
	 * @static
3186
	 */
3187
	public static function plugin_activation( $network_wide ) {
3188
		Jetpack_Options::update_option( 'activated', 1 );
3189
3190
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3191
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3192
		}
3193
3194
		if ( $network_wide ) {
3195
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
4099
4100
						/**
4101
						 * Jetpack registration Error.
4102
						 *
4103
						 * @since 7.5.0
4104
						 *
4105
						 * @param string|int $error The error code.
4106
						 * @param \WP_Error $registered The error object.
4107
						 */
4108
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4109
						break;
4110
					}
4111
4112
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4113
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4114
4115
					/**
4116
					 * Jetpack registration Success.
4117
					 *
4118
					 * @since 7.5.0
4119
					 *
4120
					 * @param string $from 'from' GET parameter;
4121
					 */
4122
					do_action( 'jetpack_connection_register_success', $from );
4123
4124
					$url = $this->build_connect_url( true, $redirect, $from );
4125
4126
					if ( ! empty( $_GET['onboarding'] ) ) {
4127
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4128
					}
4129
4130
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4131
						$url = add_query_arg( 'auth_approved', 'true', $url );
4132
					}
4133
4134
					wp_redirect( $url );
4135
					exit;
4136
				case 'activate':
4137
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4138
						$error = 'cheatin';
4139
						break;
4140
					}
4141
4142
					$module = stripslashes( $_GET['module'] );
4143
					check_admin_referer( "jetpack_activate-$module" );
4144
					self::log( 'activate', $module );
4145
					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...
4146
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4147
					}
4148
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4149
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4150
					exit;
4151
				case 'activate_default_modules':
4152
					check_admin_referer( 'activate_default_modules' );
4153
					self::log( 'activate_default_modules' );
4154
					self::restate();
4155
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4156
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4157
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4158
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4159
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4160
					exit;
4161
				case 'disconnect':
4162
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4163
						$error = 'cheatin';
4164
						break;
4165
					}
4166
4167
					check_admin_referer( 'jetpack-disconnect' );
4168
					self::log( 'disconnect' );
4169
					self::disconnect();
4170
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4171
					exit;
4172
				case 'reconnect':
4173
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4174
						$error = 'cheatin';
4175
						break;
4176
					}
4177
4178
					check_admin_referer( 'jetpack-reconnect' );
4179
					self::log( 'reconnect' );
4180
					$this->disconnect();
4181
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4182
					exit;
4183 View Code Duplication
				case 'deactivate':
4184
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4185
						$error = 'cheatin';
4186
						break;
4187
					}
4188
4189
					$modules = stripslashes( $_GET['module'] );
4190
					check_admin_referer( "jetpack_deactivate-$modules" );
4191
					foreach ( explode( ',', $modules ) as $module ) {
4192
						self::log( 'deactivate', $module );
4193
						self::deactivate_module( $module );
4194
						self::state( 'message', 'module_deactivated' );
4195
					}
4196
					self::state( 'module', $modules );
4197
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4198
					exit;
4199
				case 'unlink':
4200
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4201
					check_admin_referer( 'jetpack-unlink' );
4202
					self::log( 'unlink' );
4203
					Connection_Manager::disconnect_user();
4204
					self::state( 'message', 'unlinked' );
4205
					if ( 'sub-unlink' == $redirect ) {
4206
						wp_safe_redirect( admin_url() );
4207
					} else {
4208
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4209
					}
4210
					exit;
4211
				case 'onboard':
4212
					if ( ! current_user_can( 'manage_options' ) ) {
4213
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4214
					} else {
4215
						self::create_onboarding_token();
4216
						$url = $this->build_connect_url( true );
4217
4218
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4219
							$url = add_query_arg( 'onboarding', $token, $url );
4220
						}
4221
4222
						$calypso_env = $this->get_calypso_env();
4223
						if ( ! empty( $calypso_env ) ) {
4224
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4225
						}
4226
4227
						wp_redirect( $url );
4228
						exit;
4229
					}
4230
					exit;
4231
				default:
4232
					/**
4233
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4234
					 *
4235
					 * @since 2.6.0
4236
					 *
4237
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4238
					 */
4239
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4240
			}
4241
		}
4242
4243
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4244
			self::activate_new_modules( true );
4245
		}
4246
4247
		$message_code = self::state( 'message' );
4248
		if ( self::state( 'optin-manage' ) ) {
4249
			$activated_manage = $message_code;
4250
			$message_code     = 'jetpack-manage';
4251
		}
4252
4253
		switch ( $message_code ) {
4254
			case 'jetpack-manage':
4255
				$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' ), 'https://wordpress.com/sites' ) . '</strong>';
4256
				if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

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

Loading history...
4453
			: 'should-not-happen';
4454
4455
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4456
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4457
			// No need to update the option if we already have
4458
			// this code stored.
4459
			return;
4460
		}
4461
		$xmlrpc_errors[ $code ] = true;
4462
4463
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
4608
	 * @return string Signed user role.
4609
	 */
4610
	public static function sign_role( $role, $user_id = null ) {
4611
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4612
		return self::connection()->sign_role( $role, $user_id );
4613
	}
4614
4615
	/**
4616
	 * Builds a URL to the Jetpack connection auth page
4617
	 *
4618
	 * @since 3.9.5
4619
	 *
4620
	 * @param bool        $raw If true, URL will not be escaped.
4621
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4622
	 *                              If string, will be a custom redirect.
4623
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4624
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4625
	 *
4626
	 * @return string Connect URL
4627
	 */
4628
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4629
		$site_id    = Jetpack_Options::get_option( 'id' );
4630
		$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...
4631
4632
		if ( $register || ! $blog_token || ! $site_id ) {
4633
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4634
4635
			if ( ! empty( $redirect ) ) {
4636
				$url = add_query_arg(
4637
					'redirect',
4638
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4639
					$url
4640
				);
4641
			}
4642
4643
			if ( is_network_admin() ) {
4644
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4645
			}
4646
4647
			$calypso_env = self::get_calypso_env();
4648
4649
			if ( ! empty( $calypso_env ) ) {
4650
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4651
			}
4652
		} else {
4653
4654
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4655
			// because otherwise this logic can get us in to a loop.
4656
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4657
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4658
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4659
4660
				$response = Client::wpcom_json_api_request_as_blog(
4661
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4662
					'1.1'
4663
				);
4664
4665
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4666
4667
					// Generating a register URL instead to refresh the existing token
4668
					return $this->build_connect_url( $raw, $redirect, $from, true );
4669
				}
4670
			}
4671
4672
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4628 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...
4673
		}
4674
4675
		if ( $from ) {
4676
			$url = add_query_arg( 'from', $from, $url );
4677
		}
4678
4679
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4680
		/**
4681
		 * Filter the URL used when connecting a user to a WordPress.com account.
4682
		 *
4683
		 * @since 8.1.0
4684
		 *
4685
		 * @param string $url Connection URL.
4686
		 * @param bool   $raw If true, URL will not be escaped.
4687
		 */
4688
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4689
	}
4690
4691
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4692
4693
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4694
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4695
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4696
4697
		if ( $iframe ) {
4698
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4699
		}
4700
4701
		$c8n = self::connection();
4702
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

Loading history...
5181
	 * @param Integer $exp     Expiration time in seconds.
5182
	 * @return array
5183
	 */
5184
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5185
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5186
	}
5187
5188
	public static function get_secrets( $action, $user_id ) {
5189
		$secrets = self::connection()->get_secrets( $action, $user_id );
5190
5191
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5192
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

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

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

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

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

Loading history...
5197
		}
5198
5199
		return $secrets;
5200
	}
5201
5202
	/**
5203
	 * @deprecated 7.5 Use Connection_Manager instead.
5204
	 *
5205
	 * @param $action
5206
	 * @param $user_id
5207
	 */
5208
	public static function delete_secrets( $action, $user_id ) {
5209
		return self::connection()->delete_secrets( $action, $user_id );
5210
	}
5211
5212
	/**
5213
	 * Builds the timeout limit for queries talking with the wpcom servers.
5214
	 *
5215
	 * Based on local php max_execution_time in php.ini
5216
	 *
5217
	 * @since 2.6
5218
	 * @return int
5219
	 * @deprecated
5220
	 **/
5221
	public function get_remote_query_timeout_limit() {
5222
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5223
		return self::get_max_execution_time();
5224
	}
5225
5226
	/**
5227
	 * Builds the timeout limit for queries talking with the wpcom servers.
5228
	 *
5229
	 * Based on local php max_execution_time in php.ini
5230
	 *
5231
	 * @since 5.4
5232
	 * @return int
5233
	 **/
5234
	public static function get_max_execution_time() {
5235
		$timeout = (int) ini_get( 'max_execution_time' );
5236
5237
		// Ensure exec time set in php.ini
5238
		if ( ! $timeout ) {
5239
			$timeout = 30;
5240
		}
5241
		return $timeout;
5242
	}
5243
5244
	/**
5245
	 * Sets a minimum request timeout, and returns the current timeout
5246
	 *
5247
	 * @since 5.4
5248
	 **/
5249 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5250
		$timeout = self::get_max_execution_time();
5251
		if ( $timeout < $min_timeout ) {
5252
			$timeout = $min_timeout;
5253
			set_time_limit( $timeout );
5254
		}
5255
		return $timeout;
5256
	}
5257
5258
	/**
5259
	 * Takes the response from the Jetpack register new site endpoint and
5260
	 * verifies it worked properly.
5261
	 *
5262
	 * @since 2.6
5263
	 * @deprecated since 7.7.0
5264
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5265
	 **/
5266
	public function validate_remote_register_response() {
5267
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5268
	}
5269
5270
	/**
5271
	 * @return bool|WP_Error
5272
	 */
5273
	public static function register() {
5274
		$tracking = new Tracking();
5275
		$tracking->record_user_event( 'jpc_register_begin' );
5276
5277
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5278
5279
		$connection   = self::connection();
5280
		$registration = $connection->register();
5281
5282
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5283
5284
		if ( ! $registration || is_wp_error( $registration ) ) {
5285
			return $registration;
5286
		}
5287
5288
		return true;
5289
	}
5290
5291
	/**
5292
	 * Filters the registration request body to include tracking properties.
5293
	 *
5294
	 * @param Array $properties
5295
	 * @return Array amended properties.
5296
	 */
5297 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5298
		$tracking        = new Tracking();
5299
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5300
5301
		return array_merge(
5302
			$properties,
5303
			array(
5304
				'_ui' => $tracks_identity['_ui'],
5305
				'_ut' => $tracks_identity['_ut'],
5306
			)
5307
		);
5308
	}
5309
5310
	/**
5311
	 * Filters the token request body to include tracking properties.
5312
	 *
5313
	 * @param Array $properties
5314
	 * @return Array amended properties.
5315
	 */
5316 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5317
		$tracking        = new Tracking();
5318
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5319
5320
		return array_merge(
5321
			$properties,
5322
			array(
5323
				'_ui' => $tracks_identity['_ui'],
5324
				'_ut' => $tracks_identity['_ut'],
5325
			)
5326
		);
5327
	}
5328
5329
	/**
5330
	 * If the db version is showing something other that what we've got now, bump it to current.
5331
	 *
5332
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5333
	 */
5334
	public static function maybe_set_version_option() {
5335
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5336
		if ( JETPACK__VERSION != $version ) {
5337
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5338
5339
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5340
				/** This action is documented in class.jetpack.php */
5341
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5342
			}
5343
5344
			return true;
5345
		}
5346
		return false;
5347
	}
5348
5349
	/* Client Server API */
5350
5351
	/**
5352
	 * Loads the Jetpack XML-RPC client.
5353
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5354
	 *
5355
	 * @deprecated since 7.7.0
5356
	 */
5357
	public static function load_xml_rpc_client() {
5358
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5359
	}
5360
5361
	/**
5362
	 * Resets the saved authentication state in between testing requests.
5363
	 */
5364
	public function reset_saved_auth_state() {
5365
		$this->rest_authentication_status = null;
5366
		$this->connection_manager->reset_saved_auth_state();
5367
	}
5368
5369
	/**
5370
	 * Verifies the signature of the current request.
5371
	 *
5372
	 * @deprecated since 7.7.0
5373
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5374
	 *
5375
	 * @return false|array
5376
	 */
5377
	public function verify_xml_rpc_signature() {
5378
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5379
		return self::connection()->verify_xml_rpc_signature();
5380
	}
5381
5382
	/**
5383
	 * Verifies the signature of the current request.
5384
	 *
5385
	 * This function has side effects and should not be used. Instead,
5386
	 * use the memoized version `->verify_xml_rpc_signature()`.
5387
	 *
5388
	 * @deprecated since 7.7.0
5389
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5390
	 * @internal
5391
	 */
5392
	private function internal_verify_xml_rpc_signature() {
5393
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5394
	}
5395
5396
	/**
5397
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5398
	 *
5399
	 * @deprecated since 7.7.0
5400
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5401
	 *
5402
	 * @param \WP_User|mixed $user     User object if authenticated.
5403
	 * @param string         $username Username.
5404
	 * @param string         $password Password string.
5405
	 * @return \WP_User|mixed Authenticated user or error.
5406
	 */
5407
	public function authenticate_jetpack( $user, $username, $password ) {
5408
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5409
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5410
	}
5411
5412
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5413
	// Uses the existing XMLRPC request signing implementation.
5414
	function wp_rest_authenticate( $user ) {
5415
		if ( ! empty( $user ) ) {
5416
			// Another authentication method is in effect.
5417
			return $user;
5418
		}
5419
5420
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5421
			// Nothing to do for this authentication method.
5422
			return null;
5423
		}
5424
5425
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5426
			// Nothing to do for this authentication method.
5427
			return null;
5428
		}
5429
5430
		// Ensure that we always have the request body available.  At this
5431
		// point, the WP REST API code to determine the request body has not
5432
		// run yet.  That code may try to read from 'php://input' later, but
5433
		// this can only be done once per request in PHP versions prior to 5.6.
5434
		// So we will go ahead and perform this read now if needed, and save
5435
		// the request body where both the Jetpack signature verification code
5436
		// and the WP REST API code can see it.
5437
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5438
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5439
		}
5440
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5441
5442
		// Only support specific request parameters that have been tested and
5443
		// are known to work with signature verification.  A different method
5444
		// can be passed to the WP REST API via the '?_method=' parameter if
5445
		// needed.
5446
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5447
			$this->rest_authentication_status = new WP_Error(
5448
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5449
				__( 'This request method is not supported.', 'jetpack' ),
5450
				array( 'status' => 400 )
5451
			);
5452
			return null;
5453
		}
5454
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5455
			$this->rest_authentication_status = new WP_Error(
5456
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5457
				__( 'This request method does not support body parameters.', 'jetpack' ),
5458
				array( 'status' => 400 )
5459
			);
5460
			return null;
5461
		}
5462
5463
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5464
5465
		if (
5466
			$verified &&
5467
			isset( $verified['type'] ) &&
5468
			'user' === $verified['type'] &&
5469
			! empty( $verified['user_id'] )
5470
		) {
5471
			// Authentication successful.
5472
			$this->rest_authentication_status = true;
5473
			return $verified['user_id'];
5474
		}
5475
5476
		// Something else went wrong.  Probably a signature error.
5477
		$this->rest_authentication_status = new WP_Error(
5478
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5479
			__( 'The request is not signed correctly.', 'jetpack' ),
5480
			array( 'status' => 400 )
5481
		);
5482
		return null;
5483
	}
5484
5485
	/**
5486
	 * Report authentication status to the WP REST API.
5487
	 *
5488
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5489
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5490
	 */
5491
	public function wp_rest_authentication_errors( $value ) {
5492
		if ( $value !== null ) {
5493
			return $value;
5494
		}
5495
		return $this->rest_authentication_status;
5496
	}
5497
5498
	/**
5499
	 * Add our nonce to this request.
5500
	 *
5501
	 * @deprecated since 7.7.0
5502
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5503
	 *
5504
	 * @param int    $timestamp Timestamp of the request.
5505
	 * @param string $nonce     Nonce string.
5506
	 */
5507
	public function add_nonce( $timestamp, $nonce ) {
5508
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5509
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5510
	}
5511
5512
	/**
5513
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5514
	 * Capture it here so we can verify the signature later.
5515
	 *
5516
	 * @deprecated since 7.7.0
5517
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5518
	 *
5519
	 * @param array $methods XMLRPC methods.
5520
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5521
	 */
5522
	public function xmlrpc_methods( $methods ) {
5523
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5524
		return $this->connection_manager->xmlrpc_methods( $methods );
5525
	}
5526
5527
	/**
5528
	 * Register additional public XMLRPC methods.
5529
	 *
5530
	 * @deprecated since 7.7.0
5531
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5532
	 *
5533
	 * @param array $methods Public XMLRPC methods.
5534
	 * @return array Public XMLRPC methods, with the getOptions one.
5535
	 */
5536
	public function public_xmlrpc_methods( $methods ) {
5537
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5538
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5539
	}
5540
5541
	/**
5542
	 * Handles a getOptions XMLRPC method call.
5543
	 *
5544
	 * @deprecated since 7.7.0
5545
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5546
	 *
5547
	 * @param array $args method call arguments.
5548
	 * @return array an amended XMLRPC server options array.
5549
	 */
5550
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5551
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5552
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

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

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

Loading history...
5553
	}
5554
5555
	/**
5556
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5557
	 *
5558
	 * @deprecated since 7.7.0
5559
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5560
	 *
5561
	 * @param array $options Standard Core options.
5562
	 * @return array Amended options.
5563
	 */
5564
	public function xmlrpc_options( $options ) {
5565
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5566
		return $this->connection_manager->xmlrpc_options( $options );
5567
	}
5568
5569
	/**
5570
	 * Cleans nonces that were saved when calling ::add_nonce.
5571
	 *
5572
	 * @deprecated since 7.7.0
5573
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5574
	 *
5575
	 * @param bool $all whether to clean even non-expired nonces.
5576
	 */
5577
	public static function clean_nonces( $all = false ) {
5578
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5579
		return self::connection()->clean_nonces( $all );
5580
	}
5581
5582
	/**
5583
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5584
	 * SET: state( $key, $value );
5585
	 * GET: $value = state( $key );
5586
	 *
5587
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5589
	 * @param bool   $restate private
5590
	 */
5591
	public static function state( $key = null, $value = null, $restate = false ) {
5592
		static $state = array();
5593
		static $path, $domain;
5594
		if ( ! isset( $path ) ) {
5595
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5596
			$admin_url = self::admin_url();
5597
			$bits      = wp_parse_url( $admin_url );
5598
5599
			if ( is_array( $bits ) ) {
5600
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5601
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5602
			} else {
5603
				$path = $domain = null;
5604
			}
5605
		}
5606
5607
		// Extract state from cookies and delete cookies
5608
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5609
			$yum = $_COOKIE['jetpackState'];
5610
			unset( $_COOKIE['jetpackState'] );
5611
			foreach ( $yum as $k => $v ) {
5612
				if ( strlen( $v ) ) {
5613
					$state[ $k ] = $v;
5614
				}
5615
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5616
			}
5617
		}
5618
5619
		if ( $restate ) {
5620
			foreach ( $state as $k => $v ) {
5621
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5622
			}
5623
			return;
5624
		}
5625
5626
		// Get a state variable
5627
		if ( isset( $key ) && ! isset( $value ) ) {
5628
			if ( array_key_exists( $key, $state ) ) {
5629
				return $state[ $key ];
5630
			}
5631
			return null;
5632
		}
5633
5634
		// Set a state variable
5635
		if ( isset( $key ) && isset( $value ) ) {
5636
			if ( is_array( $value ) && isset( $value[0] ) ) {
5637
				$value = $value[0];
5638
			}
5639
			$state[ $key ] = $value;
5640
			if ( ! headers_sent() ) {
5641
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5642
			}
5643
		}
5644
	}
5645
5646
	public static function restate() {
5647
		self::state( null, null, true );
5648
	}
5649
5650
	public static function check_privacy( $file ) {
5651
		static $is_site_publicly_accessible = null;
5652
5653
		if ( is_null( $is_site_publicly_accessible ) ) {
5654
			$is_site_publicly_accessible = false;
5655
5656
			$rpc = new Jetpack_IXR_Client();
5657
5658
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5659
			if ( $success ) {
5660
				$response = $rpc->getResponse();
5661
				if ( $response ) {
5662
					$is_site_publicly_accessible = true;
5663
				}
5664
			}
5665
5666
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5667
		}
5668
5669
		if ( $is_site_publicly_accessible ) {
5670
			return;
5671
		}
5672
5673
		$module_slug = self::get_module_slug( $file );
5674
5675
		$privacy_checks = self::state( 'privacy_checks' );
5676
		if ( ! $privacy_checks ) {
5677
			$privacy_checks = $module_slug;
5678
		} else {
5679
			$privacy_checks .= ",$module_slug";
5680
		}
5681
5682
		self::state( 'privacy_checks', $privacy_checks );
5683
	}
5684
5685
	/**
5686
	 * Helper method for multicall XMLRPC.
5687
	 *
5688
	 * @param ...$args Args for the async_call.
5689
	 */
5690
	public static function xmlrpc_async_call( ...$args ) {
5691
		global $blog_id;
5692
		static $clients = array();
5693
5694
		$client_blog_id = is_multisite() ? $blog_id : 0;
5695
5696
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5697
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5698
			if ( function_exists( 'ignore_user_abort' ) ) {
5699
				ignore_user_abort( true );
5700
			}
5701
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5702
		}
5703
5704
		if ( ! empty( $args[0] ) ) {
5705
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5706
		} elseif ( is_multisite() ) {
5707
			foreach ( $clients as $client_blog_id => $client ) {
5708
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5709
					continue;
5710
				}
5711
5712
				$switch_success = switch_to_blog( $client_blog_id, true );
5713
				if ( ! $switch_success ) {
5714
					continue;
5715
				}
5716
5717
				flush();
5718
				$client->query();
5719
5720
				restore_current_blog();
5721
			}
5722
		} else {
5723
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5724
				flush();
5725
				$clients[0]->query();
5726
			}
5727
		}
5728
	}
5729
5730
	public static function staticize_subdomain( $url ) {
5731
5732
		// Extract hostname from URL
5733
		$host = wp_parse_url( $url, PHP_URL_HOST );
5734
5735
		// Explode hostname on '.'
5736
		$exploded_host = explode( '.', $host );
5737
5738
		// Retrieve the name and TLD
5739
		if ( count( $exploded_host ) > 1 ) {
5740
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5741
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5742
			// Rebuild domain excluding subdomains
5743
			$domain = $name . '.' . $tld;
5744
		} else {
5745
			$domain = $host;
5746
		}
5747
		// Array of Automattic domains
5748
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5749
5750
		// Return $url if not an Automattic domain
5751
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5752
			return $url;
5753
		}
5754
5755
		if ( is_ssl() ) {
5756
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5757
		}
5758
5759
		srand( crc32( basename( $url ) ) );
5760
		$static_counter = rand( 0, 2 );
5761
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5762
5763
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5764
	}
5765
5766
	/* JSON API Authorization */
5767
5768
	/**
5769
	 * Handles the login action for Authorizing the JSON API
5770
	 */
5771
	function login_form_json_api_authorization() {
5772
		$this->verify_json_api_authorization_request();
5773
5774
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5775
5776
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5777
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5778
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5779
	}
5780
5781
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5782
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5783
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5784
			return $url;
5785
		}
5786
5787
		$parsed_url = wp_parse_url( $url );
5788
		$url        = strtok( $url, '?' );
5789
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5790
		if ( ! empty( $parsed_url['query'] ) ) {
5791
			$url .= "&{$parsed_url['query']}";
5792
		}
5793
5794
		return $url;
5795
	}
5796
5797
	// Make sure the POSTed request is handled by the same action
5798
	function preserve_action_in_login_form_for_json_api_authorization() {
5799
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5800
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5801
	}
5802
5803
	// If someone logs in to approve API access, store the Access Code in usermeta
5804
	function store_json_api_authorization_token( $user_login, $user ) {
5805
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5806
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5807
		$token = wp_generate_password( 32, false );
5808
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5809
	}
5810
5811
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5812
	function allow_wpcom_public_api_domain( $domains ) {
5813
		$domains[] = 'public-api.wordpress.com';
5814
		return $domains;
5815
	}
5816
5817
	static function is_redirect_encoded( $redirect_url ) {
5818
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5819
	}
5820
5821
	// Add all wordpress.com environments to the safe redirect whitelist
5822
	function allow_wpcom_environments( $domains ) {
5823
		$domains[] = 'wordpress.com';
5824
		$domains[] = 'wpcalypso.wordpress.com';
5825
		$domains[] = 'horizon.wordpress.com';
5826
		$domains[] = 'calypso.localhost';
5827
		return $domains;
5828
	}
5829
5830
	// Add the Access Code details to the public-api.wordpress.com redirect
5831
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5832
		return add_query_arg(
5833
			urlencode_deep(
5834
				array(
5835
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5836
					'jetpack-user-id' => (int) $user->ID,
5837
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5838
				)
5839
			),
5840
			$redirect_to
5841
		);
5842
	}
5843
5844
5845
	/**
5846
	 * Verifies the request by checking the signature
5847
	 *
5848
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5849
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5850
	 *
5851
	 * @param null|array $environment
5852
	 */
5853
	function verify_json_api_authorization_request( $environment = null ) {
5854
		$environment = is_null( $environment )
5855
			? $_REQUEST
5856
			: $environment;
5857
5858
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5859
		$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...
5860
		if ( ! $token || empty( $token->secret ) ) {
5861
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5862
		}
5863
5864
		$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' );
5865
5866
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5867
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5868
			/**
5869
			 * Jetpack authorisation request Error.
5870
			 *
5871
			 * @since 7.5.0
5872
			 */
5873
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5874
			$die_error = sprintf(
5875
				/* translators: %s is a URL */
5876
				__( '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' ),
5877
				'https://jetpack.com/support/double-encoding/'
5878
			);
5879
		}
5880
5881
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5882
5883
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5884
			$signature = $jetpack_signature->sign_request(
5885
				$environment['token'],
5886
				$environment['timestamp'],
5887
				$environment['nonce'],
5888
				'',
5889
				'GET',
5890
				$environment['jetpack_json_api_original_query'],
5891
				null,
5892
				true
5893
			);
5894
		} else {
5895
			$signature = $jetpack_signature->sign_current_request(
5896
				array(
5897
					'body'   => null,
5898
					'method' => 'GET',
5899
				)
5900
			);
5901
		}
5902
5903
		if ( ! $signature ) {
5904
			wp_die( $die_error );
5905
		} elseif ( is_wp_error( $signature ) ) {
5906
			wp_die( $die_error );
5907
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5908
			if ( is_ssl() ) {
5909
				// 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
5910
				$signature = $jetpack_signature->sign_current_request(
5911
					array(
5912
						'scheme' => 'http',
5913
						'body'   => null,
5914
						'method' => 'GET',
5915
					)
5916
				);
5917
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5918
					wp_die( $die_error );
5919
				}
5920
			} else {
5921
				wp_die( $die_error );
5922
			}
5923
		}
5924
5925
		$timestamp = (int) $environment['timestamp'];
5926
		$nonce     = stripslashes( (string) $environment['nonce'] );
5927
5928
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5929
			// De-nonce the nonce, at least for 5 minutes.
5930
			// 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)
5931
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5932
			if ( $old_nonce_time < time() - 300 ) {
5933
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5934
			}
5935
		}
5936
5937
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5938
		$data_filters = array(
5939
			'state'        => 'opaque',
5940
			'client_id'    => 'int',
5941
			'client_title' => 'string',
5942
			'client_image' => 'url',
5943
		);
5944
5945
		foreach ( $data_filters as $key => $sanitation ) {
5946
			if ( ! isset( $data->$key ) ) {
5947
				wp_die( $die_error );
5948
			}
5949
5950
			switch ( $sanitation ) {
5951
				case 'int':
5952
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5953
					break;
5954
				case 'opaque':
5955
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5956
					break;
5957
				case 'string':
5958
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5959
					break;
5960
				case 'url':
5961
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5962
					break;
5963
			}
5964
		}
5965
5966
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5967
			wp_die( $die_error );
5968
		}
5969
	}
5970
5971
	function login_message_json_api_authorization( $message ) {
5972
		return '<p class="message">' . sprintf(
5973
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5974
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5975
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5976
	}
5977
5978
	/**
5979
	 * Get $content_width, but with a <s>twist</s> filter.
5980
	 */
5981
	public static function get_content_width() {
5982
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5983
			? $GLOBALS['content_width']
5984
			: false;
5985
		/**
5986
		 * Filter the Content Width value.
5987
		 *
5988
		 * @since 2.2.3
5989
		 *
5990
		 * @param string $content_width Content Width value.
5991
		 */
5992
		return apply_filters( 'jetpack_content_width', $content_width );
5993
	}
5994
5995
	/**
5996
	 * Pings the WordPress.com Mirror Site for the specified options.
5997
	 *
5998
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5999
	 *
6000
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6001
	 */
6002
	public function get_cloud_site_options( $option_names ) {
6003
		$option_names = array_filter( (array) $option_names, 'is_string' );
6004
6005
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6006
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6007
		if ( $xml->isError() ) {
6008
			return array(
6009
				'error_code' => $xml->getErrorCode(),
6010
				'error_msg'  => $xml->getErrorMessage(),
6011
			);
6012
		}
6013
		$cloud_site_options = $xml->getResponse();
6014
6015
		return $cloud_site_options;
6016
	}
6017
6018
	/**
6019
	 * Checks if the site is currently in an identity crisis.
6020
	 *
6021
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6022
	 */
6023
	public static function check_identity_crisis() {
6024
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6025
			return false;
6026
		}
6027
6028
		return Jetpack_Options::get_option( 'sync_error_idc' );
6029
	}
6030
6031
	/**
6032
	 * Checks whether the home and siteurl specifically are whitelisted
6033
	 * Written so that we don't have re-check $key and $value params every time
6034
	 * we want to check if this site is whitelisted, for example in footer.php
6035
	 *
6036
	 * @since  3.8.0
6037
	 * @return bool True = already whitelisted False = not whitelisted
6038
	 */
6039
	public static function is_staging_site() {
6040
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6041
		return ( new Status() )->is_staging_site();
6042
	}
6043
6044
	/**
6045
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6046
	 *
6047
	 * @since 4.4.0
6048
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6049
	 *
6050
	 * @return bool
6051
	 */
6052
	public static function validate_sync_error_idc_option() {
6053
		$is_valid = false;
6054
6055
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6056
		if ( false === $idc_allowed ) {
6057
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6058
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6059
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6060
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6061
				$transient_duration = HOUR_IN_SECONDS;
6062
			} else {
6063
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6064
				$idc_allowed        = '1';
6065
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6066
			}
6067
6068
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6069
		}
6070
6071
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6072
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6073
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6074
			$local_options = self::get_sync_error_idc_option();
6075
			// Ensure all values are set.
6076
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6077
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6078
					$is_valid = true;
6079
				}
6080
			}
6081
6082
		}
6083
6084
		/**
6085
		 * Filters whether the sync_error_idc option is valid.
6086
		 *
6087
		 * @since 4.4.0
6088
		 *
6089
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6090
		 */
6091
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6092
6093
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6094
			// Since the option exists, and did not validate, delete it
6095
			Jetpack_Options::delete_option( 'sync_error_idc' );
6096
		}
6097
6098
		return $is_valid;
6099
	}
6100
6101
	/**
6102
	 * Normalizes a url by doing three things:
6103
	 *  - Strips protocol
6104
	 *  - Strips www
6105
	 *  - Adds a trailing slash
6106
	 *
6107
	 * @since 4.4.0
6108
	 * @param string $url
6109
	 * @return WP_Error|string
6110
	 */
6111
	public static function normalize_url_protocol_agnostic( $url ) {
6112
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6113
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6114
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
6115
		}
6116
6117
		// Strip www and protocols
6118
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6119
		return $url;
6120
	}
6121
6122
	/**
6123
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6124
	 *
6125
	 * @since 4.4.0
6126
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6127
	 *
6128
	 * @param array $response
6129
	 * @return array Array of the local urls, wpcom urls, and error code
6130
	 */
6131
	public static function get_sync_error_idc_option( $response = array() ) {
6132
		// Since the local options will hit the database directly, store the values
6133
		// in a transient to allow for autoloading and caching on subsequent views.
6134
		$local_options = get_transient( 'jetpack_idc_local' );
6135
		if ( false === $local_options ) {
6136
			$local_options = array(
6137
				'home'    => Functions::home_url(),
6138
				'siteurl' => Functions::site_url(),
6139
			);
6140
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6141
		}
6142
6143
		$options = array_merge( $local_options, $response );
6144
6145
		$returned_values = array();
6146
		foreach ( $options as $key => $option ) {
6147
			if ( 'error_code' === $key ) {
6148
				$returned_values[ $key ] = $option;
6149
				continue;
6150
			}
6151
6152
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6153
				continue;
6154
			}
6155
6156
			$returned_values[ $key ] = $normalized_url;
6157
		}
6158
6159
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6160
6161
		return $returned_values;
6162
	}
6163
6164
	/**
6165
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6166
	 * If set to true, the site will be put into staging mode.
6167
	 *
6168
	 * @since 4.3.2
6169
	 * @return bool
6170
	 */
6171
	public static function sync_idc_optin() {
6172
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6173
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6174
		} else {
6175
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6176
		}
6177
6178
		/**
6179
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6180
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6181
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6182
		 *
6183
		 * @since 4.3.2
6184
		 *
6185
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6186
		 */
6187
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6188
	}
6189
6190
	/**
6191
	 * Maybe Use a .min.css stylesheet, maybe not.
6192
	 *
6193
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6194
	 */
6195
	public static function maybe_min_asset( $url, $path, $plugin ) {
6196
		// Short out on things trying to find actual paths.
6197
		if ( ! $path || empty( $plugin ) ) {
6198
			return $url;
6199
		}
6200
6201
		$path = ltrim( $path, '/' );
6202
6203
		// Strip out the abspath.
6204
		$base = dirname( plugin_basename( $plugin ) );
6205
6206
		// Short out on non-Jetpack assets.
6207
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6208
			return $url;
6209
		}
6210
6211
		// File name parsing.
6212
		$file              = "{$base}/{$path}";
6213
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6214
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6215
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6216
		$extension         = array_shift( $file_name_parts_r );
6217
6218
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6219
			// Already pointing at the minified version.
6220
			if ( 'min' === $file_name_parts_r[0] ) {
6221
				return $url;
6222
			}
6223
6224
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6225
			if ( file_exists( $min_full_path ) ) {
6226
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6227
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6228
				if ( 'css' === $extension ) {
6229
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6230
					self::$min_assets[ $key ] = $path;
6231
				}
6232
			}
6233
		}
6234
6235
		return $url;
6236
	}
6237
6238
	/**
6239
	 * If the asset is minified, let's flag .min as the suffix.
6240
	 *
6241
	 * Attached to `style_loader_src` filter.
6242
	 *
6243
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
6772
	 * @return mixed
6773
	 */
6774
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6775
		if ( ! is_array( $sorted ) ) {
6776
			return $sorted;
6777
		}
6778
6779
		foreach ( $sorted as $box_context => $ids ) {
6780
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6781
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6782
				continue;
6783
			}
6784
6785
			$ids_array = explode( ',', $ids );
6786
			$key       = array_search( 'dashboard_stats', $ids_array );
6787
6788
			if ( false !== $key ) {
6789
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6790
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6791
				$sorted[ $box_context ] = implode( ',', $ids_array );
6792
				// We've found it, stop searching, and just return.
6793
				break;
6794
			}
6795
		}
6796
6797
		return $sorted;
6798
	}
6799
6800
	public static function dashboard_widget() {
6801
		/**
6802
		 * Fires when the dashboard is loaded.
6803
		 *
6804
		 * @since 3.4.0
6805
		 */
6806
		do_action( 'jetpack_dashboard_widget' );
6807
	}
6808
6809
	public static function dashboard_widget_footer() {
6810
		?>
6811
		<footer>
6812
6813
		<div class="protect">
6814
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6815
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6816
				<p class="blocked-count">
6817
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6818
				</p>
6819
				<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>
6820
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6821
				<a href="
6822
				<?php
6823
				echo esc_url(
6824
					wp_nonce_url(
6825
						self::admin_url(
6826
							array(
6827
								'action' => 'activate',
6828
								'module' => 'protect',
6829
							)
6830
						),
6831
						'jetpack_activate-protect'
6832
					)
6833
				);
6834
				?>
6835
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6836
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6837
				</a>
6838
			<?php else : ?>
6839
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6840
			<?php endif; ?>
6841
		</div>
6842
6843
		<div class="akismet">
6844
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6845
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6846
				<p class="blocked-count">
6847
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6848
				</p>
6849
				<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>
6850
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6851
				<a href="
6852
				<?php
6853
				echo esc_url(
6854
					wp_nonce_url(
6855
						add_query_arg(
6856
							array(
6857
								'action' => 'activate',
6858
								'plugin' => 'akismet/akismet.php',
6859
							),
6860
							admin_url( 'plugins.php' )
6861
						),
6862
						'activate-plugin_akismet/akismet.php'
6863
					)
6864
				);
6865
				?>
6866
							" class="button button-jetpack">
6867
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6868
				</a>
6869
			<?php else : ?>
6870
				<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>
6871
			<?php endif; ?>
6872
		</div>
6873
6874
		</footer>
6875
		<?php
6876
	}
6877
6878
	/*
6879
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6880
	 */
6881
	function jetpack_icon_user_connected( $columns ) {
6882
		$columns['user_jetpack'] = '';
6883
		return $columns;
6884
	}
6885
6886
	/*
6887
	 * Show Jetpack icon if the user is linked.
6888
	 */
6889
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6890
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6891
			$jetpack_logo = new Jetpack_Logo();
6892
			$emblem_html  = sprintf(
6893
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6894
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6895
				$jetpack_logo->get_jp_emblem()
6896
			);
6897
			return $emblem_html;
6898
		}
6899
6900
		return $val;
6901
	}
6902
6903
	/*
6904
	 * Style the Jetpack user column
6905
	 */
6906
	function jetpack_user_col_style() {
6907
		global $current_screen;
6908
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6909
			?>
6910
			<style>
6911
				.fixed .column-user_jetpack {
6912
					width: 21px;
6913
				}
6914
				.jp-emblem-user-admin svg {
6915
					width: 20px;
6916
					height: 20px;
6917
				}
6918
				.jp-emblem-user-admin path {
6919
					fill: #00BE28;
6920
				}
6921
			</style>
6922
			<?php
6923
		}
6924
	}
6925
6926
	/**
6927
	 * Checks if Akismet is active and working.
6928
	 *
6929
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6930
	 * that implied usage of methods present since more recent version.
6931
	 * See https://github.com/Automattic/jetpack/pull/9585
6932
	 *
6933
	 * @since  5.1.0
6934
	 *
6935
	 * @return bool True = Akismet available. False = Aksimet not available.
6936
	 */
6937
	public static function is_akismet_active() {
6938
		static $status = null;
6939
6940
		if ( ! is_null( $status ) ) {
6941
			return $status;
6942
		}
6943
6944
		// Check if a modern version of Akismet is active.
6945
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6946
			$status = false;
6947
			return $status;
6948
		}
6949
6950
		// Make sure there is a key known to Akismet at all before verifying key.
6951
		$akismet_key = Akismet::get_api_key();
6952
		if ( ! $akismet_key ) {
6953
			$status = false;
6954
			return $status;
6955
		}
6956
6957
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6958
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6959
6960
		// 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.
6961
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6962
		// We cache the result of the Akismet key verification for ten minutes.
6963
		if ( ! $akismet_key_state || $recheck ) {
6964
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6965
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6966
		}
6967
6968
		$status = 'valid' === $akismet_key_state;
6969
6970
		return $status;
6971
	}
6972
6973
	/**
6974
	 * @deprecated
6975
	 *
6976
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6977
	 */
6978
	public static function is_function_in_backtrace() {
6979
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6980
	}
6981
6982
	/**
6983
	 * Given a minified path, and a non-minified path, will return
6984
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6985
	 *
6986
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6987
	 * root Jetpack directory.
6988
	 *
6989
	 * @since 5.6.0
6990
	 *
6991
	 * @param string $min_path
6992
	 * @param string $non_min_path
6993
	 * @return string The URL to the file
6994
	 */
6995
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6996
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6997
	}
6998
6999
	/**
7000
	 * Checks for whether Jetpack Backup & Scan is enabled.
7001
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7002
	 *
7003
	 * @return bool|int|mixed
7004
	 */
7005
	public static function is_rewind_enabled() {
7006
		if ( ! self::is_active() ) {
7007
			return false;
7008
		}
7009
7010
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7011
		if ( false === $rewind_enabled ) {
7012
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7013
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7014
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7015
				&& ! empty( $rewind_data['state'] )
7016
				&& 'active' === $rewind_data['state'] )
7017
				? 1
7018
				: 0;
7019
7020
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7021
		}
7022
		return $rewind_enabled;
7023
	}
7024
7025
	/**
7026
	 * Return Calypso environment value; used for developing Jetpack and pairing
7027
	 * it with different Calypso enrionments, such as localhost.
7028
	 *
7029
	 * @since 7.4.0
7030
	 *
7031
	 * @return string Calypso environment
7032
	 */
7033
	public static function get_calypso_env() {
7034
		if ( isset( $_GET['calypso_env'] ) ) {
7035
			return sanitize_key( $_GET['calypso_env'] );
7036
		}
7037
7038
		if ( getenv( 'CALYPSO_ENV' ) ) {
7039
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7040
		}
7041
7042
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7043
			return sanitize_key( CALYPSO_ENV );
7044
		}
7045
7046
		return '';
7047
	}
7048
7049
	/**
7050
	 * Checks whether or not TOS has been agreed upon.
7051
	 * Will return true if a user has clicked to register, or is already connected.
7052
	 */
7053
	public static function jetpack_tos_agreed() {
7054
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7055
7056
		$terms_of_service = new Terms_Of_Service();
7057
		return $terms_of_service->has_agreed();
7058
7059
	}
7060
7061
	/**
7062
	 * Handles activating default modules as well general cleanup for the new connection.
7063
	 *
7064
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7065
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7066
	 * @param boolean $send_state_messages          Whether to send state messages.
7067
	 * @return void
7068
	 */
7069
	public static function handle_post_authorization_actions(
7070
		$activate_sso = false,
7071
		$redirect_on_activation_error = false,
7072
		$send_state_messages = true
7073
	) {
7074
		$other_modules = $activate_sso
7075
			? array( 'sso' )
7076
			: array();
7077
7078
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7079
			self::delete_active_modules();
7080
7081
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7082
		} else {
7083
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7084
		}
7085
7086
		// Since this is a fresh connection, be sure to clear out IDC options
7087
		Jetpack_IDC::clear_all_idc_options();
7088
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7089
7090
		// Start nonce cleaner
7091
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7092
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7093
7094
		if ( $send_state_messages ) {
7095
			self::state( 'message', 'authorized' );
7096
		}
7097
	}
7098
7099
	/**
7100
	 * Returns a boolean for whether backups UI should be displayed or not.
7101
	 *
7102
	 * @return bool Should backups UI be displayed?
7103
	 */
7104
	public static function show_backups_ui() {
7105
		/**
7106
		 * Whether UI for backups should be displayed.
7107
		 *
7108
		 * @since 6.5.0
7109
		 *
7110
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7111
		 */
7112
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7113
	}
7114
7115
	/*
7116
	 * Deprecated manage functions
7117
	 */
7118
	function prepare_manage_jetpack_notice() {
7119
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7120
	}
7121
	function manage_activate_screen() {
7122
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7123
	}
7124
	function admin_jetpack_manage_notice() {
7125
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7126
	}
7127
	function opt_out_jetpack_manage_url() {
7128
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7129
	}
7130
	function opt_in_jetpack_manage_url() {
7131
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7132
	}
7133
	function opt_in_jetpack_manage_notice() {
7134
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7135
	}
7136
	function can_display_jetpack_manage_notice() {
7137
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7138
	}
7139
7140
	/**
7141
	 * Clean leftoveruser meta.
7142
	 *
7143
	 * Delete Jetpack-related user meta when it is no longer needed.
7144
	 *
7145
	 * @since 7.3.0
7146
	 *
7147
	 * @param int $user_id User ID being updated.
7148
	 */
7149
	public static function user_meta_cleanup( $user_id ) {
7150
		$meta_keys = array(
7151
			// AtD removed from Jetpack 7.3
7152
			'AtD_options',
7153
			'AtD_check_when',
7154
			'AtD_guess_lang',
7155
			'AtD_ignored_phrases',
7156
		);
7157
7158
		foreach ( $meta_keys as $meta_key ) {
7159
			if ( get_user_meta( $user_id, $meta_key ) ) {
7160
				delete_user_meta( $user_id, $meta_key );
7161
			}
7162
		}
7163
	}
7164
7165
	/**
7166
	 * Checks if a Jetpack site is both active and not in development.
7167
	 *
7168
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7169
	 *
7170
	 * @return bool True if Jetpack is active and not in development.
7171
	 */
7172
	public static function is_active_and_not_development_mode() {
7173
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7174
			return false;
7175
		}
7176
		return true;
7177
	}
7178
}
7179