Completed
Push — fix/early-plugins-loaded-hooks ( 4c83b1 )
by
unknown
24:01 queued 17:25
created

Jetpack::add_configure_hook()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 15
rs 9.7666
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
		add_action( 'plugins_loaded', array( $this, 'configure' ), $first_priority - 1 );
582
	}
583
584
	/**
585
	 * Constructor.  Initializes WordPress hooks
586
	 */
587
	private function __construct() {
588
		/*
589
		 * Check for and alert any deprecated hooks
590
		 */
591
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
592
593
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
594
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
595
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
596
597
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
598
599
		add_filter(
600
			'jetpack_signature_check_token',
601
			array( __CLASS__, 'verify_onboarding_token' ),
602
			10,
603
			3
604
		);
605
606
		/**
607
		 * Prepare Gutenberg Editor functionality
608
		 */
609
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
610
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
611
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
612
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
613
614
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
615
616
		// Unlink user before deleting the user from WP.com.
617
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
618
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
619
620
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
621
622
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
623
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
624
625
		add_action( 'admin_init', array( $this, 'admin_init' ) );
626
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
627
628
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
629
630
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
631
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
632
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
633
634
		// returns HTTPS support status
635
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
636
637
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
638
639
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
640
641
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
642
643
		/**
644
		 * These actions run checks to load additional files.
645
		 * They check for external files or plugins, so they need to run as late as possible.
646
		 */
647
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
648
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
649
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
650
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
651
652
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
653
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
654
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
655
656
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
657
658
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
659
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
660
661
		// A filter to control all just in time messages
662
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
663
664
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
665
666
		// Hide edit post link if mobile app.
667
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
668
			add_filter( 'get_edit_post_link', '__return_empty_string' );
669
		}
670
671
		// Update the Jetpack plan from API on heartbeats
672
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
673
674
		/**
675
		 * This is the hack to concatenate all css files into one.
676
		 * For description and reasoning see the implode_frontend_css method
677
		 *
678
		 * Super late priority so we catch all the registered styles
679
		 */
680
		if ( ! is_admin() ) {
681
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
682
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
683
		}
684
685
		/**
686
		 * These are sync actions that we need to keep track of for jitms
687
		 */
688
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
689
690
		// Actually push the stats on shutdown.
691
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
692
			add_action( 'shutdown', array( $this, 'push_stats' ) );
693
		}
694
695
		/*
696
		 * Load some scripts asynchronously.
697
		 */
698
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
699
700
		// Actions for Manager::authorize().
701
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
702
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
703
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
704
705
		// Filters for the Manager::get_token() urls and request body.
706
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
707
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
708
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
709
	}
710
711
	/**
712
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
713
	 * Config object.
714
	 */
715
	public function configure() {
716
		$config = new Config();
717
718
		foreach (
719
			array(
720
				'connection',
721
				'sync',
722
				'tracking',
723
				'tos',
724
			)
725
			as $feature
726
		) {
727
			$config->ensure( $feature );
728
		}
729
730
		if ( is_admin() ) {
731
			$config->ensure( 'jitm' );
732
		}
733
734
		$this->connection_manager = new Connection_Manager();
735
736
		/*
737
		 * Load things that should only be in Network Admin.
738
		 *
739
		 * For now blow away everything else until a more full
740
		 * understanding of what is needed at the network level is
741
		 * available
742
		 */
743
		if ( is_multisite() ) {
744
			$network = Jetpack_Network::init();
745
			$network->set_connection( $this->connection_manager );
746
		}
747
748
		if ( $this->connection_manager->is_active() ) {
749
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
750
751
			Jetpack_Heartbeat::init();
752
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
753
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
754
				Jetpack_Search_Performance_Logger::init();
755
			}
756
		}
757
758
		// Initialize remote file upload request handlers.
759
		$this->add_remote_request_handlers();
760
761
		/*
762
		 * Enable enhanced handling of previewing sites in Calypso
763
		 */
764
		if ( self::is_active() ) {
765
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
766
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
767
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
768
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
769
		}
770
771
		/*
772
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
773
		 * We should make sure to only do this for front end links.
774
		 */
775
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
776
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
777
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
778
779
			/*
780
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
781
			 * so they point moderation links on emails to Calypso.
782
			 */
783
			jetpack_require_lib( 'functions.wp-notify' );
784
		}
785
786
	}
787
788
	/**
789
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
790
	 * initialization code.
791
	 *
792
	 * @action plugins_loaded
793
	 */
794
	public function late_initialization() {
795
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
796
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
797
798
		Partner::init();
799
800
		/**
801
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
802
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
803
		 *
804
		 * @since 8.1.0
805
		 *
806
		 * @param Jetpack $jetpack the main plugin class object.
807
		 */
808
		do_action( 'jetpack_loaded', $this );
809
810
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
811
	}
812
813
	/**
814
	 * Sets up the XMLRPC request handlers.
815
	 *
816
	 * @deprecated since 7.7.0
817
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
818
	 *
819
	 * @param Array                 $request_params Incoming request parameters.
820
	 * @param Boolean               $is_active      Whether the connection is currently active.
821
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
822
	 * @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...
823
	 */
824
	public function setup_xmlrpc_handlers(
825
		$request_params,
826
		$is_active,
827
		$is_signed,
828
		Jetpack_XMLRPC_Server $xmlrpc_server = null
829
	) {
830
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
831
		return $this->connection_manager->setup_xmlrpc_handlers(
832
			$request_params,
833
			$is_active,
834
			$is_signed,
835
			$xmlrpc_server
836
		);
837
	}
838
839
	/**
840
	 * Initialize REST API registration connector.
841
	 *
842
	 * @deprecated since 7.7.0
843
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
844
	 */
845
	public function initialize_rest_api_registration_connector() {
846
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
847
		$this->connection_manager->initialize_rest_api_registration_connector();
848
	}
849
850
	/**
851
	 * This is ported over from the manage module, which has been deprecated and baked in here.
852
	 *
853
	 * @param $domains
854
	 */
855
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
856
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
857
	}
858
859
	/**
860
	 * Return $domains, with 'wordpress.com' appended.
861
	 * This is ported over from the manage module, which has been deprecated and baked in here.
862
	 *
863
	 * @param $domains
864
	 * @return array
865
	 */
866
	function allow_wpcom_domain( $domains ) {
867
		if ( empty( $domains ) ) {
868
			$domains = array();
869
		}
870
		$domains[] = 'wordpress.com';
871
		return array_unique( $domains );
872
	}
873
874
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
875
		$post = get_post( $post_id );
876
877
		if ( empty( $post ) ) {
878
			return $default_url;
879
		}
880
881
		$post_type = $post->post_type;
882
883
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
884
		// https://en.support.wordpress.com/custom-post-types/
885
		$allowed_post_types = array(
886
			'post'                => 'post',
887
			'page'                => 'page',
888
			'jetpack-portfolio'   => 'edit/jetpack-portfolio',
889
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
890
		);
891
892
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
893
			return $default_url;
894
		}
895
896
		$path_prefix = $allowed_post_types[ $post_type ];
897
898
		$site_slug = self::build_raw_urls( get_home_url() );
899
900
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
901
	}
902
903
	function point_edit_comment_links_to_calypso( $url ) {
904
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
905
		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...
906
		return esc_url(
907
			sprintf(
908
				'https://wordpress.com/comment/%s/%d',
909
				self::build_raw_urls( get_home_url() ),
910
				$query_args['amp;c']
911
			)
912
		);
913
	}
914
915
	function jetpack_track_last_sync_callback( $params ) {
916
		/**
917
		 * Filter to turn off jitm caching
918
		 *
919
		 * @since 5.4.0
920
		 *
921
		 * @param bool false Whether to cache just in time messages
922
		 */
923
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
924
			return $params;
925
		}
926
927
		if ( is_array( $params ) && isset( $params[0] ) ) {
928
			$option = $params[0];
929
			if ( 'active_plugins' === $option ) {
930
				// use the cache if we can, but not terribly important if it gets evicted
931
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
932
			}
933
		}
934
935
		return $params;
936
	}
937
938
	function jetpack_connection_banner_callback() {
939
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
940
941
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
942
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
943
			wp_send_json_success();
944
		}
945
946
		wp_die();
947
	}
948
949
	/**
950
	 * Removes all XML-RPC methods that are not `jetpack.*`.
951
	 * Only used in our alternate XML-RPC endpoint, where we want to
952
	 * ensure that Core and other plugins' methods are not exposed.
953
	 *
954
	 * @deprecated since 7.7.0
955
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
956
	 *
957
	 * @param array $methods A list of registered WordPress XMLRPC methods.
958
	 * @return array Filtered $methods
959
	 */
960
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
961
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
962
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
963
	}
964
965
	/**
966
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
967
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
968
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
969
	 * which is accessible via a different URI. Most of the below is copied directly
970
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
971
	 *
972
	 * @deprecated since 7.7.0
973
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
974
	 */
975
	public function alternate_xmlrpc() {
976
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
977
		$this->connection_manager->alternate_xmlrpc();
978
	}
979
980
	/**
981
	 * The callback for the JITM ajax requests.
982
	 *
983
	 * @deprecated since 7.9.0
984
	 */
985
	function jetpack_jitm_ajax_callback() {
986
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
987
	}
988
989
	/**
990
	 * If there are any stats that need to be pushed, but haven't been, push them now.
991
	 */
992
	function push_stats() {
993
		if ( ! empty( $this->stats ) ) {
994
			$this->do_stats( 'server_side' );
995
		}
996
	}
997
998
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
999
		$is_development_mode = ( new Status() )->is_development_mode();
1000
		switch ( $cap ) {
1001
			case 'jetpack_connect':
1002
			case 'jetpack_reconnect':
1003
				if ( $is_development_mode ) {
1004
					$caps = array( 'do_not_allow' );
1005
					break;
1006
				}
1007
				/**
1008
				 * Pass through. If it's not development mode, these should match disconnect.
1009
				 * Let users disconnect if it's development mode, just in case things glitch.
1010
				 */
1011
			case 'jetpack_disconnect':
1012
				/**
1013
				 * In multisite, can individual site admins manage their own connection?
1014
				 *
1015
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1016
				 */
1017
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1018
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1019
						/**
1020
						 * We need to update the option name -- it's terribly unclear which
1021
						 * direction the override goes.
1022
						 *
1023
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1024
						 */
1025
						$caps = array( 'do_not_allow' );
1026
						break;
1027
					}
1028
				}
1029
1030
				$caps = array( 'manage_options' );
1031
				break;
1032
			case 'jetpack_manage_modules':
1033
			case 'jetpack_activate_modules':
1034
			case 'jetpack_deactivate_modules':
1035
				$caps = array( 'manage_options' );
1036
				break;
1037
			case 'jetpack_configure_modules':
1038
				$caps = array( 'manage_options' );
1039
				break;
1040
			case 'jetpack_manage_autoupdates':
1041
				$caps = array(
1042
					'manage_options',
1043
					'update_plugins',
1044
				);
1045
				break;
1046
			case 'jetpack_network_admin_page':
1047
			case 'jetpack_network_settings_page':
1048
				$caps = array( 'manage_network_plugins' );
1049
				break;
1050
			case 'jetpack_network_sites_page':
1051
				$caps = array( 'manage_sites' );
1052
				break;
1053
			case 'jetpack_admin_page':
1054
				if ( $is_development_mode ) {
1055
					$caps = array( 'manage_options' );
1056
					break;
1057
				} else {
1058
					$caps = array( 'read' );
1059
				}
1060
				break;
1061
			case 'jetpack_connect_user':
1062
				if ( $is_development_mode ) {
1063
					$caps = array( 'do_not_allow' );
1064
					break;
1065
				}
1066
				$caps = array( 'read' );
1067
				break;
1068
		}
1069
		return $caps;
1070
	}
1071
1072
	/**
1073
	 * Require a Jetpack authentication.
1074
	 *
1075
	 * @deprecated since 7.7.0
1076
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1077
	 */
1078
	public function require_jetpack_authentication() {
1079
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1080
		$this->connection_manager->require_jetpack_authentication();
1081
	}
1082
1083
	/**
1084
	 * Load language files
1085
	 *
1086
	 * @action plugins_loaded
1087
	 */
1088
	public static function plugin_textdomain() {
1089
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1090
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1091
	}
1092
1093
	/**
1094
	 * Register assets for use in various modules and the Jetpack admin page.
1095
	 *
1096
	 * @uses wp_script_is, wp_register_script, plugins_url
1097
	 * @action wp_loaded
1098
	 * @return null
1099
	 */
1100
	public function register_assets() {
1101
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1102
			wp_register_script(
1103
				'spin',
1104
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1105
				false,
1106
				'1.3'
1107
			);
1108
		}
1109
1110 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1111
			wp_register_script(
1112
				'jquery.spin',
1113
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1114
				array( 'jquery', 'spin' ),
1115
				'1.3'
1116
			);
1117
		}
1118
1119 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1120
			wp_register_script(
1121
				'jetpack-gallery-settings',
1122
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1123
				array( 'media-views' ),
1124
				'20121225'
1125
			);
1126
		}
1127
1128 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1129
			wp_register_script(
1130
				'jetpack-twitter-timeline',
1131
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1132
				array( 'jquery' ),
1133
				'4.0.0',
1134
				true
1135
			);
1136
		}
1137
1138
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1139
			wp_register_script(
1140
				'jetpack-facebook-embed',
1141
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1142
				array( 'jquery' ),
1143
				null,
1144
				true
1145
			);
1146
1147
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1148
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1149
			if ( ! is_numeric( $fb_app_id ) ) {
1150
				$fb_app_id = '';
1151
			}
1152
			wp_localize_script(
1153
				'jetpack-facebook-embed',
1154
				'jpfbembed',
1155
				array(
1156
					'appid'  => $fb_app_id,
1157
					'locale' => $this->get_locale(),
1158
				)
1159
			);
1160
		}
1161
1162
		/**
1163
		 * As jetpack_register_genericons is by default fired off a hook,
1164
		 * the hook may have already fired by this point.
1165
		 * So, let's just trigger it manually.
1166
		 */
1167
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1168
		jetpack_register_genericons();
1169
1170
		/**
1171
		 * Register the social logos
1172
		 */
1173
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1174
		jetpack_register_social_logos();
1175
1176 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1177
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1178
		}
1179
	}
1180
1181
	/**
1182
	 * Guess locale from language code.
1183
	 *
1184
	 * @param string $lang Language code.
1185
	 * @return string|bool
1186
	 */
1187 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1188
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1189
			return 'en_US';
1190
		}
1191
1192
		if ( ! class_exists( 'GP_Locales' ) ) {
1193
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1194
				return false;
1195
			}
1196
1197
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1198
		}
1199
1200
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1201
			// WP.com: get_locale() returns 'it'
1202
			$locale = GP_Locales::by_slug( $lang );
1203
		} else {
1204
			// Jetpack: get_locale() returns 'it_IT';
1205
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1206
		}
1207
1208
		if ( ! $locale ) {
1209
			return false;
1210
		}
1211
1212
		if ( empty( $locale->facebook_locale ) ) {
1213
			if ( empty( $locale->wp_locale ) ) {
1214
				return false;
1215
			} else {
1216
				// Facebook SDK is smart enough to fall back to en_US if a
1217
				// locale isn't supported. Since supported Facebook locales
1218
				// can fall out of sync, we'll attempt to use the known
1219
				// wp_locale value and rely on said fallback.
1220
				return $locale->wp_locale;
1221
			}
1222
		}
1223
1224
		return $locale->facebook_locale;
1225
	}
1226
1227
	/**
1228
	 * Get the locale.
1229
	 *
1230
	 * @return string|bool
1231
	 */
1232
	function get_locale() {
1233
		$locale = $this->guess_locale_from_lang( get_locale() );
1234
1235
		if ( ! $locale ) {
1236
			$locale = 'en_US';
1237
		}
1238
1239
		return $locale;
1240
	}
1241
1242
	/**
1243
	 * Return the network_site_url so that .com knows what network this site is a part of.
1244
	 *
1245
	 * @param  bool $option
1246
	 * @return string
1247
	 */
1248
	public function jetpack_main_network_site_option( $option ) {
1249
		return network_site_url();
1250
	}
1251
	/**
1252
	 * Network Name.
1253
	 */
1254
	static function network_name( $option = null ) {
1255
		global $current_site;
1256
		return $current_site->site_name;
1257
	}
1258
	/**
1259
	 * Does the network allow new user and site registrations.
1260
	 *
1261
	 * @return string
1262
	 */
1263
	static function network_allow_new_registrations( $option = null ) {
1264
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1265
	}
1266
	/**
1267
	 * Does the network allow admins to add new users.
1268
	 *
1269
	 * @return boolian
1270
	 */
1271
	static function network_add_new_users( $option = null ) {
1272
		return (bool) get_site_option( 'add_new_users' );
1273
	}
1274
	/**
1275
	 * File upload psace left per site in MB.
1276
	 *  -1 means NO LIMIT.
1277
	 *
1278
	 * @return number
1279
	 */
1280
	static function network_site_upload_space( $option = null ) {
1281
		// value in MB
1282
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1283
	}
1284
1285
	/**
1286
	 * Network allowed file types.
1287
	 *
1288
	 * @return string
1289
	 */
1290
	static function network_upload_file_types( $option = null ) {
1291
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1292
	}
1293
1294
	/**
1295
	 * Maximum file upload size set by the network.
1296
	 *
1297
	 * @return number
1298
	 */
1299
	static function network_max_upload_file_size( $option = null ) {
1300
		// value in KB
1301
		return get_site_option( 'fileupload_maxk', 300 );
1302
	}
1303
1304
	/**
1305
	 * Lets us know if a site allows admins to manage the network.
1306
	 *
1307
	 * @return array
1308
	 */
1309
	static function network_enable_administration_menus( $option = null ) {
1310
		return get_site_option( 'menu_items' );
1311
	}
1312
1313
	/**
1314
	 * If a user has been promoted to or demoted from admin, we need to clear the
1315
	 * jetpack_other_linked_admins transient.
1316
	 *
1317
	 * @since 4.3.2
1318
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1319
	 *
1320
	 * @param int    $user_id   The user ID whose role changed.
1321
	 * @param string $role      The new role.
1322
	 * @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...
1323
	 */
1324
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1325
		if ( 'administrator' == $role
1326
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1327
			|| is_null( $old_roles )
1328
		) {
1329
			delete_transient( 'jetpack_other_linked_admins' );
1330
		}
1331
	}
1332
1333
	/**
1334
	 * Checks to see if there are any other users available to become primary
1335
	 * Users must both:
1336
	 * - Be linked to wpcom
1337
	 * - Be an admin
1338
	 *
1339
	 * @return mixed False if no other users are linked, Int if there are.
1340
	 */
1341
	static function get_other_linked_admins() {
1342
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1343
1344
		if ( false === $other_linked_users ) {
1345
			$admins = get_users( array( 'role' => 'administrator' ) );
1346
			if ( count( $admins ) > 1 ) {
1347
				$available = array();
1348
				foreach ( $admins as $admin ) {
1349
					if ( self::is_user_connected( $admin->ID ) ) {
1350
						$available[] = $admin->ID;
1351
					}
1352
				}
1353
1354
				$count_connected_admins = count( $available );
1355
				if ( count( $available ) > 1 ) {
1356
					$other_linked_users = $count_connected_admins;
1357
				} else {
1358
					$other_linked_users = 0;
1359
				}
1360
			} else {
1361
				$other_linked_users = 0;
1362
			}
1363
1364
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1365
		}
1366
1367
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1368
	}
1369
1370
	/**
1371
	 * Return whether we are dealing with a multi network setup or not.
1372
	 * The reason we are type casting this is because we want to avoid the situation where
1373
	 * the result is false since when is_main_network_option return false it cases
1374
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1375
	 * database which could be set to anything as opposed to what this function returns.
1376
	 *
1377
	 * @param  bool $option
1378
	 *
1379
	 * @return boolean
1380
	 */
1381
	public function is_main_network_option( $option ) {
1382
		// return '1' or ''
1383
		return (string) (bool) self::is_multi_network();
1384
	}
1385
1386
	/**
1387
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1388
	 *
1389
	 * @param  string $option
1390
	 * @return boolean
1391
	 */
1392
	public function is_multisite( $option ) {
1393
		return (string) (bool) is_multisite();
1394
	}
1395
1396
	/**
1397
	 * Implemented since there is no core is multi network function
1398
	 * Right now there is no way to tell if we which network is the dominant network on the system
1399
	 *
1400
	 * @since  3.3
1401
	 * @return boolean
1402
	 */
1403 View Code Duplication
	public static function is_multi_network() {
1404
		global  $wpdb;
1405
1406
		// if we don't have a multi site setup no need to do any more
1407
		if ( ! is_multisite() ) {
1408
			return false;
1409
		}
1410
1411
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1412
		if ( $num_sites > 1 ) {
1413
			return true;
1414
		} else {
1415
			return false;
1416
		}
1417
	}
1418
1419
	/**
1420
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1421
	 *
1422
	 * @return null
1423
	 */
1424
	function update_jetpack_main_network_site_option() {
1425
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1426
	}
1427
	/**
1428
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1429
	 */
1430
	function update_jetpack_network_settings() {
1431
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1432
		// Only sync this info for the main network site.
1433
	}
1434
1435
	/**
1436
	 * Get back if the current site is single user site.
1437
	 *
1438
	 * @return bool
1439
	 */
1440 View Code Duplication
	public static function is_single_user_site() {
1441
		global $wpdb;
1442
1443
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1444
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1445
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1446
		}
1447
		return 1 === (int) $some_users;
1448
	}
1449
1450
	/**
1451
	 * Returns true if the site has file write access false otherwise.
1452
	 *
1453
	 * @return string ( '1' | '0' )
1454
	 **/
1455
	public static function file_system_write_access() {
1456
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1457
			require_once ABSPATH . 'wp-admin/includes/file.php';
1458
		}
1459
1460
		require_once ABSPATH . 'wp-admin/includes/template.php';
1461
1462
		$filesystem_method = get_filesystem_method();
1463
		if ( $filesystem_method === 'direct' ) {
1464
			return 1;
1465
		}
1466
1467
		ob_start();
1468
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1469
		ob_end_clean();
1470
		if ( $filesystem_credentials_are_stored ) {
1471
			return 1;
1472
		}
1473
		return 0;
1474
	}
1475
1476
	/**
1477
	 * Finds out if a site is using a version control system.
1478
	 *
1479
	 * @return string ( '1' | '0' )
1480
	 **/
1481
	public static function is_version_controlled() {
1482
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1483
		return (string) (int) Functions::is_version_controlled();
1484
	}
1485
1486
	/**
1487
	 * Determines whether the current theme supports featured images or not.
1488
	 *
1489
	 * @return string ( '1' | '0' )
1490
	 */
1491
	public static function featured_images_enabled() {
1492
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1493
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1494
	}
1495
1496
	/**
1497
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1498
	 *
1499
	 * @deprecated 4.7 use get_avatar_url instead.
1500
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1501
	 * @param int               $size Size of the avatar image
1502
	 * @param string            $default URL to a default image to use if no avatar is available
1503
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1504
	 *
1505
	 * @return array
1506
	 */
1507
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1508
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1509
		return get_avatar_url(
1510
			$id_or_email,
1511
			array(
1512
				'size'          => $size,
1513
				'default'       => $default,
1514
				'force_default' => $force_display,
1515
			)
1516
		);
1517
	}
1518
1519
	/**
1520
	 * jetpack_updates is saved in the following schema:
1521
	 *
1522
	 * array (
1523
	 *      'plugins'                       => (int) Number of plugin updates available.
1524
	 *      'themes'                        => (int) Number of theme updates available.
1525
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1526
	 *      'translations'                  => (int) Number of translation updates available.
1527
	 *      'total'                         => (int) Total of all available updates.
1528
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1529
	 * )
1530
	 *
1531
	 * @return array
1532
	 */
1533
	public static function get_updates() {
1534
		$update_data = wp_get_update_data();
1535
1536
		// Stores the individual update counts as well as the total count.
1537
		if ( isset( $update_data['counts'] ) ) {
1538
			$updates = $update_data['counts'];
1539
		}
1540
1541
		// If we need to update WordPress core, let's find the latest version number.
1542 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1543
			$cur = get_preferred_from_update_core();
1544
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1545
				$updates['wp_update_version'] = $cur->current;
1546
			}
1547
		}
1548
		return isset( $updates ) ? $updates : array();
1549
	}
1550
1551
	public static function get_update_details() {
1552
		$update_details = array(
1553
			'update_core'    => get_site_transient( 'update_core' ),
1554
			'update_plugins' => get_site_transient( 'update_plugins' ),
1555
			'update_themes'  => get_site_transient( 'update_themes' ),
1556
		);
1557
		return $update_details;
1558
	}
1559
1560
	public static function refresh_update_data() {
1561
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1562
1563
	}
1564
1565
	public static function refresh_theme_data() {
1566
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1567
	}
1568
1569
	/**
1570
	 * Is Jetpack active?
1571
	 */
1572
	public static function is_active() {
1573
		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...
1574
	}
1575
1576
	/**
1577
	 * Make an API call to WordPress.com for plan status
1578
	 *
1579
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1580
	 *
1581
	 * @return bool True if plan is updated, false if no update
1582
	 */
1583
	public static function refresh_active_plan_from_wpcom() {
1584
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1585
		return Jetpack_Plan::refresh_from_wpcom();
1586
	}
1587
1588
	/**
1589
	 * Get the plan that this Jetpack site is currently using
1590
	 *
1591
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1592
	 * @return array Active Jetpack plan details.
1593
	 */
1594
	public static function get_active_plan() {
1595
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1596
		return Jetpack_Plan::get();
1597
	}
1598
1599
	/**
1600
	 * Determine whether the active plan supports a particular feature
1601
	 *
1602
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1603
	 * @return bool True if plan supports feature, false if not.
1604
	 */
1605
	public static function active_plan_supports( $feature ) {
1606
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1607
		return Jetpack_Plan::supports( $feature );
1608
	}
1609
1610
	/**
1611
	 * Deprecated: Is Jetpack in development (offline) mode?
1612
	 *
1613
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1614
	 * and themes still use it, and we do not want to flood them with notices.
1615
	 *
1616
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1617
	 *
1618
	 * @deprecated since 8.0.
1619
	 */
1620
	public static function is_development_mode() {
1621
		return ( new Status() )->is_development_mode();
1622
	}
1623
1624
	/**
1625
	 * Whether the site is currently onboarding or not.
1626
	 * A site is considered as being onboarded if it currently has an onboarding token.
1627
	 *
1628
	 * @since 5.8
1629
	 *
1630
	 * @access public
1631
	 * @static
1632
	 *
1633
	 * @return bool True if the site is currently onboarding, false otherwise
1634
	 */
1635
	public static function is_onboarding() {
1636
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1637
	}
1638
1639
	/**
1640
	 * Determines reason for Jetpack development mode.
1641
	 */
1642
	public static function development_mode_trigger_text() {
1643
		if ( ! ( new Status() )->is_development_mode() ) {
1644
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1645
		}
1646
1647
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1648
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1649
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1650
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1651
		} else {
1652
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1653
		}
1654
1655
		return $notice;
1656
1657
	}
1658
	/**
1659
	 * Get Jetpack development mode notice text and notice class.
1660
	 *
1661
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1662
	 */
1663
	public static function show_development_mode_notice() {
1664 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1665
			$notice = sprintf(
1666
				/* translators: %s is a URL */
1667
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1668
				'https://jetpack.com/support/development-mode/'
1669
			);
1670
1671
			$notice .= ' ' . self::development_mode_trigger_text();
1672
1673
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1674
		}
1675
1676
		// Throw up a notice if using a development version and as for feedback.
1677
		if ( self::is_development_version() ) {
1678
			/* translators: %s is a URL */
1679
			$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/' );
1680
1681
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1682
		}
1683
		// Throw up a notice if using staging mode
1684
		if ( ( new Status() )->is_staging_site() ) {
1685
			/* translators: %s is a URL */
1686
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1687
1688
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1689
		}
1690
	}
1691
1692
	/**
1693
	 * Whether Jetpack's version maps to a public release, or a development version.
1694
	 */
1695
	public static function is_development_version() {
1696
		/**
1697
		 * Allows filtering whether this is a development version of Jetpack.
1698
		 *
1699
		 * This filter is especially useful for tests.
1700
		 *
1701
		 * @since 4.3.0
1702
		 *
1703
		 * @param bool $development_version Is this a develoment version of Jetpack?
1704
		 */
1705
		return (bool) apply_filters(
1706
			'jetpack_development_version',
1707
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1708
		);
1709
	}
1710
1711
	/**
1712
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1713
	 */
1714
	public static function is_user_connected( $user_id = false ) {
1715
		return self::connection()->is_user_connected( $user_id );
1716
	}
1717
1718
	/**
1719
	 * Get the wpcom user data of the current|specified connected user.
1720
	 */
1721 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1722
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1723
		if ( ! $user_id ) {
1724
			$user_id = get_current_user_id();
1725
		}
1726
1727
		$transient_key = "jetpack_connected_user_data_$user_id";
1728
1729
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1730
			return $cached_user_data;
1731
		}
1732
1733
		$xml = new Jetpack_IXR_Client(
1734
			array(
1735
				'user_id' => $user_id,
1736
			)
1737
		);
1738
		$xml->query( 'wpcom.getUser' );
1739
		if ( ! $xml->isError() ) {
1740
			$user_data = $xml->getResponse();
1741
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1742
			return $user_data;
1743
		}
1744
1745
		return false;
1746
	}
1747
1748
	/**
1749
	 * Get the wpcom email of the current|specified connected user.
1750
	 */
1751 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1752
		if ( ! $user_id ) {
1753
			$user_id = get_current_user_id();
1754
		}
1755
1756
		$xml = new Jetpack_IXR_Client(
1757
			array(
1758
				'user_id' => $user_id,
1759
			)
1760
		);
1761
		$xml->query( 'wpcom.getUserEmail' );
1762
		if ( ! $xml->isError() ) {
1763
			return $xml->getResponse();
1764
		}
1765
		return false;
1766
	}
1767
1768
	/**
1769
	 * Get the wpcom email of the master user.
1770
	 */
1771
	public static function get_master_user_email() {
1772
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1773
		if ( $master_user_id ) {
1774
			return self::get_connected_user_email( $master_user_id );
1775
		}
1776
		return '';
1777
	}
1778
1779
	/**
1780
	 * Whether the current user is the connection owner.
1781
	 *
1782
	 * @deprecated since 7.7
1783
	 *
1784
	 * @return bool Whether the current user is the connection owner.
1785
	 */
1786
	public function current_user_is_connection_owner() {
1787
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1788
		return self::connection()->is_connection_owner();
1789
	}
1790
1791
	/**
1792
	 * Gets current user IP address.
1793
	 *
1794
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1795
	 *
1796
	 * @return string                  Current user IP address.
1797
	 */
1798
	public static function current_user_ip( $check_all_headers = false ) {
1799
		if ( $check_all_headers ) {
1800
			foreach ( array(
1801
				'HTTP_CF_CONNECTING_IP',
1802
				'HTTP_CLIENT_IP',
1803
				'HTTP_X_FORWARDED_FOR',
1804
				'HTTP_X_FORWARDED',
1805
				'HTTP_X_CLUSTER_CLIENT_IP',
1806
				'HTTP_FORWARDED_FOR',
1807
				'HTTP_FORWARDED',
1808
				'HTTP_VIA',
1809
			) as $key ) {
1810
				if ( ! empty( $_SERVER[ $key ] ) ) {
1811
					return $_SERVER[ $key ];
1812
				}
1813
			}
1814
		}
1815
1816
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1817
	}
1818
1819
	/**
1820
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1821
	 */
1822
	function extra_oembed_providers() {
1823
		// Cloudup: https://dev.cloudup.com/#oembed
1824
		wp_oembed_add_provider( 'https://cloudup.com/*', 'https://cloudup.com/oembed' );
1825
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1826
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1827
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1828
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1829
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1830
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1831
	}
1832
1833
	/**
1834
	 * Synchronize connected user role changes
1835
	 */
1836
	function user_role_change( $user_id ) {
1837
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1838
		Users::user_role_change( $user_id );
1839
	}
1840
1841
	/**
1842
	 * Loads the currently active modules.
1843
	 */
1844
	public static function load_modules() {
1845
		$is_development_mode = ( new Status() )->is_development_mode();
1846
		if (
1847
			! self::is_active()
1848
			&& ! $is_development_mode
1849
			&& ! self::is_onboarding()
1850
			&& (
1851
				! is_multisite()
1852
				|| ! get_site_option( 'jetpack_protect_active' )
1853
			)
1854
		) {
1855
			return;
1856
		}
1857
1858
		$version = Jetpack_Options::get_option( 'version' );
1859 View Code Duplication
		if ( ! $version ) {
1860
			$version = $old_version = JETPACK__VERSION . ':' . time();
1861
			/** This action is documented in class.jetpack.php */
1862
			do_action( 'updating_jetpack_version', $version, false );
1863
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1864
		}
1865
		list( $version ) = explode( ':', $version );
1866
1867
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1868
1869
		$modules_data = array();
1870
1871
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1872
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1873
			$updated_modules = array();
1874
			foreach ( $modules as $module ) {
1875
				$modules_data[ $module ] = self::get_module( $module );
1876
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1877
					continue;
1878
				}
1879
1880
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1881
					continue;
1882
				}
1883
1884
				$updated_modules[] = $module;
1885
			}
1886
1887
			$modules = array_diff( $modules, $updated_modules );
1888
		}
1889
1890
		foreach ( $modules as $index => $module ) {
1891
			// If we're in dev mode, disable modules requiring a connection
1892
			if ( $is_development_mode ) {
1893
				// Prime the pump if we need to
1894
				if ( empty( $modules_data[ $module ] ) ) {
1895
					$modules_data[ $module ] = self::get_module( $module );
1896
				}
1897
				// If the module requires a connection, but we're in local mode, don't include it.
1898
				if ( $modules_data[ $module ]['requires_connection'] ) {
1899
					continue;
1900
				}
1901
			}
1902
1903
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1904
				continue;
1905
			}
1906
1907
			if ( ! include_once self::get_module_path( $module ) ) {
1908
				unset( $modules[ $index ] );
1909
				self::update_active_modules( array_values( $modules ) );
1910
				continue;
1911
			}
1912
1913
			/**
1914
			 * Fires when a specific module is loaded.
1915
			 * The dynamic part of the hook, $module, is the module slug.
1916
			 *
1917
			 * @since 1.1.0
1918
			 */
1919
			do_action( 'jetpack_module_loaded_' . $module );
1920
		}
1921
1922
		/**
1923
		 * Fires when all the modules are loaded.
1924
		 *
1925
		 * @since 1.1.0
1926
		 */
1927
		do_action( 'jetpack_modules_loaded' );
1928
1929
		// 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.
1930
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1931
	}
1932
1933
	/**
1934
	 * Check if Jetpack's REST API compat file should be included
1935
	 *
1936
	 * @action plugins_loaded
1937
	 * @return null
1938
	 */
1939
	public function check_rest_api_compat() {
1940
		/**
1941
		 * Filters the list of REST API compat files to be included.
1942
		 *
1943
		 * @since 2.2.5
1944
		 *
1945
		 * @param array $args Array of REST API compat files to include.
1946
		 */
1947
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1948
1949
		if ( function_exists( 'bbpress' ) ) {
1950
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1951
		}
1952
1953
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1954
			require_once $_jetpack_rest_api_compat_include;
1955
		}
1956
	}
1957
1958
	/**
1959
	 * Gets all plugins currently active in values, regardless of whether they're
1960
	 * traditionally activated or network activated.
1961
	 *
1962
	 * @todo Store the result in core's object cache maybe?
1963
	 */
1964
	public static function get_active_plugins() {
1965
		$active_plugins = (array) get_option( 'active_plugins', array() );
1966
1967
		if ( is_multisite() ) {
1968
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1969
			// whereas active_plugins stores them in the values.
1970
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1971
			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...
1972
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1973
			}
1974
		}
1975
1976
		sort( $active_plugins );
1977
1978
		return array_unique( $active_plugins );
1979
	}
1980
1981
	/**
1982
	 * Gets and parses additional plugin data to send with the heartbeat data
1983
	 *
1984
	 * @since 3.8.1
1985
	 *
1986
	 * @return array Array of plugin data
1987
	 */
1988
	public static function get_parsed_plugin_data() {
1989
		if ( ! function_exists( 'get_plugins' ) ) {
1990
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
1991
		}
1992
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1993
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1994
		$active_plugins = self::get_active_plugins();
1995
1996
		$plugins = array();
1997
		foreach ( $all_plugins as $path => $plugin_data ) {
1998
			$plugins[ $path ] = array(
1999
				'is_active' => in_array( $path, $active_plugins ),
2000
				'file'      => $path,
2001
				'name'      => $plugin_data['Name'],
2002
				'version'   => $plugin_data['Version'],
2003
				'author'    => $plugin_data['Author'],
2004
			);
2005
		}
2006
2007
		return $plugins;
2008
	}
2009
2010
	/**
2011
	 * Gets and parses theme data to send with the heartbeat data
2012
	 *
2013
	 * @since 3.8.1
2014
	 *
2015
	 * @return array Array of theme data
2016
	 */
2017
	public static function get_parsed_theme_data() {
2018
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2019
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2020
2021
		$themes = array();
2022
		foreach ( $all_themes as $slug => $theme_data ) {
2023
			$theme_headers = array();
2024
			foreach ( $header_keys as $header_key ) {
2025
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2026
			}
2027
2028
			$themes[ $slug ] = array(
2029
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2030
				'slug'            => $slug,
2031
				'theme_root'      => $theme_data->get_theme_root_uri(),
2032
				'parent'          => $theme_data->parent(),
2033
				'headers'         => $theme_headers,
2034
			);
2035
		}
2036
2037
		return $themes;
2038
	}
2039
2040
	/**
2041
	 * Checks whether a specific plugin is active.
2042
	 *
2043
	 * We don't want to store these in a static variable, in case
2044
	 * there are switch_to_blog() calls involved.
2045
	 */
2046
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2047
		return in_array( $plugin, self::get_active_plugins() );
2048
	}
2049
2050
	/**
2051
	 * Check if Jetpack's Open Graph tags should be used.
2052
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2053
	 *
2054
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2055
	 * @action plugins_loaded
2056
	 * @return null
2057
	 */
2058
	public function check_open_graph() {
2059
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2060
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2061
		}
2062
2063
		$active_plugins = self::get_active_plugins();
2064
2065
		if ( ! empty( $active_plugins ) ) {
2066
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2067
				if ( in_array( $plugin, $active_plugins ) ) {
2068
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2069
					break;
2070
				}
2071
			}
2072
		}
2073
2074
		/**
2075
		 * Allow the addition of Open Graph Meta Tags to all pages.
2076
		 *
2077
		 * @since 2.0.3
2078
		 *
2079
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2080
		 */
2081
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2082
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2083
		}
2084
	}
2085
2086
	/**
2087
	 * Check if Jetpack's Twitter tags should be used.
2088
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2089
	 *
2090
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2091
	 * @action plugins_loaded
2092
	 * @return null
2093
	 */
2094
	public function check_twitter_tags() {
2095
2096
		$active_plugins = self::get_active_plugins();
2097
2098
		if ( ! empty( $active_plugins ) ) {
2099
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2100
				if ( in_array( $plugin, $active_plugins ) ) {
2101
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2102
					break;
2103
				}
2104
			}
2105
		}
2106
2107
		/**
2108
		 * Allow Twitter Card Meta tags to be disabled.
2109
		 *
2110
		 * @since 2.6.0
2111
		 *
2112
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2113
		 */
2114
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2115
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2116
		}
2117
	}
2118
2119
	/**
2120
	 * Allows plugins to submit security reports.
2121
	 *
2122
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2123
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2124
	 * @param array  $args         See definitions above
2125
	 */
2126
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2127
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2128
	}
2129
2130
	/* Jetpack Options API */
2131
2132
	public static function get_option_names( $type = 'compact' ) {
2133
		return Jetpack_Options::get_option_names( $type );
2134
	}
2135
2136
	/**
2137
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2138
	 *
2139
	 * @param string $name    Option name
2140
	 * @param mixed  $default (optional)
2141
	 */
2142
	public static function get_option( $name, $default = false ) {
2143
		return Jetpack_Options::get_option( $name, $default );
2144
	}
2145
2146
	/**
2147
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2148
	 *
2149
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2150
	 * @param string $name  Option name
2151
	 * @param mixed  $value Option value
2152
	 */
2153
	public static function update_option( $name, $value ) {
2154
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2155
		return Jetpack_Options::update_option( $name, $value );
2156
	}
2157
2158
	/**
2159
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2160
	 *
2161
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2162
	 * @param array $array array( option name => option value, ... )
2163
	 */
2164
	public static function update_options( $array ) {
2165
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2166
		return Jetpack_Options::update_options( $array );
2167
	}
2168
2169
	/**
2170
	 * Deletes the given option.  May be passed multiple option names as an array.
2171
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2172
	 *
2173
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2174
	 * @param string|array $names
2175
	 */
2176
	public static function delete_option( $names ) {
2177
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2178
		return Jetpack_Options::delete_option( $names );
2179
	}
2180
2181
	/**
2182
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2183
	 *
2184
	 * Enters a user token into the user_tokens option
2185
	 *
2186
	 * @param int    $user_id The user id.
2187
	 * @param string $token The user token.
2188
	 * @param bool   $is_master_user Whether the user is the master user.
2189
	 * @return bool
2190
	 */
2191
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2192
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2193
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2194
	}
2195
2196
	/**
2197
	 * Returns an array of all PHP files in the specified absolute path.
2198
	 * Equivalent to glob( "$absolute_path/*.php" ).
2199
	 *
2200
	 * @param string $absolute_path The absolute path of the directory to search.
2201
	 * @return array Array of absolute paths to the PHP files.
2202
	 */
2203
	public static function glob_php( $absolute_path ) {
2204
		if ( function_exists( 'glob' ) ) {
2205
			return glob( "$absolute_path/*.php" );
2206
		}
2207
2208
		$absolute_path = untrailingslashit( $absolute_path );
2209
		$files         = array();
2210
		if ( ! $dir = @opendir( $absolute_path ) ) {
2211
			return $files;
2212
		}
2213
2214
		while ( false !== $file = readdir( $dir ) ) {
2215
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2216
				continue;
2217
			}
2218
2219
			$file = "$absolute_path/$file";
2220
2221
			if ( ! is_file( $file ) ) {
2222
				continue;
2223
			}
2224
2225
			$files[] = $file;
2226
		}
2227
2228
		closedir( $dir );
2229
2230
		return $files;
2231
	}
2232
2233
	public static function activate_new_modules( $redirect = false ) {
2234
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2235
			return;
2236
		}
2237
2238
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2239 View Code Duplication
		if ( ! $jetpack_old_version ) {
2240
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2241
			/** This action is documented in class.jetpack.php */
2242
			do_action( 'updating_jetpack_version', $version, false );
2243
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2244
		}
2245
2246
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2247
2248
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2249
			return;
2250
		}
2251
2252
		$active_modules     = self::get_active_modules();
2253
		$reactivate_modules = array();
2254
		foreach ( $active_modules as $active_module ) {
2255
			$module = self::get_module( $active_module );
2256
			if ( ! isset( $module['changed'] ) ) {
2257
				continue;
2258
			}
2259
2260
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2261
				continue;
2262
			}
2263
2264
			$reactivate_modules[] = $active_module;
2265
			self::deactivate_module( $active_module );
2266
		}
2267
2268
		$new_version = JETPACK__VERSION . ':' . time();
2269
		/** This action is documented in class.jetpack.php */
2270
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2271
		Jetpack_Options::update_options(
2272
			array(
2273
				'version'     => $new_version,
2274
				'old_version' => $jetpack_old_version,
2275
			)
2276
		);
2277
2278
		self::state( 'message', 'modules_activated' );
2279
		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...
2280
2281
		if ( $redirect ) {
2282
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2283
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2284
				$page = $_GET['page'];
2285
			}
2286
2287
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2288
			exit;
2289
		}
2290
	}
2291
2292
	/**
2293
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2294
	 * Make sure to tuck away module "library" files in a sub-directory.
2295
	 */
2296
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2297
		static $modules = null;
2298
2299
		if ( ! isset( $modules ) ) {
2300
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2301
			// Use the cache if we're on the front-end and it's available...
2302
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2303
				$modules = $available_modules_option[ JETPACK__VERSION ];
2304
			} else {
2305
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2306
2307
				$modules = array();
2308
2309
				foreach ( $files as $file ) {
2310
					if ( ! $headers = self::get_module( $file ) ) {
2311
						continue;
2312
					}
2313
2314
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2315
				}
2316
2317
				Jetpack_Options::update_option(
2318
					'available_modules',
2319
					array(
2320
						JETPACK__VERSION => $modules,
2321
					)
2322
				);
2323
			}
2324
		}
2325
2326
		/**
2327
		 * Filters the array of modules available to be activated.
2328
		 *
2329
		 * @since 2.4.0
2330
		 *
2331
		 * @param array $modules Array of available modules.
2332
		 * @param string $min_version Minimum version number required to use modules.
2333
		 * @param string $max_version Maximum version number required to use modules.
2334
		 */
2335
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2336
2337
		if ( ! $min_version && ! $max_version ) {
2338
			return array_keys( $mods );
2339
		}
2340
2341
		$r = array();
2342
		foreach ( $mods as $slug => $introduced ) {
2343
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2344
				continue;
2345
			}
2346
2347
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2348
				continue;
2349
			}
2350
2351
			$r[] = $slug;
2352
		}
2353
2354
		return $r;
2355
	}
2356
2357
	/**
2358
	 * Default modules loaded on activation.
2359
	 */
2360
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2361
		$return = array();
2362
2363
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2364
			$module_data = self::get_module( $module );
2365
2366
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2367
				case 'yes':
2368
					$return[] = $module;
2369
					break;
2370
				case 'public':
2371
					if ( Jetpack_Options::get_option( 'public' ) ) {
2372
						$return[] = $module;
2373
					}
2374
					break;
2375
				case 'no':
2376
				default:
2377
					break;
2378
			}
2379
		}
2380
		/**
2381
		 * Filters the array of default modules.
2382
		 *
2383
		 * @since 2.5.0
2384
		 *
2385
		 * @param array $return Array of default modules.
2386
		 * @param string $min_version Minimum version number required to use modules.
2387
		 * @param string $max_version Maximum version number required to use modules.
2388
		 */
2389
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2390
	}
2391
2392
	/**
2393
	 * Checks activated modules during auto-activation to determine
2394
	 * if any of those modules are being deprecated.  If so, close
2395
	 * them out, and add any replacement modules.
2396
	 *
2397
	 * Runs at priority 99 by default.
2398
	 *
2399
	 * This is run late, so that it can still activate a module if
2400
	 * the new module is a replacement for another that the user
2401
	 * currently has active, even if something at the normal priority
2402
	 * would kibosh everything.
2403
	 *
2404
	 * @since 2.6
2405
	 * @uses jetpack_get_default_modules filter
2406
	 * @param array $modules
2407
	 * @return array
2408
	 */
2409
	function handle_deprecated_modules( $modules ) {
2410
		$deprecated_modules = array(
2411
			'debug'            => null,  // Closed out and moved to the debugger library.
2412
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2413
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2414
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2415
		);
2416
2417
		// Don't activate SSO if they never completed activating WPCC.
2418
		if ( self::is_module_active( 'wpcc' ) ) {
2419
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2420
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2421
				$deprecated_modules['wpcc'] = null;
2422
			}
2423
		}
2424
2425
		foreach ( $deprecated_modules as $module => $replacement ) {
2426
			if ( self::is_module_active( $module ) ) {
2427
				self::deactivate_module( $module );
2428
				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...
2429
					$modules[] = $replacement;
2430
				}
2431
			}
2432
		}
2433
2434
		return array_unique( $modules );
2435
	}
2436
2437
	/**
2438
	 * Checks activated plugins during auto-activation to determine
2439
	 * if any of those plugins are in the list with a corresponding module
2440
	 * that is not compatible with the plugin. The module will not be allowed
2441
	 * to auto-activate.
2442
	 *
2443
	 * @since 2.6
2444
	 * @uses jetpack_get_default_modules filter
2445
	 * @param array $modules
2446
	 * @return array
2447
	 */
2448
	function filter_default_modules( $modules ) {
2449
2450
		$active_plugins = self::get_active_plugins();
2451
2452
		if ( ! empty( $active_plugins ) ) {
2453
2454
			// For each module we'd like to auto-activate...
2455
			foreach ( $modules as $key => $module ) {
2456
				// If there are potential conflicts for it...
2457
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2458
					// For each potential conflict...
2459
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2460
						// If that conflicting plugin is active...
2461
						if ( in_array( $plugin, $active_plugins ) ) {
2462
							// Remove that item from being auto-activated.
2463
							unset( $modules[ $key ] );
2464
						}
2465
					}
2466
				}
2467
			}
2468
		}
2469
2470
		return $modules;
2471
	}
2472
2473
	/**
2474
	 * Extract a module's slug from its full path.
2475
	 */
2476
	public static function get_module_slug( $file ) {
2477
		return str_replace( '.php', '', basename( $file ) );
2478
	}
2479
2480
	/**
2481
	 * Generate a module's path from its slug.
2482
	 */
2483
	public static function get_module_path( $slug ) {
2484
		/**
2485
		 * Filters the path of a modules.
2486
		 *
2487
		 * @since 7.4.0
2488
		 *
2489
		 * @param array $return The absolute path to a module's root php file
2490
		 * @param string $slug The module slug
2491
		 */
2492
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2493
	}
2494
2495
	/**
2496
	 * Load module data from module file. Headers differ from WordPress
2497
	 * plugin headers to avoid them being identified as standalone
2498
	 * plugins on the WordPress plugins page.
2499
	 */
2500
	public static function get_module( $module ) {
2501
		$headers = array(
2502
			'name'                      => 'Module Name',
2503
			'description'               => 'Module Description',
2504
			'sort'                      => 'Sort Order',
2505
			'recommendation_order'      => 'Recommendation Order',
2506
			'introduced'                => 'First Introduced',
2507
			'changed'                   => 'Major Changes In',
2508
			'deactivate'                => 'Deactivate',
2509
			'free'                      => 'Free',
2510
			'requires_connection'       => 'Requires Connection',
2511
			'auto_activate'             => 'Auto Activate',
2512
			'module_tags'               => 'Module Tags',
2513
			'feature'                   => 'Feature',
2514
			'additional_search_queries' => 'Additional Search Queries',
2515
			'plan_classes'              => 'Plans',
2516
		);
2517
2518
		$file = self::get_module_path( self::get_module_slug( $module ) );
2519
2520
		$mod = self::get_file_data( $file, $headers );
2521
		if ( empty( $mod['name'] ) ) {
2522
			return false;
2523
		}
2524
2525
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2526
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2527
		$mod['deactivate']           = empty( $mod['deactivate'] );
2528
		$mod['free']                 = empty( $mod['free'] );
2529
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2530
2531
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2532
			$mod['auto_activate'] = 'No';
2533
		} else {
2534
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2535
		}
2536
2537
		if ( $mod['module_tags'] ) {
2538
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2539
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2540
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2541
		} else {
2542
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2543
		}
2544
2545 View Code Duplication
		if ( $mod['plan_classes'] ) {
2546
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2547
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2548
		} else {
2549
			$mod['plan_classes'] = array( 'free' );
2550
		}
2551
2552 View Code Duplication
		if ( $mod['feature'] ) {
2553
			$mod['feature'] = explode( ',', $mod['feature'] );
2554
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2555
		} else {
2556
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2557
		}
2558
2559
		/**
2560
		 * Filters the feature array on a module.
2561
		 *
2562
		 * This filter allows you to control where each module is filtered: Recommended,
2563
		 * and the default "Other" listing.
2564
		 *
2565
		 * @since 3.5.0
2566
		 *
2567
		 * @param array   $mod['feature'] The areas to feature this module:
2568
		 *     'Recommended' shows on the main Jetpack admin screen.
2569
		 *     'Other' should be the default if no other value is in the array.
2570
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2571
		 * @param array   $mod All the currently assembled module data.
2572
		 */
2573
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2574
2575
		/**
2576
		 * Filter the returned data about a module.
2577
		 *
2578
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2579
		 * so please be careful.
2580
		 *
2581
		 * @since 3.6.0
2582
		 *
2583
		 * @param array   $mod    The details of the requested module.
2584
		 * @param string  $module The slug of the module, e.g. sharedaddy
2585
		 * @param string  $file   The path to the module source file.
2586
		 */
2587
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2588
	}
2589
2590
	/**
2591
	 * Like core's get_file_data implementation, but caches the result.
2592
	 */
2593
	public static function get_file_data( $file, $headers ) {
2594
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2595
		$file_name = basename( $file );
2596
2597
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2598
2599
		$file_data_option = get_transient( $cache_key );
2600
2601
		if ( ! is_array( $file_data_option ) ) {
2602
			delete_transient( $cache_key );
2603
			$file_data_option = false;
2604
		}
2605
2606
		if ( false === $file_data_option ) {
2607
			$file_data_option = array();
2608
		}
2609
2610
		$key           = md5( $file_name . serialize( $headers ) );
2611
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2612
2613
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2614
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2615
			return $file_data_option[ $key ];
2616
		}
2617
2618
		$data = get_file_data( $file, $headers );
2619
2620
		$file_data_option[ $key ] = $data;
2621
2622
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2623
2624
		return $data;
2625
	}
2626
2627
2628
	/**
2629
	 * Return translated module tag.
2630
	 *
2631
	 * @param string $tag Tag as it appears in each module heading.
2632
	 *
2633
	 * @return mixed
2634
	 */
2635
	public static function translate_module_tag( $tag ) {
2636
		return jetpack_get_module_i18n_tag( $tag );
2637
	}
2638
2639
	/**
2640
	 * Get i18n strings as a JSON-encoded string
2641
	 *
2642
	 * @return string The locale as JSON
2643
	 */
2644
	public static function get_i18n_data_json() {
2645
2646
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2647
		// JSON files with the file they should be included for. This is an md5
2648
		// of '_inc/build/admin.js'.
2649
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2650
2651
		$i18n_json =
2652
				   JETPACK__PLUGIN_DIR
2653
				   . 'languages/json/jetpack-'
2654
				   . get_user_locale()
2655
				   . '-'
2656
				   . $path_md5
2657
				   . '.json';
2658
2659
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2660
			$locale_data = @file_get_contents( $i18n_json );
2661
			if ( $locale_data ) {
2662
				return $locale_data;
2663
			}
2664
		}
2665
2666
		// Return valid empty Jed locale
2667
		return '{ "locale_data": { "messages": { "": {} } } }';
2668
	}
2669
2670
	/**
2671
	 * Add locale data setup to wp-i18n
2672
	 *
2673
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2674
	 *
2675
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2676
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2677
	 *
2678
	 * This method provides a safe way to request the setup multiple times but add the script at
2679
	 * most once.
2680
	 *
2681
	 * @since 6.7.0
2682
	 *
2683
	 * @return void
2684
	 */
2685
	public static function setup_wp_i18n_locale_data() {
2686
		static $script_added = false;
2687
		if ( ! $script_added ) {
2688
			$script_added = true;
2689
			wp_add_inline_script(
2690
				'wp-i18n',
2691
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2692
			);
2693
		}
2694
	}
2695
2696
	/**
2697
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2698
	 *
2699
	 * @since 3.9.2
2700
	 *
2701
	 * @param array $modules
2702
	 *
2703
	 * @return string|void
2704
	 */
2705
	public static function get_translated_modules( $modules ) {
2706
		foreach ( $modules as $index => $module ) {
2707
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2708
			if ( isset( $module['name'] ) ) {
2709
				$modules[ $index ]['name'] = $i18n_module['name'];
2710
			}
2711
			if ( isset( $module['description'] ) ) {
2712
				$modules[ $index ]['description']       = $i18n_module['description'];
2713
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2714
			}
2715
		}
2716
		return $modules;
2717
	}
2718
2719
	/**
2720
	 * Get a list of activated modules as an array of module slugs.
2721
	 */
2722
	public static function get_active_modules() {
2723
		$active = Jetpack_Options::get_option( 'active_modules' );
2724
2725
		if ( ! is_array( $active ) ) {
2726
			$active = array();
2727
		}
2728
2729
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2730
			$active[] = 'vaultpress';
2731
		} else {
2732
			$active = array_diff( $active, array( 'vaultpress' ) );
2733
		}
2734
2735
		// If protect is active on the main site of a multisite, it should be active on all sites.
2736
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2737
			$active[] = 'protect';
2738
		}
2739
2740
		/**
2741
		 * Allow filtering of the active modules.
2742
		 *
2743
		 * Gives theme and plugin developers the power to alter the modules that
2744
		 * are activated on the fly.
2745
		 *
2746
		 * @since 5.8.0
2747
		 *
2748
		 * @param array $active Array of active module slugs.
2749
		 */
2750
		$active = apply_filters( 'jetpack_active_modules', $active );
2751
2752
		return array_unique( $active );
2753
	}
2754
2755
	/**
2756
	 * Check whether or not a Jetpack module is active.
2757
	 *
2758
	 * @param string $module The slug of a Jetpack module.
2759
	 * @return bool
2760
	 *
2761
	 * @static
2762
	 */
2763
	public static function is_module_active( $module ) {
2764
		return in_array( $module, self::get_active_modules() );
2765
	}
2766
2767
	public static function is_module( $module ) {
2768
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2769
	}
2770
2771
	/**
2772
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2773
	 *
2774
	 * @param bool $catch True to start catching, False to stop.
2775
	 *
2776
	 * @static
2777
	 */
2778
	public static function catch_errors( $catch ) {
2779
		static $display_errors, $error_reporting;
2780
2781
		if ( $catch ) {
2782
			$display_errors  = @ini_set( 'display_errors', 1 );
2783
			$error_reporting = @error_reporting( E_ALL );
2784
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2785
		} else {
2786
			@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...
2787
			@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...
2788
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2789
		}
2790
	}
2791
2792
	/**
2793
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2794
	 */
2795
	public static function catch_errors_on_shutdown() {
2796
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2797
	}
2798
2799
	/**
2800
	 * Rewrite any string to make paths easier to read.
2801
	 *
2802
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2803
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2804
	 *
2805
	 * @param $string
2806
	 * @return mixed
2807
	 */
2808
	public static function alias_directories( $string ) {
2809
		// ABSPATH has a trailing slash.
2810
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2811
		// WP_CONTENT_DIR does not have a trailing slash.
2812
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2813
2814
		return $string;
2815
	}
2816
2817
	public static function activate_default_modules(
2818
		$min_version = false,
2819
		$max_version = false,
2820
		$other_modules = array(),
2821
		$redirect = null,
2822
		$send_state_messages = null
2823
	) {
2824
		$jetpack = self::init();
2825
2826
		if ( is_null( $redirect ) ) {
2827
			if (
2828
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2829
			||
2830
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2831
			||
2832
				( defined( 'WP_CLI' ) && WP_CLI )
2833
			||
2834
				( defined( 'DOING_CRON' ) && DOING_CRON )
2835
			||
2836
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2837
			) {
2838
				$redirect = false;
2839
			} elseif ( is_admin() ) {
2840
				$redirect = true;
2841
			} else {
2842
				$redirect = false;
2843
			}
2844
		}
2845
2846
		if ( is_null( $send_state_messages ) ) {
2847
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2848
		}
2849
2850
		$modules = self::get_default_modules( $min_version, $max_version );
2851
		$modules = array_merge( $other_modules, $modules );
2852
2853
		// Look for standalone plugins and disable if active.
2854
2855
		$to_deactivate = array();
2856
		foreach ( $modules as $module ) {
2857
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2858
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2859
			}
2860
		}
2861
2862
		$deactivated = array();
2863
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2864
			list( $probable_file, $probable_title ) = $deactivate_me;
2865
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2866
				$deactivated[] = $module;
2867
			}
2868
		}
2869
2870
		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...
2871
			if ( $send_state_messages ) {
2872
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2873
			}
2874
2875
			if ( $redirect ) {
2876
				$url = add_query_arg(
2877
					array(
2878
						'action'   => 'activate_default_modules',
2879
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2880
					),
2881
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2882
				);
2883
				wp_safe_redirect( $url );
2884
				exit;
2885
			}
2886
		}
2887
2888
		/**
2889
		 * Fires before default modules are activated.
2890
		 *
2891
		 * @since 1.9.0
2892
		 *
2893
		 * @param string $min_version Minimum version number required to use modules.
2894
		 * @param string $max_version Maximum version number required to use modules.
2895
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2896
		 */
2897
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2898
2899
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2900
		if ( $send_state_messages ) {
2901
			self::restate();
2902
			self::catch_errors( true );
2903
		}
2904
2905
		$active = self::get_active_modules();
2906
2907
		foreach ( $modules as $module ) {
2908
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2909
				$active[] = $module;
2910
				self::update_active_modules( $active );
2911
				continue;
2912
			}
2913
2914
			if ( $send_state_messages && in_array( $module, $active ) ) {
2915
				$module_info = self::get_module( $module );
2916 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2917
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2918
					if ( $active_state = self::state( $state ) ) {
2919
						$active_state = explode( ',', $active_state );
2920
					} else {
2921
						$active_state = array();
2922
					}
2923
					$active_state[] = $module;
2924
					self::state( $state, implode( ',', $active_state ) );
2925
				}
2926
				continue;
2927
			}
2928
2929
			$file = self::get_module_path( $module );
2930
			if ( ! file_exists( $file ) ) {
2931
				continue;
2932
			}
2933
2934
			// we'll override this later if the plugin can be included without fatal error
2935
			if ( $redirect ) {
2936
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2937
			}
2938
2939
			if ( $send_state_messages ) {
2940
				self::state( 'error', 'module_activation_failed' );
2941
				self::state( 'module', $module );
2942
			}
2943
2944
			ob_start();
2945
			require_once $file;
2946
2947
			$active[] = $module;
2948
2949 View Code Duplication
			if ( $send_state_messages ) {
2950
2951
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2952
				if ( $active_state = self::state( $state ) ) {
2953
					$active_state = explode( ',', $active_state );
2954
				} else {
2955
					$active_state = array();
2956
				}
2957
				$active_state[] = $module;
2958
				self::state( $state, implode( ',', $active_state ) );
2959
			}
2960
2961
			self::update_active_modules( $active );
2962
2963
			ob_end_clean();
2964
		}
2965
2966
		if ( $send_state_messages ) {
2967
			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...
2968
			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...
2969
		}
2970
2971
		self::catch_errors( false );
2972
		/**
2973
		 * Fires when default modules are activated.
2974
		 *
2975
		 * @since 1.9.0
2976
		 *
2977
		 * @param string $min_version Minimum version number required to use modules.
2978
		 * @param string $max_version Maximum version number required to use modules.
2979
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2980
		 */
2981
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2982
	}
2983
2984
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2985
		/**
2986
		 * Fires before a module is activated.
2987
		 *
2988
		 * @since 2.6.0
2989
		 *
2990
		 * @param string $module Module slug.
2991
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2992
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2993
		 */
2994
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2995
2996
		$jetpack = self::init();
2997
2998
		if ( ! strlen( $module ) ) {
2999
			return false;
3000
		}
3001
3002
		if ( ! self::is_module( $module ) ) {
3003
			return false;
3004
		}
3005
3006
		// If it's already active, then don't do it again
3007
		$active = self::get_active_modules();
3008
		foreach ( $active as $act ) {
3009
			if ( $act == $module ) {
3010
				return true;
3011
			}
3012
		}
3013
3014
		$module_data = self::get_module( $module );
3015
3016
		$is_development_mode = ( new Status() )->is_development_mode();
3017
		if ( ! self::is_active() ) {
3018
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3019
				return false;
3020
			}
3021
3022
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3023
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3024
				return false;
3025
			}
3026
		}
3027
3028
		// Check and see if the old plugin is active
3029
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3030
			// Deactivate the old plugin
3031
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3032
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3033
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3034
				self::state( 'deactivated_plugins', $module );
3035
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3036
				exit;
3037
			}
3038
		}
3039
3040
		// Protect won't work with mis-configured IPs
3041
		if ( 'protect' === $module ) {
3042
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3043
			if ( ! jetpack_protect_get_ip() ) {
3044
				self::state( 'message', 'protect_misconfigured_ip' );
3045
				return false;
3046
			}
3047
		}
3048
3049
		if ( ! Jetpack_Plan::supports( $module ) ) {
3050
			return false;
3051
		}
3052
3053
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3054
		self::state( 'module', $module );
3055
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3056
3057
		self::catch_errors( true );
3058
		ob_start();
3059
		require self::get_module_path( $module );
3060
		/** This action is documented in class.jetpack.php */
3061
		do_action( 'jetpack_activate_module', $module );
3062
		$active[] = $module;
3063
		self::update_active_modules( $active );
3064
3065
		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...
3066
		ob_end_clean();
3067
		self::catch_errors( false );
3068
3069
		if ( $redirect ) {
3070
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3071
		}
3072
		if ( $exit ) {
3073
			exit;
3074
		}
3075
		return true;
3076
	}
3077
3078
	function activate_module_actions( $module ) {
3079
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3080
	}
3081
3082
	public static function deactivate_module( $module ) {
3083
		/**
3084
		 * Fires when a module is deactivated.
3085
		 *
3086
		 * @since 1.9.0
3087
		 *
3088
		 * @param string $module Module slug.
3089
		 */
3090
		do_action( 'jetpack_pre_deactivate_module', $module );
3091
3092
		$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...
3093
3094
		$active = self::get_active_modules();
3095
		$new    = array_filter( array_diff( $active, (array) $module ) );
3096
3097
		return self::update_active_modules( $new );
3098
	}
3099
3100
	public static function enable_module_configurable( $module ) {
3101
		$module = self::get_module_slug( $module );
3102
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3103
	}
3104
3105
	/**
3106
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3107
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3108
	 *
3109
	 * @param string $module Module slug
3110
	 * @return string $url module configuration URL
3111
	 */
3112
	public static function module_configuration_url( $module ) {
3113
		$module      = self::get_module_slug( $module );
3114
		$default_url = self::admin_url() . "#/settings?term=$module";
3115
		/**
3116
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3117
		 *
3118
		 * @since 6.9.0
3119
		 *
3120
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3121
		 */
3122
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3123
3124
		return $url;
3125
	}
3126
3127
	/* Installation */
3128
	public static function bail_on_activation( $message, $deactivate = true ) {
3129
		?>
3130
<!doctype html>
3131
<html>
3132
<head>
3133
<meta charset="<?php bloginfo( 'charset' ); ?>">
3134
<style>
3135
* {
3136
	text-align: center;
3137
	margin: 0;
3138
	padding: 0;
3139
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3140
}
3141
p {
3142
	margin-top: 1em;
3143
	font-size: 18px;
3144
}
3145
</style>
3146
<body>
3147
<p><?php echo esc_html( $message ); ?></p>
3148
</body>
3149
</html>
3150
		<?php
3151
		if ( $deactivate ) {
3152
			$plugins = get_option( 'active_plugins' );
3153
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3154
			$update  = false;
3155
			foreach ( $plugins as $i => $plugin ) {
3156
				if ( $plugin === $jetpack ) {
3157
					$plugins[ $i ] = false;
3158
					$update        = true;
3159
				}
3160
			}
3161
3162
			if ( $update ) {
3163
				update_option( 'active_plugins', array_filter( $plugins ) );
3164
			}
3165
		}
3166
		exit;
3167
	}
3168
3169
	/**
3170
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3171
	 *
3172
	 * @static
3173
	 */
3174
	public static function plugin_activation( $network_wide ) {
3175
		Jetpack_Options::update_option( 'activated', 1 );
3176
3177
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3178
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3179
		}
3180
3181
		if ( $network_wide ) {
3182
			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...
3183
		}
3184
3185
		// For firing one-off events (notices) immediately after activation
3186
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3187
3188
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3189
3190
		Health::on_jetpack_activated();
3191
3192
		self::plugin_initialize();
3193
	}
3194
3195
	public static function get_activation_source( $referer_url ) {
3196
3197
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3198
			return array( 'wp-cli', null );
3199
		}
3200
3201
		$referer = wp_parse_url( $referer_url );
3202
3203
		$source_type  = 'unknown';
3204
		$source_query = null;
3205
3206
		if ( ! is_array( $referer ) ) {
3207
			return array( $source_type, $source_query );
3208
		}
3209
3210
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3211
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3212
3213
		if ( isset( $referer['query'] ) ) {
3214
			parse_str( $referer['query'], $query_parts );
3215
		} else {
3216
			$query_parts = array();
3217
		}
3218
3219
		if ( $plugins_path === $referer['path'] ) {
3220
			$source_type = 'list';
3221
		} elseif ( $plugins_install_path === $referer['path'] ) {
3222
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3223
			switch ( $tab ) {
3224
				case 'popular':
3225
					$source_type = 'popular';
3226
					break;
3227
				case 'recommended':
3228
					$source_type = 'recommended';
3229
					break;
3230
				case 'favorites':
3231
					$source_type = 'favorites';
3232
					break;
3233
				case 'search':
3234
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3235
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3236
					break;
3237
				default:
3238
					$source_type = 'featured';
3239
			}
3240
		}
3241
3242
		return array( $source_type, $source_query );
3243
	}
3244
3245
	/**
3246
	 * Runs before bumping version numbers up to a new version
3247
	 *
3248
	 * @param  string $version    Version:timestamp
3249
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3250
	 * @return null              [description]
3251
	 */
3252
	public static function do_version_bump( $version, $old_version ) {
3253
		if ( ! $old_version ) { // For new sites
3254
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3255
		}
3256
	}
3257
3258
	/**
3259
	 * Sets the internal version number and activation state.
3260
	 *
3261
	 * @static
3262
	 */
3263
	public static function plugin_initialize() {
3264
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3265
			Jetpack_Options::update_option( 'activated', 2 );
3266
		}
3267
3268 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3269
			$version = $old_version = JETPACK__VERSION . ':' . time();
3270
			/** This action is documented in class.jetpack.php */
3271
			do_action( 'updating_jetpack_version', $version, false );
3272
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3273
		}
3274
3275
		self::load_modules();
3276
3277
		Jetpack_Options::delete_option( 'do_activate' );
3278
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3279
	}
3280
3281
	/**
3282
	 * Removes all connection options
3283
	 *
3284
	 * @static
3285
	 */
3286
	public static function plugin_deactivation() {
3287
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3288
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3289
			Jetpack_Network::init()->deactivate();
3290
		} else {
3291
			self::disconnect( false );
3292
			// Jetpack_Heartbeat::init()->deactivate();
3293
		}
3294
	}
3295
3296
	/**
3297
	 * Disconnects from the Jetpack servers.
3298
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3299
	 *
3300
	 * @static
3301
	 */
3302
	public static function disconnect( $update_activated_state = true ) {
3303
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3304
		$connection = self::connection();
3305
		$connection->clean_nonces( true );
3306
3307
		// If the site is in an IDC because sync is not allowed,
3308
		// let's make sure to not disconnect the production site.
3309
		if ( ! self::validate_sync_error_idc_option() ) {
3310
			$tracking = new Tracking();
3311
			$tracking->record_user_event( 'disconnect_site', array() );
3312
3313
			$connection->disconnect_site_wpcom();
3314
		}
3315
3316
		$connection->delete_all_connection_tokens();
3317
		Jetpack_IDC::clear_all_idc_options();
3318
3319
		if ( $update_activated_state ) {
3320
			Jetpack_Options::update_option( 'activated', 4 );
3321
		}
3322
3323
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3324
			// Check then record unique disconnection if site has never been disconnected previously
3325
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3326
				$jetpack_unique_connection['disconnected'] = 1;
3327
			} else {
3328
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3329
					// track unique disconnect
3330
					$jetpack = self::init();
3331
3332
					$jetpack->stat( 'connections', 'unique-disconnect' );
3333
					$jetpack->do_stats( 'server_side' );
3334
				}
3335
				// increment number of times disconnected
3336
				$jetpack_unique_connection['disconnected'] += 1;
3337
			}
3338
3339
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3340
		}
3341
3342
		// Delete all the sync related data. Since it could be taking up space.
3343
		Sender::get_instance()->uninstall();
3344
3345
		// Disable the Heartbeat cron
3346
		Jetpack_Heartbeat::init()->deactivate();
3347
	}
3348
3349
	/**
3350
	 * Unlinks the current user from the linked WordPress.com user.
3351
	 *
3352
	 * @deprecated since 7.7
3353
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3354
	 *
3355
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
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...
3356
	 * @return Boolean Whether the disconnection of the user was successful.
3357
	 */
3358
	public static function unlink_user( $user_id = null ) {
3359
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3360
		return Connection_Manager::disconnect_user( $user_id );
3361
	}
3362
3363
	/**
3364
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3365
	 */
3366
	public static function try_registration() {
3367
		$terms_of_service = new Terms_Of_Service();
3368
		// The user has agreed to the TOS at some point by now.
3369
		$terms_of_service->agree();
3370
3371
		// Let's get some testing in beta versions and such.
3372
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3373
			// Before attempting to connect, let's make sure that the domains are viable.
3374
			$domains_to_check = array_unique(
3375
				array(
3376
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3377
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3378
				)
3379
			);
3380
			foreach ( $domains_to_check as $domain ) {
3381
				$result = self::connection()->is_usable_domain( $domain );
3382
				if ( is_wp_error( $result ) ) {
3383
					return $result;
3384
				}
3385
			}
3386
		}
3387
3388
		$result = self::register();
3389
3390
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3391
		if ( ! $result || is_wp_error( $result ) ) {
3392
			return $result;
3393
		} else {
3394
			return true;
3395
		}
3396
	}
3397
3398
	/**
3399
	 * Tracking an internal event log. Try not to put too much chaff in here.
3400
	 *
3401
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3402
	 */
3403
	public static function log( $code, $data = null ) {
3404
		// only grab the latest 200 entries
3405
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3406
3407
		// Append our event to the log
3408
		$log_entry = array(
3409
			'time'    => time(),
3410
			'user_id' => get_current_user_id(),
3411
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3412
			'code'    => $code,
3413
		);
3414
		// Don't bother storing it unless we've got some.
3415
		if ( ! is_null( $data ) ) {
3416
			$log_entry['data'] = $data;
3417
		}
3418
		$log[] = $log_entry;
3419
3420
		// Try add_option first, to make sure it's not autoloaded.
3421
		// @todo: Add an add_option method to Jetpack_Options
3422
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3423
			Jetpack_Options::update_option( 'log', $log );
3424
		}
3425
3426
		/**
3427
		 * Fires when Jetpack logs an internal event.
3428
		 *
3429
		 * @since 3.0.0
3430
		 *
3431
		 * @param array $log_entry {
3432
		 *  Array of details about the log entry.
3433
		 *
3434
		 *  @param string time Time of the event.
3435
		 *  @param int user_id ID of the user who trigerred the event.
3436
		 *  @param int blog_id Jetpack Blog ID.
3437
		 *  @param string code Unique name for the event.
3438
		 *  @param string data Data about the event.
3439
		 * }
3440
		 */
3441
		do_action( 'jetpack_log_entry', $log_entry );
3442
	}
3443
3444
	/**
3445
	 * Get the internal event log.
3446
	 *
3447
	 * @param $event (string) - only return the specific log events
3448
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3449
	 *
3450
	 * @return array of log events || WP_Error for invalid params
3451
	 */
3452
	public static function get_log( $event = false, $num = false ) {
3453
		if ( $event && ! is_string( $event ) ) {
3454
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
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...
3455
		}
3456
3457
		if ( $num && ! is_numeric( $num ) ) {
3458
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
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...
3459
		}
3460
3461
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3462
3463
		// If nothing set - act as it did before, otherwise let's start customizing the output
3464
		if ( ! $num && ! $event ) {
3465
			return $entire_log;
3466
		} else {
3467
			$entire_log = array_reverse( $entire_log );
3468
		}
3469
3470
		$custom_log_output = array();
3471
3472
		if ( $event ) {
3473
			foreach ( $entire_log as $log_event ) {
3474
				if ( $event == $log_event['code'] ) {
3475
					$custom_log_output[] = $log_event;
3476
				}
3477
			}
3478
		} else {
3479
			$custom_log_output = $entire_log;
3480
		}
3481
3482
		if ( $num ) {
3483
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3484
		}
3485
3486
		return $custom_log_output;
3487
	}
3488
3489
	/**
3490
	 * Log modification of important settings.
3491
	 */
3492
	public static function log_settings_change( $option, $old_value, $value ) {
3493
		switch ( $option ) {
3494
			case 'jetpack_sync_non_public_post_stati':
3495
				self::log( $option, $value );
3496
				break;
3497
		}
3498
	}
3499
3500
	/**
3501
	 * Return stat data for WPCOM sync
3502
	 */
3503
	public static function get_stat_data( $encode = true, $extended = true ) {
3504
		$data = Jetpack_Heartbeat::generate_stats_array();
3505
3506
		if ( $extended ) {
3507
			$additional_data = self::get_additional_stat_data();
3508
			$data            = array_merge( $data, $additional_data );
3509
		}
3510
3511
		if ( $encode ) {
3512
			return json_encode( $data );
3513
		}
3514
3515
		return $data;
3516
	}
3517
3518
	/**
3519
	 * Get additional stat data to sync to WPCOM
3520
	 */
3521
	public static function get_additional_stat_data( $prefix = '' ) {
3522
		$return[ "{$prefix}themes" ]        = self::get_parsed_theme_data();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$return was never initialized. Although not strictly required by PHP, it is generally a good practice to add $return = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
3523
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3524
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3525
		$return[ "{$prefix}site-count" ]    = 0;
3526
3527
		if ( function_exists( 'get_blog_count' ) ) {
3528
			$return[ "{$prefix}site-count" ] = get_blog_count();
3529
		}
3530
		return $return;
3531
	}
3532
3533
	private static function get_site_user_count() {
3534
		global $wpdb;
3535
3536
		if ( function_exists( 'wp_is_large_network' ) ) {
3537
			if ( wp_is_large_network( 'users' ) ) {
3538
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3539
			}
3540
		}
3541
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3542
			// It wasn't there, so regenerate the data and save the transient
3543
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3544
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3545
		}
3546
		return $user_count;
3547
	}
3548
3549
	/* Admin Pages */
3550
3551
	function admin_init() {
3552
		// If the plugin is not connected, display a connect message.
3553
		if (
3554
			// the plugin was auto-activated and needs its candy
3555
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3556
		||
3557
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3558
			! Jetpack_Options::get_option( 'activated' )
3559
		) {
3560
			self::plugin_initialize();
3561
		}
3562
3563
		$is_development_mode = ( new Status() )->is_development_mode();
3564
		if ( ! self::is_active() && ! $is_development_mode ) {
3565
			Jetpack_Connection_Banner::init();
3566
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3567
			// Upgrade: 1.1 -> 1.1.1
3568
			// Check and see if host can verify the Jetpack servers' SSL certificate
3569
			$args       = array();
3570
			$connection = self::connection();
3571
			Client::_wp_remote_request(
3572
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3573
				$args,
3574
				true
3575
			);
3576
		}
3577
3578
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3579
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3580
		}
3581
3582
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3583
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3584
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3585
3586
		if ( self::is_active() || $is_development_mode ) {
3587
			// Artificially throw errors in certain whitelisted cases during plugin activation
3588
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3589
		}
3590
3591
		// Add custom column in wp-admin/users.php to show whether user is linked.
3592
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3593
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3594
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3595
	}
3596
3597
	function admin_body_class( $admin_body_class = '' ) {
3598
		$classes = explode( ' ', trim( $admin_body_class ) );
3599
3600
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3601
3602
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3603
		return " $admin_body_class ";
3604
	}
3605
3606
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3607
		return $admin_body_class . ' jetpack-pagestyles ';
3608
	}
3609
3610
	/**
3611
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3612
	 * This function artificially throws errors for such cases (whitelisted).
3613
	 *
3614
	 * @param string $plugin The activated plugin.
3615
	 */
3616
	function throw_error_on_activate_plugin( $plugin ) {
3617
		$active_modules = self::get_active_modules();
3618
3619
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3620
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3621
			$throw = false;
3622
3623
			// Try and make sure it really was the stats plugin
3624
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3625
				if ( 'stats.php' == basename( $plugin ) ) {
3626
					$throw = true;
3627
				}
3628
			} else {
3629
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3630
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3631
					$throw = true;
3632
				}
3633
			}
3634
3635
			if ( $throw ) {
3636
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3637
			}
3638
		}
3639
	}
3640
3641
	function intercept_plugin_error_scrape_init() {
3642
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3643
	}
3644
3645
	function intercept_plugin_error_scrape( $action, $result ) {
3646
		if ( ! $result ) {
3647
			return;
3648
		}
3649
3650
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3651
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3652
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3653
			}
3654
		}
3655
	}
3656
3657
	/**
3658
	 * Register the remote file upload request handlers, if needed.
3659
	 *
3660
	 * @access public
3661
	 */
3662
	public function add_remote_request_handlers() {
3663
		// Remote file uploads are allowed only via AJAX requests.
3664
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3665
			return;
3666
		}
3667
3668
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3669
		$remote_request_actions = array(
3670
			'jetpack_upload_file',
3671
			'jetpack_update_file',
3672
		);
3673
3674
		// phpcs:ignore WordPress.Security.NonceVerification
3675
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3676
			return;
3677
		}
3678
3679
		// Require Jetpack authentication for the remote file upload AJAX requests.
3680
		$this->connection_manager->require_jetpack_authentication();
3681
3682
		// Register the remote file upload AJAX handlers.
3683
		foreach ( $remote_request_actions as $action ) {
3684
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3685
		}
3686
	}
3687
3688
	/**
3689
	 * Handler for Jetpack remote file uploads.
3690
	 *
3691
	 * @access public
3692
	 */
3693
	public function remote_request_handlers() {
3694
		$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...
3695
3696
		switch ( current_filter() ) {
3697
			case 'wp_ajax_nopriv_jetpack_upload_file':
3698
				$response = $this->upload_handler();
3699
				break;
3700
3701
			case 'wp_ajax_nopriv_jetpack_update_file':
3702
				$response = $this->upload_handler( true );
3703
				break;
3704
			default:
3705
				$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...
3706
				break;
3707
		}
3708
3709
		if ( ! $response ) {
3710
			$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...
3711
		}
3712
3713
		if ( is_wp_error( $response ) ) {
3714
			$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...
3715
			$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...
3716
			$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...
3717
3718
			if ( ! is_int( $status_code ) ) {
3719
				$status_code = 400;
3720
			}
3721
3722
			status_header( $status_code );
3723
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3724
		}
3725
3726
		status_header( 200 );
3727
		if ( true === $response ) {
3728
			exit;
3729
		}
3730
3731
		die( json_encode( (object) $response ) );
3732
	}
3733
3734
	/**
3735
	 * Uploads a file gotten from the global $_FILES.
3736
	 * If `$update_media_item` is true and `post_id` is defined
3737
	 * the attachment file of the media item (gotten through of the post_id)
3738
	 * will be updated instead of add a new one.
3739
	 *
3740
	 * @param  boolean $update_media_item - update media attachment
3741
	 * @return array - An array describing the uploadind files process
3742
	 */
3743
	function upload_handler( $update_media_item = false ) {
3744
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3745
			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...
3746
		}
3747
3748
		$user = wp_authenticate( '', '' );
3749
		if ( ! $user || is_wp_error( $user ) ) {
3750
			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...
3751
		}
3752
3753
		wp_set_current_user( $user->ID );
3754
3755
		if ( ! current_user_can( 'upload_files' ) ) {
3756
			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...
3757
		}
3758
3759
		if ( empty( $_FILES ) ) {
3760
			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...
3761
		}
3762
3763
		foreach ( array_keys( $_FILES ) as $files_key ) {
3764
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3765
				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...
3766
			}
3767
		}
3768
3769
		$media_keys = array_keys( $_FILES['media'] );
3770
3771
		$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...
3772
		if ( ! $token || is_wp_error( $token ) ) {
3773
			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...
3774
		}
3775
3776
		$uploaded_files = array();
3777
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3778
		unset( $GLOBALS['post'] );
3779
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3780
			$file = array();
3781
			foreach ( $media_keys as $media_key ) {
3782
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3783
			}
3784
3785
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3786
3787
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3788
			if ( $hmac_provided !== $hmac_file ) {
3789
				$uploaded_files[ $index ] = (object) array(
3790
					'error'             => 'invalid_hmac',
3791
					'error_description' => 'The corresponding HMAC for this file does not match',
3792
				);
3793
				continue;
3794
			}
3795
3796
			$_FILES['.jetpack.upload.'] = $file;
3797
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3798
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3799
				$post_id = 0;
3800
			}
3801
3802
			if ( $update_media_item ) {
3803
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3804
					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...
3805
				}
3806
3807
				$media_array = $_FILES['media'];
3808
3809
				$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...
3810
				$file_array['type']     = $media_array['type'][0];
3811
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3812
				$file_array['error']    = $media_array['error'][0];
3813
				$file_array['size']     = $media_array['size'][0];
3814
3815
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3816
3817
				if ( is_wp_error( $edited_media_item ) ) {
3818
					return $edited_media_item;
3819
				}
3820
3821
				$response = (object) array(
3822
					'id'   => (string) $post_id,
3823
					'file' => (string) $edited_media_item->post_title,
3824
					'url'  => (string) wp_get_attachment_url( $post_id ),
3825
					'type' => (string) $edited_media_item->post_mime_type,
3826
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3827
				);
3828
3829
				return (array) array( $response );
3830
			}
3831
3832
			$attachment_id = media_handle_upload(
3833
				'.jetpack.upload.',
3834
				$post_id,
3835
				array(),
3836
				array(
3837
					'action' => 'jetpack_upload_file',
3838
				)
3839
			);
3840
3841
			if ( ! $attachment_id ) {
3842
				$uploaded_files[ $index ] = (object) array(
3843
					'error'             => 'unknown',
3844
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3845
				);
3846
			} elseif ( is_wp_error( $attachment_id ) ) {
3847
				$uploaded_files[ $index ] = (object) array(
3848
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3849
					'error_description' => $attachment_id->get_error_message(),
3850
				);
3851
			} else {
3852
				$attachment               = get_post( $attachment_id );
3853
				$uploaded_files[ $index ] = (object) array(
3854
					'id'   => (string) $attachment_id,
3855
					'file' => $attachment->post_title,
3856
					'url'  => wp_get_attachment_url( $attachment_id ),
3857
					'type' => $attachment->post_mime_type,
3858
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3859
				);
3860
				// Zip files uploads are not supported unless they are done for installation purposed
3861
				// lets delete them in case something goes wrong in this whole process
3862
				if ( 'application/zip' === $attachment->post_mime_type ) {
3863
					// Schedule a cleanup for 2 hours from now in case of failed install.
3864
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3865
				}
3866
			}
3867
		}
3868
		if ( ! is_null( $global_post ) ) {
3869
			$GLOBALS['post'] = $global_post;
3870
		}
3871
3872
		return $uploaded_files;
3873
	}
3874
3875
	/**
3876
	 * Add help to the Jetpack page
3877
	 *
3878
	 * @since Jetpack (1.2.3)
3879
	 * @return false if not the Jetpack page
3880
	 */
3881
	function admin_help() {
3882
		$current_screen = get_current_screen();
3883
3884
		// Overview
3885
		$current_screen->add_help_tab(
3886
			array(
3887
				'id'      => 'home',
3888
				'title'   => __( 'Home', 'jetpack' ),
3889
				'content' =>
3890
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3891
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3892
					'<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>',
3893
			)
3894
		);
3895
3896
		// Screen Content
3897
		if ( current_user_can( 'manage_options' ) ) {
3898
			$current_screen->add_help_tab(
3899
				array(
3900
					'id'      => 'settings',
3901
					'title'   => __( 'Settings', 'jetpack' ),
3902
					'content' =>
3903
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3904
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3905
						'<ol>' .
3906
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3907
							'<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>' .
3908
						'</ol>' .
3909
						'<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>',
3910
				)
3911
			);
3912
		}
3913
3914
		// Help Sidebar
3915
		$current_screen->set_help_sidebar(
3916
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3917
			'<p><a href="https://jetpack.com/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3918
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3919
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3920
		);
3921
	}
3922
3923
	function admin_menu_css() {
3924
		wp_enqueue_style( 'jetpack-icons' );
3925
	}
3926
3927
	function admin_menu_order() {
3928
		return true;
3929
	}
3930
3931 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3932
		$jp_menu_order = array();
3933
3934
		foreach ( $menu_order as $index => $item ) {
3935
			if ( $item != 'jetpack' ) {
3936
				$jp_menu_order[] = $item;
3937
			}
3938
3939
			if ( $index == 0 ) {
3940
				$jp_menu_order[] = 'jetpack';
3941
			}
3942
		}
3943
3944
		return $jp_menu_order;
3945
	}
3946
3947
	function admin_banner_styles() {
3948
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3949
3950 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3951
			wp_register_style(
3952
				'jetpack-dops-style',
3953
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3954
				array(),
3955
				JETPACK__VERSION
3956
			);
3957
		}
3958
3959
		wp_enqueue_style(
3960
			'jetpack',
3961
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3962
			array( 'jetpack-dops-style' ),
3963
			JETPACK__VERSION . '-20121016'
3964
		);
3965
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3966
		wp_style_add_data( 'jetpack', 'suffix', $min );
3967
	}
3968
3969
	function plugin_action_links( $actions ) {
3970
3971
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3972
3973
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
3974
			return array_merge(
3975
				$jetpack_home,
3976
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3977
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3978
				$actions
3979
			);
3980
		}
3981
3982
		return array_merge( $jetpack_home, $actions );
3983
	}
3984
3985
	/*
3986
	 * Registration flow:
3987
	 * 1 - ::admin_page_load() action=register
3988
	 * 2 - ::try_registration()
3989
	 * 3 - ::register()
3990
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3991
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3992
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3993
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3994
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3995
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3996
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3997
	 *       jetpack_id, jetpack_secret, jetpack_public
3998
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3999
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4000
	 * 5 - user logs in with WP.com account
4001
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4002
	 *		- Manager::authorize()
4003
	 *		- Manager::get_token()
4004
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4005
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4006
	 *			- which responds with access_token, token_type, scope
4007
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4008
	 *		- Jetpack::activate_default_modules()
4009
	 *     		- Deactivates deprecated plugins
4010
	 *     		- Activates all default modules
4011
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4012
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4013
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4014
	 *     Done!
4015
	 */
4016
4017
	/**
4018
	 * Handles the page load events for the Jetpack admin page
4019
	 */
4020
	function admin_page_load() {
4021
		$error = false;
4022
4023
		// Make sure we have the right body class to hook stylings for subpages off of.
4024
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4025
4026
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4027
			// Should only be used in intermediate redirects to preserve state across redirects
4028
			self::restate();
4029
		}
4030
4031
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4032
			// @todo: Add validation against a known whitelist
4033
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4034
			// User clicked in the iframe to link their accounts
4035
			if ( ! self::is_user_connected() ) {
4036
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4037
4038
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4039
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4040
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4041
4042
				if ( isset( $_GET['notes_iframe'] ) ) {
4043
					$connect_url .= '&notes_iframe';
4044
				}
4045
				wp_redirect( $connect_url );
4046
				exit;
4047
			} else {
4048
				if ( ! isset( $_GET['calypso_env'] ) ) {
4049
					self::state( 'message', 'already_authorized' );
4050
					wp_safe_redirect( self::admin_url() );
4051
					exit;
4052
				} else {
4053
					$connect_url  = $this->build_connect_url( true, false, $from );
4054
					$connect_url .= '&already_authorized=true';
4055
					wp_redirect( $connect_url );
4056
					exit;
4057
				}
4058
			}
4059
		}
4060
4061
		if ( isset( $_GET['action'] ) ) {
4062
			switch ( $_GET['action'] ) {
4063
				case 'authorize':
4064
					if ( self::is_active() && self::is_user_connected() ) {
4065
						self::state( 'message', 'already_authorized' );
4066
						wp_safe_redirect( self::admin_url() );
4067
						exit;
4068
					}
4069
					self::log( 'authorize' );
4070
					$client_server = new Jetpack_Client_Server();
4071
					$client_server->client_authorize();
4072
					exit;
4073
				case 'register':
4074
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4075
						$error = 'cheatin';
4076
						break;
4077
					}
4078
					check_admin_referer( 'jetpack-register' );
4079
					self::log( 'register' );
4080
					self::maybe_set_version_option();
4081
					$registered = self::try_registration();
4082 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4083
						$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...
4084
						self::state( 'error', $error );
4085
						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...
4086
4087
						/**
4088
						 * Jetpack registration Error.
4089
						 *
4090
						 * @since 7.5.0
4091
						 *
4092
						 * @param string|int $error The error code.
4093
						 * @param \WP_Error $registered The error object.
4094
						 */
4095
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4096
						break;
4097
					}
4098
4099
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4100
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4101
4102
					/**
4103
					 * Jetpack registration Success.
4104
					 *
4105
					 * @since 7.5.0
4106
					 *
4107
					 * @param string $from 'from' GET parameter;
4108
					 */
4109
					do_action( 'jetpack_connection_register_success', $from );
4110
4111
					$url = $this->build_connect_url( true, $redirect, $from );
4112
4113
					if ( ! empty( $_GET['onboarding'] ) ) {
4114
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4115
					}
4116
4117
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4118
						$url = add_query_arg( 'auth_approved', 'true', $url );
4119
					}
4120
4121
					wp_redirect( $url );
4122
					exit;
4123
				case 'activate':
4124
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4125
						$error = 'cheatin';
4126
						break;
4127
					}
4128
4129
					$module = stripslashes( $_GET['module'] );
4130
					check_admin_referer( "jetpack_activate-$module" );
4131
					self::log( 'activate', $module );
4132
					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...
4133
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4134
					}
4135
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4136
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4137
					exit;
4138
				case 'activate_default_modules':
4139
					check_admin_referer( 'activate_default_modules' );
4140
					self::log( 'activate_default_modules' );
4141
					self::restate();
4142
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4143
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4144
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4145
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4146
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4147
					exit;
4148
				case 'disconnect':
4149
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4150
						$error = 'cheatin';
4151
						break;
4152
					}
4153
4154
					check_admin_referer( 'jetpack-disconnect' );
4155
					self::log( 'disconnect' );
4156
					self::disconnect();
4157
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4158
					exit;
4159
				case 'reconnect':
4160
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4161
						$error = 'cheatin';
4162
						break;
4163
					}
4164
4165
					check_admin_referer( 'jetpack-reconnect' );
4166
					self::log( 'reconnect' );
4167
					$this->disconnect();
4168
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4169
					exit;
4170 View Code Duplication
				case 'deactivate':
4171
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4172
						$error = 'cheatin';
4173
						break;
4174
					}
4175
4176
					$modules = stripslashes( $_GET['module'] );
4177
					check_admin_referer( "jetpack_deactivate-$modules" );
4178
					foreach ( explode( ',', $modules ) as $module ) {
4179
						self::log( 'deactivate', $module );
4180
						self::deactivate_module( $module );
4181
						self::state( 'message', 'module_deactivated' );
4182
					}
4183
					self::state( 'module', $modules );
4184
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4185
					exit;
4186
				case 'unlink':
4187
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4188
					check_admin_referer( 'jetpack-unlink' );
4189
					self::log( 'unlink' );
4190
					Connection_Manager::disconnect_user();
4191
					self::state( 'message', 'unlinked' );
4192
					if ( 'sub-unlink' == $redirect ) {
4193
						wp_safe_redirect( admin_url() );
4194
					} else {
4195
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4196
					}
4197
					exit;
4198
				case 'onboard':
4199
					if ( ! current_user_can( 'manage_options' ) ) {
4200
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4201
					} else {
4202
						self::create_onboarding_token();
4203
						$url = $this->build_connect_url( true );
4204
4205
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4206
							$url = add_query_arg( 'onboarding', $token, $url );
4207
						}
4208
4209
						$calypso_env = $this->get_calypso_env();
4210
						if ( ! empty( $calypso_env ) ) {
4211
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4212
						}
4213
4214
						wp_redirect( $url );
4215
						exit;
4216
					}
4217
					exit;
4218
				default:
4219
					/**
4220
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4221
					 *
4222
					 * @since 2.6.0
4223
					 *
4224
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4225
					 */
4226
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4227
			}
4228
		}
4229
4230
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4231
			self::activate_new_modules( true );
4232
		}
4233
4234
		$message_code = self::state( 'message' );
4235
		if ( self::state( 'optin-manage' ) ) {
4236
			$activated_manage = $message_code;
4237
			$message_code     = 'jetpack-manage';
4238
		}
4239
4240
		switch ( $message_code ) {
4241
			case 'jetpack-manage':
4242
				$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>';
4243
				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...
4244
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4245
				}
4246
				break;
4247
4248
		}
4249
4250
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4251
4252
		if ( ! empty( $deactivated_plugins ) ) {
4253
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4254
			$deactivated_titles  = array();
4255
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4256
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4257
					continue;
4258
				}
4259
4260
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4261
			}
4262
4263
			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...
4264
				if ( $this->message ) {
4265
					$this->message .= "<br /><br />\n";
4266
				}
4267
4268
				$this->message .= wp_sprintf(
4269
					_n(
4270
						'Jetpack contains the most recent version of the old %l plugin.',
4271
						'Jetpack contains the most recent versions of the old %l plugins.',
4272
						count( $deactivated_titles ),
4273
						'jetpack'
4274
					),
4275
					$deactivated_titles
4276
				);
4277
4278
				$this->message .= "<br />\n";
4279
4280
				$this->message .= _n(
4281
					'The old version has been deactivated and can be removed from your site.',
4282
					'The old versions have been deactivated and can be removed from your site.',
4283
					count( $deactivated_titles ),
4284
					'jetpack'
4285
				);
4286
			}
4287
		}
4288
4289
		$this->privacy_checks = self::state( 'privacy_checks' );
4290
4291
		if ( $this->message || $this->error || $this->privacy_checks ) {
4292
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4293
		}
4294
4295
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4296
	}
4297
4298
	function admin_notices() {
4299
4300
		if ( $this->error ) {
4301
			?>
4302
<div id="message" class="jetpack-message jetpack-err">
4303
	<div class="squeezer">
4304
		<h2>
4305
			<?php
4306
			echo wp_kses(
4307
				$this->error,
4308
				array(
4309
					'a'      => array( 'href' => array() ),
4310
					'small'  => true,
4311
					'code'   => true,
4312
					'strong' => true,
4313
					'br'     => true,
4314
					'b'      => true,
4315
				)
4316
			);
4317
			?>
4318
			</h2>
4319
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4320
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4321
<?php	endif; ?>
4322
	</div>
4323
</div>
4324
			<?php
4325
		}
4326
4327
		if ( $this->message ) {
4328
			?>
4329
<div id="message" class="jetpack-message">
4330
	<div class="squeezer">
4331
		<h2>
4332
			<?php
4333
			echo wp_kses(
4334
				$this->message,
4335
				array(
4336
					'strong' => array(),
4337
					'a'      => array( 'href' => true ),
4338
					'br'     => true,
4339
				)
4340
			);
4341
			?>
4342
			</h2>
4343
	</div>
4344
</div>
4345
			<?php
4346
		}
4347
4348
		if ( $this->privacy_checks ) :
4349
			$module_names = $module_slugs = array();
4350
4351
			$privacy_checks = explode( ',', $this->privacy_checks );
4352
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4353
			foreach ( $privacy_checks as $module_slug ) {
4354
				$module = self::get_module( $module_slug );
4355
				if ( ! $module ) {
4356
					continue;
4357
				}
4358
4359
				$module_slugs[] = $module_slug;
4360
				$module_names[] = "<strong>{$module['name']}</strong>";
4361
			}
4362
4363
			$module_slugs = join( ',', $module_slugs );
4364
			?>
4365
<div id="message" class="jetpack-message jetpack-err">
4366
	<div class="squeezer">
4367
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4368
		<p>
4369
			<?php
4370
			echo wp_kses(
4371
				wptexturize(
4372
					wp_sprintf(
4373
						_nx(
4374
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4375
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4376
							count( $privacy_checks ),
4377
							'%l = list of Jetpack module/feature names',
4378
							'jetpack'
4379
						),
4380
						$module_names
4381
					)
4382
				),
4383
				array( 'strong' => true )
4384
			);
4385
4386
			echo "\n<br />\n";
4387
4388
			echo wp_kses(
4389
				sprintf(
4390
					_nx(
4391
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4392
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4393
						count( $privacy_checks ),
4394
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4395
						'jetpack'
4396
					),
4397
					wp_nonce_url(
4398
						self::admin_url(
4399
							array(
4400
								'page'   => 'jetpack',
4401
								'action' => 'deactivate',
4402
								'module' => urlencode( $module_slugs ),
4403
							)
4404
						),
4405
						"jetpack_deactivate-$module_slugs"
4406
					),
4407
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4408
				),
4409
				array(
4410
					'a' => array(
4411
						'href'  => true,
4412
						'title' => true,
4413
					),
4414
				)
4415
			);
4416
			?>
4417
		</p>
4418
	</div>
4419
</div>
4420
			<?php
4421
endif;
4422
	}
4423
4424
	/**
4425
	 * We can't always respond to a signed XML-RPC request with a
4426
	 * helpful error message. In some circumstances, doing so could
4427
	 * leak information.
4428
	 *
4429
	 * Instead, track that the error occurred via a Jetpack_Option,
4430
	 * and send that data back in the heartbeat.
4431
	 * All this does is increment a number, but it's enough to find
4432
	 * trends.
4433
	 *
4434
	 * @param WP_Error $xmlrpc_error The error produced during
4435
	 *                               signature validation.
4436
	 */
4437
	function track_xmlrpc_error( $xmlrpc_error ) {
4438
		$code = is_wp_error( $xmlrpc_error )
4439
			? $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...
4440
			: 'should-not-happen';
4441
4442
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4443
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4444
			// No need to update the option if we already have
4445
			// this code stored.
4446
			return;
4447
		}
4448
		$xmlrpc_errors[ $code ] = true;
4449
4450
		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...
4451
	}
4452
4453
	/**
4454
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4455
	 */
4456
	function stat( $group, $detail ) {
4457
		if ( ! isset( $this->stats[ $group ] ) ) {
4458
			$this->stats[ $group ] = array();
4459
		}
4460
		$this->stats[ $group ][] = $detail;
4461
	}
4462
4463
	/**
4464
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4465
	 */
4466
	function do_stats( $method = '' ) {
4467
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4468
			foreach ( $this->stats as $group => $stats ) {
4469
				if ( is_array( $stats ) && count( $stats ) ) {
4470
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4471
					if ( 'server_side' === $method ) {
4472
						self::do_server_side_stat( $args );
4473
					} else {
4474
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4475
					}
4476
				}
4477
				unset( $this->stats[ $group ] );
4478
			}
4479
		}
4480
	}
4481
4482
	/**
4483
	 * Runs stats code for a one-off, server-side.
4484
	 *
4485
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4486
	 *
4487
	 * @return bool If it worked.
4488
	 */
4489
	static function do_server_side_stat( $args ) {
4490
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4491
		if ( is_wp_error( $response ) ) {
4492
			return false;
4493
		}
4494
4495
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4496
			return false;
4497
		}
4498
4499
		return true;
4500
	}
4501
4502
	/**
4503
	 * Builds the stats url.
4504
	 *
4505
	 * @param $args array|string The arguments to append to the URL.
4506
	 *
4507
	 * @return string The URL to be pinged.
4508
	 */
4509
	static function build_stats_url( $args ) {
4510
		$defaults = array(
4511
			'v'    => 'wpcom2',
4512
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4513
		);
4514
		$args     = wp_parse_args( $args, $defaults );
4515
		/**
4516
		 * Filter the URL used as the Stats tracking pixel.
4517
		 *
4518
		 * @since 2.3.2
4519
		 *
4520
		 * @param string $url Base URL used as the Stats tracking pixel.
4521
		 */
4522
		$base_url = apply_filters(
4523
			'jetpack_stats_base_url',
4524
			'https://pixel.wp.com/g.gif'
4525
		);
4526
		$url      = add_query_arg( $args, $base_url );
4527
		return $url;
4528
	}
4529
4530
	/**
4531
	 * Get the role of the current user.
4532
	 *
4533
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4534
	 *
4535
	 * @access public
4536
	 * @static
4537
	 *
4538
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4539
	 */
4540
	public static function translate_current_user_to_role() {
4541
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4542
4543
		$roles = new Roles();
4544
		return $roles->translate_current_user_to_role();
4545
	}
4546
4547
	/**
4548
	 * Get the role of a particular user.
4549
	 *
4550
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4551
	 *
4552
	 * @access public
4553
	 * @static
4554
	 *
4555
	 * @param \WP_User $user User object.
4556
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4557
	 */
4558
	public static function translate_user_to_role( $user ) {
4559
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4560
4561
		$roles = new Roles();
4562
		return $roles->translate_user_to_role( $user );
4563
	}
4564
4565
	/**
4566
	 * Get the minimum capability for a role.
4567
	 *
4568
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4569
	 *
4570
	 * @access public
4571
	 * @static
4572
	 *
4573
	 * @param string $role Role name.
4574
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4575
	 */
4576
	public static function translate_role_to_cap( $role ) {
4577
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4578
4579
		$roles = new Roles();
4580
		return $roles->translate_role_to_cap( $role );
4581
	}
4582
4583
	/**
4584
	 * Sign a user role with the master access token.
4585
	 * If not specified, will default to the current user.
4586
	 *
4587
	 * @deprecated since 7.7
4588
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4589
	 *
4590
	 * @access public
4591
	 * @static
4592
	 *
4593
	 * @param string $role    User role.
4594
	 * @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...
4595
	 * @return string Signed user role.
4596
	 */
4597
	public static function sign_role( $role, $user_id = null ) {
4598
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4599
		return self::connection()->sign_role( $role, $user_id );
4600
	}
4601
4602
	/**
4603
	 * Builds a URL to the Jetpack connection auth page
4604
	 *
4605
	 * @since 3.9.5
4606
	 *
4607
	 * @param bool        $raw If true, URL will not be escaped.
4608
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4609
	 *                              If string, will be a custom redirect.
4610
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4611
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4612
	 *
4613
	 * @return string Connect URL
4614
	 */
4615
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4616
		$site_id    = Jetpack_Options::get_option( 'id' );
4617
		$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...
4618
4619
		if ( $register || ! $blog_token || ! $site_id ) {
4620
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4621
4622
			if ( ! empty( $redirect ) ) {
4623
				$url = add_query_arg(
4624
					'redirect',
4625
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4626
					$url
4627
				);
4628
			}
4629
4630
			if ( is_network_admin() ) {
4631
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4632
			}
4633
4634
			$calypso_env = self::get_calypso_env();
4635
4636
			if ( ! empty( $calypso_env ) ) {
4637
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4638
			}
4639
		} else {
4640
4641
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4642
			// because otherwise this logic can get us in to a loop.
4643
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4644
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4645
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4646
4647
				$response = Client::wpcom_json_api_request_as_blog(
4648
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4649
					'1.1'
4650
				);
4651
4652
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4653
4654
					// Generating a register URL instead to refresh the existing token
4655
					return $this->build_connect_url( $raw, $redirect, $from, true );
4656
				}
4657
			}
4658
4659
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4615 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...
4660
		}
4661
4662
		if ( $from ) {
4663
			$url = add_query_arg( 'from', $from, $url );
4664
		}
4665
4666
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4667
		/**
4668
		 * Filter the URL used when connecting a user to a WordPress.com account.
4669
		 *
4670
		 * @since 8.1.0
4671
		 *
4672
		 * @param string $url Connection URL.
4673
		 * @param bool   $raw If true, URL will not be escaped.
4674
		 */
4675
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4676
	}
4677
4678
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4679
4680
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4681
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4682
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4683
4684
		if ( $iframe ) {
4685
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4686
		}
4687
4688
		$c8n = self::connection();
4689
		$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...
4690
4691
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4692
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4693
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4694
4695
		if ( $iframe ) {
4696
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4697
		}
4698
4699
		return $url;
4700
	}
4701
4702
	/**
4703
	 * Filters the connection URL parameter array.
4704
	 *
4705
	 * @param Array $args default URL parameters used by the package.
4706
	 * @return Array the modified URL arguments array.
4707
	 */
4708
	public static function filter_connect_request_body( $args ) {
4709
		if (
4710
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4711
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4712
		) {
4713
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4714
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4715
				? $gp_locale->slug
4716
				: '';
4717
		}
4718
4719
		$tracking        = new Tracking();
4720
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4721
4722
		$args = array_merge(
4723
			$args,
4724
			array(
4725
				'_ui' => $tracks_identity['_ui'],
4726
				'_ut' => $tracks_identity['_ut'],
4727
			)
4728
		);
4729
4730
		$calypso_env = self::get_calypso_env();
4731
4732
		if ( ! empty( $calypso_env ) ) {
4733
			$args['calypso_env'] = $calypso_env;
4734
		}
4735
4736
		return $args;
4737
	}
4738
4739
	/**
4740
	 * Filters the URL that will process the connection data. It can be different from the URL
4741
	 * that we send the user to after everything is done.
4742
	 *
4743
	 * @param String $processing_url the default redirect URL used by the package.
4744
	 * @return String the modified URL.
4745
	 */
4746
	public static function filter_connect_processing_url( $processing_url ) {
4747
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4748
		return $processing_url;
4749
	}
4750
4751
	/**
4752
	 * Filters the redirection URL that is used for connect requests. The redirect
4753
	 * URL should return the user back to the Jetpack console.
4754
	 *
4755
	 * @param String $redirect the default redirect URL used by the package.
4756
	 * @return String the modified URL.
4757
	 */
4758
	public static function filter_connect_redirect_url( $redirect ) {
4759
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4760
		$redirect           = $redirect
4761
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4762
			: $jetpack_admin_page;
4763
4764
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4765
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4766
		}
4767
4768
		return $redirect;
4769
	}
4770
4771
	/**
4772
	 * This action fires at the beginning of the Manager::authorize method.
4773
	 */
4774
	public static function authorize_starting() {
4775
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4776
		// Checking if site has been active/connected previously before recording unique connection.
4777
		if ( ! $jetpack_unique_connection ) {
4778
			// jetpack_unique_connection option has never been set.
4779
			$jetpack_unique_connection = array(
4780
				'connected'    => 0,
4781
				'disconnected' => 0,
4782
				'version'      => '3.6.1',
4783
			);
4784
4785
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4786
4787
			// Track unique connection.
4788
			$jetpack = self::init();
4789
4790
			$jetpack->stat( 'connections', 'unique-connection' );
4791
			$jetpack->do_stats( 'server_side' );
4792
		}
4793
4794
		// Increment number of times connected.
4795
		$jetpack_unique_connection['connected'] += 1;
4796
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4797
	}
4798
4799
	/**
4800
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4801
	 * linked.
4802
	 */
4803
	public static function authorize_ending_linked() {
4804
		// Don't activate anything since we are just connecting a user.
4805
		self::state( 'message', 'linked' );
4806
	}
4807
4808
	/**
4809
	 * This action fires at the end of the Manager::authorize method when the master user is
4810
	 * authorized.
4811
	 *
4812
	 * @param array $data The request data.
4813
	 */
4814
	public static function authorize_ending_authorized( $data ) {
4815
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4816
		self::invalidate_onboarding_token();
4817
4818
		// If redirect_uri is SSO, ensure SSO module is enabled.
4819
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4820
4821
		/** This filter is documented in class.jetpack-cli.php */
4822
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4823
4824
		$activate_sso = (
4825
			isset( $redirect_options['action'] ) &&
4826
			'jetpack-sso' === $redirect_options['action'] &&
4827
			$jetpack_start_enable_sso
4828
		);
4829
4830
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4831
4832
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4833
	}
4834
4835
	/**
4836
	 * Get our assumed site creation date.
4837
	 * Calculated based on the earlier date of either:
4838
	 * - Earliest admin user registration date.
4839
	 * - Earliest date of post of any post type.
4840
	 *
4841
	 * @since 7.2.0
4842
	 * @deprecated since 7.8.0
4843
	 *
4844
	 * @return string Assumed site creation date and time.
4845
	 */
4846
	public static function get_assumed_site_creation_date() {
4847
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4848
		return self::connection()->get_assumed_site_creation_date();
4849
	}
4850
4851 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4852
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4853
4854
		if ( $activation_source_name ) {
4855
			$args['_as'] = urlencode( $activation_source_name );
4856
		}
4857
4858
		if ( $activation_source_keyword ) {
4859
			$args['_ak'] = urlencode( $activation_source_keyword );
4860
		}
4861
	}
4862
4863
	function build_reconnect_url( $raw = false ) {
4864
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4865
		return $raw ? $url : esc_url( $url );
4866
	}
4867
4868
	public static function admin_url( $args = null ) {
4869
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4870
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4871
		return $url;
4872
	}
4873
4874
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4875
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4876
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4877
	}
4878
4879
	function dismiss_jetpack_notice() {
4880
4881
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4882
			return;
4883
		}
4884
4885
		switch ( $_GET['jetpack-notice'] ) {
4886
			case 'dismiss':
4887
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4888
4889
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4890
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4891
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4892
				}
4893
				break;
4894
		}
4895
	}
4896
4897
	public static function sort_modules( $a, $b ) {
4898
		if ( $a['sort'] == $b['sort'] ) {
4899
			return 0;
4900
		}
4901
4902
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4903
	}
4904
4905
	function ajax_recheck_ssl() {
4906
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4907
		$result = self::permit_ssl( true );
4908
		wp_send_json(
4909
			array(
4910
				'enabled' => $result,
4911
				'message' => get_transient( 'jetpack_https_test_message' ),
4912
			)
4913
		);
4914
	}
4915
4916
	/* Client API */
4917
4918
	/**
4919
	 * Returns the requested Jetpack API URL
4920
	 *
4921
	 * @deprecated since 7.7
4922
	 * @return string
4923
	 */
4924
	public static function api_url( $relative_url ) {
4925
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4926
		$connection = self::connection();
4927
		return $connection->api_url( $relative_url );
4928
	}
4929
4930
	/**
4931
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
4932
	 *
4933
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4934
	 */
4935
	public static function fix_url_for_bad_hosts( $url ) {
4936
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
4937
		return Connection_Utils::fix_url_for_bad_hosts( $url );
4938
	}
4939
4940
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4941
		// Default to a blog token.
4942
		$token_type = 'blog';
4943
4944
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4945
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4946
			if ( ! empty( $_GET['onboarding'] ) ) {
4947
				$jpo = $_GET;
4948
			} else {
4949
				$jpo = json_decode( $request_data, true );
4950
			}
4951
4952
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4953
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4954
4955
			if (
4956
				isset( $jpo_user )
4957
				&& isset( $jpo_token )
4958
				&& is_email( $jpo_user )
4959
				&& ctype_alnum( $jpo_token )
4960
				&& isset( $_GET['rest_route'] )
4961
				&& self::validate_onboarding_token_action(
4962
					$jpo_token,
4963
					$_GET['rest_route']
4964
				)
4965
			) {
4966
				$jp_user = get_user_by( 'email', $jpo_user );
4967
				if ( is_a( $jp_user, 'WP_User' ) ) {
4968
					wp_set_current_user( $jp_user->ID );
4969
					$user_can = is_multisite()
4970
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4971
						: current_user_can( 'manage_options' );
4972
					if ( $user_can ) {
4973
						$token_type              = 'user';
4974
						$token->external_user_id = $jp_user->ID;
4975
					}
4976
				}
4977
			}
4978
4979
			$token_data['type']    = $token_type;
4980
			$token_data['user_id'] = $token->external_user_id;
4981
		}
4982
4983
		return $token_data;
4984
	}
4985
4986
	/**
4987
	 * Create a random secret for validating onboarding payload
4988
	 *
4989
	 * @return string Secret token
4990
	 */
4991
	public static function create_onboarding_token() {
4992
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4993
			$token = wp_generate_password( 32, false );
4994
			Jetpack_Options::update_option( 'onboarding', $token );
4995
		}
4996
4997
		return $token;
4998
	}
4999
5000
	/**
5001
	 * Remove the onboarding token
5002
	 *
5003
	 * @return bool True on success, false on failure
5004
	 */
5005
	public static function invalidate_onboarding_token() {
5006
		return Jetpack_Options::delete_option( 'onboarding' );
5007
	}
5008
5009
	/**
5010
	 * Validate an onboarding token for a specific action
5011
	 *
5012
	 * @return boolean True if token/action pair is accepted, false if not
5013
	 */
5014
	public static function validate_onboarding_token_action( $token, $action ) {
5015
		// Compare tokens, bail if tokens do not match
5016
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5017
			return false;
5018
		}
5019
5020
		// List of valid actions we can take
5021
		$valid_actions = array(
5022
			'/jetpack/v4/settings',
5023
		);
5024
5025
		// Whitelist the action
5026
		if ( ! in_array( $action, $valid_actions ) ) {
5027
			return false;
5028
		}
5029
5030
		return true;
5031
	}
5032
5033
	/**
5034
	 * Checks to see if the URL is using SSL to connect with Jetpack
5035
	 *
5036
	 * @since 2.3.3
5037
	 * @return boolean
5038
	 */
5039
	public static function permit_ssl( $force_recheck = false ) {
5040
		// Do some fancy tests to see if ssl is being supported
5041
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5042
			$message = '';
5043
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5044
				$ssl = 0;
5045
			} else {
5046
				switch ( JETPACK_CLIENT__HTTPS ) {
5047
					case 'NEVER':
5048
						$ssl     = 0;
5049
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5050
						break;
5051
					case 'ALWAYS':
5052
					case 'AUTO':
5053
					default:
5054
						$ssl = 1;
5055
						break;
5056
				}
5057
5058
				// If it's not 'NEVER', test to see
5059
				if ( $ssl ) {
5060
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5061
						$ssl     = 0;
5062
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5063
					} else {
5064
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5065
						if ( is_wp_error( $response ) ) {
5066
							$ssl     = 0;
5067
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5068
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5069
							$ssl     = 0;
5070
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5071
						}
5072
					}
5073
				}
5074
			}
5075
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5076
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5077
		}
5078
5079
		return (bool) $ssl;
5080
	}
5081
5082
	/*
5083
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5084
	 */
5085
	public function alert_auto_ssl_fail() {
5086
		if ( ! current_user_can( 'manage_options' ) ) {
5087
			return;
5088
		}
5089
5090
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5091
		?>
5092
5093
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5094
			<div class="jp-banner__content">
5095
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5096
				<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>
5097
				<p>
5098
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5099
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5100
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5101
				</p>
5102
				<p>
5103
					<?php
5104
					printf(
5105
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5106
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5107
						esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' )
5108
					);
5109
					?>
5110
				</p>
5111
			</div>
5112
		</div>
5113
		<style>
5114
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5115
		</style>
5116
		<script type="text/javascript">
5117
			jQuery( document ).ready( function( $ ) {
5118
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5119
					var $this = $( this );
5120
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5121
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5122
					e.preventDefault();
5123
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5124
					$.post( ajaxurl, data )
5125
					  .done( function( response ) {
5126
						  if ( response.enabled ) {
5127
							  $( '#jetpack-ssl-warning' ).hide();
5128
						  } else {
5129
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5130
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5131
						  }
5132
					  }.bind( $this ) );
5133
				} );
5134
			} );
5135
		</script>
5136
5137
		<?php
5138
	}
5139
5140
	/**
5141
	 * Returns the Jetpack XML-RPC API
5142
	 *
5143
	 * @deprecated 8.0 Use Connection_Manager instead.
5144
	 * @return string
5145
	 */
5146
	public static function xmlrpc_api_url() {
5147
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5148
		return self::connection()->xmlrpc_api_url();
5149
	}
5150
5151
	/**
5152
	 * Returns the connection manager object.
5153
	 *
5154
	 * @return Automattic\Jetpack\Connection\Manager
5155
	 */
5156
	public static function connection() {
5157
		return self::init()->connection_manager;
5158
	}
5159
5160
	/**
5161
	 * Creates two secret tokens and the end of life timestamp for them.
5162
	 *
5163
	 * Note these tokens are unique per call, NOT static per site for connecting.
5164
	 *
5165
	 * @since 2.6
5166
	 * @param String  $action  The action name.
5167
	 * @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...
5168
	 * @param Integer $exp     Expiration time in seconds.
5169
	 * @return array
5170
	 */
5171
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5172
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5173
	}
5174
5175
	public static function get_secrets( $action, $user_id ) {
5176
		$secrets = self::connection()->get_secrets( $action, $user_id );
5177
5178
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5179
			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...
5180
		}
5181
5182
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5183
			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...
5184
		}
5185
5186
		return $secrets;
5187
	}
5188
5189
	/**
5190
	 * @deprecated 7.5 Use Connection_Manager instead.
5191
	 *
5192
	 * @param $action
5193
	 * @param $user_id
5194
	 */
5195
	public static function delete_secrets( $action, $user_id ) {
5196
		return self::connection()->delete_secrets( $action, $user_id );
5197
	}
5198
5199
	/**
5200
	 * Builds the timeout limit for queries talking with the wpcom servers.
5201
	 *
5202
	 * Based on local php max_execution_time in php.ini
5203
	 *
5204
	 * @since 2.6
5205
	 * @return int
5206
	 * @deprecated
5207
	 **/
5208
	public function get_remote_query_timeout_limit() {
5209
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5210
		return self::get_max_execution_time();
5211
	}
5212
5213
	/**
5214
	 * Builds the timeout limit for queries talking with the wpcom servers.
5215
	 *
5216
	 * Based on local php max_execution_time in php.ini
5217
	 *
5218
	 * @since 5.4
5219
	 * @return int
5220
	 **/
5221
	public static function get_max_execution_time() {
5222
		$timeout = (int) ini_get( 'max_execution_time' );
5223
5224
		// Ensure exec time set in php.ini
5225
		if ( ! $timeout ) {
5226
			$timeout = 30;
5227
		}
5228
		return $timeout;
5229
	}
5230
5231
	/**
5232
	 * Sets a minimum request timeout, and returns the current timeout
5233
	 *
5234
	 * @since 5.4
5235
	 **/
5236 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5237
		$timeout = self::get_max_execution_time();
5238
		if ( $timeout < $min_timeout ) {
5239
			$timeout = $min_timeout;
5240
			set_time_limit( $timeout );
5241
		}
5242
		return $timeout;
5243
	}
5244
5245
	/**
5246
	 * Takes the response from the Jetpack register new site endpoint and
5247
	 * verifies it worked properly.
5248
	 *
5249
	 * @since 2.6
5250
	 * @deprecated since 7.7.0
5251
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5252
	 **/
5253
	public function validate_remote_register_response() {
5254
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5255
	}
5256
5257
	/**
5258
	 * @return bool|WP_Error
5259
	 */
5260
	public static function register() {
5261
		$tracking = new Tracking();
5262
		$tracking->record_user_event( 'jpc_register_begin' );
5263
5264
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5265
5266
		$connection   = self::connection();
5267
		$registration = $connection->register();
5268
5269
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5270
5271
		if ( ! $registration || is_wp_error( $registration ) ) {
5272
			return $registration;
5273
		}
5274
5275
		return true;
5276
	}
5277
5278
	/**
5279
	 * Filters the registration request body to include tracking properties.
5280
	 *
5281
	 * @param Array $properties
5282
	 * @return Array amended properties.
5283
	 */
5284 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5285
		$tracking        = new Tracking();
5286
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5287
5288
		return array_merge(
5289
			$properties,
5290
			array(
5291
				'_ui' => $tracks_identity['_ui'],
5292
				'_ut' => $tracks_identity['_ut'],
5293
			)
5294
		);
5295
	}
5296
5297
	/**
5298
	 * Filters the token request body to include tracking properties.
5299
	 *
5300
	 * @param Array $properties
5301
	 * @return Array amended properties.
5302
	 */
5303 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5304
		$tracking        = new Tracking();
5305
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5306
5307
		return array_merge(
5308
			$properties,
5309
			array(
5310
				'_ui' => $tracks_identity['_ui'],
5311
				'_ut' => $tracks_identity['_ut'],
5312
			)
5313
		);
5314
	}
5315
5316
	/**
5317
	 * If the db version is showing something other that what we've got now, bump it to current.
5318
	 *
5319
	 * @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...
5320
	 */
5321
	public static function maybe_set_version_option() {
5322
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5323
		if ( JETPACK__VERSION != $version ) {
5324
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5325
5326
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5327
				/** This action is documented in class.jetpack.php */
5328
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5329
			}
5330
5331
			return true;
5332
		}
5333
		return false;
5334
	}
5335
5336
	/* Client Server API */
5337
5338
	/**
5339
	 * Loads the Jetpack XML-RPC client.
5340
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5341
	 *
5342
	 * @deprecated since 7.7.0
5343
	 */
5344
	public static function load_xml_rpc_client() {
5345
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5346
	}
5347
5348
	/**
5349
	 * Resets the saved authentication state in between testing requests.
5350
	 */
5351
	public function reset_saved_auth_state() {
5352
		$this->rest_authentication_status = null;
5353
		$this->connection_manager->reset_saved_auth_state();
5354
	}
5355
5356
	/**
5357
	 * Verifies the signature of the current request.
5358
	 *
5359
	 * @deprecated since 7.7.0
5360
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5361
	 *
5362
	 * @return false|array
5363
	 */
5364
	public function verify_xml_rpc_signature() {
5365
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5366
		return self::connection()->verify_xml_rpc_signature();
5367
	}
5368
5369
	/**
5370
	 * Verifies the signature of the current request.
5371
	 *
5372
	 * This function has side effects and should not be used. Instead,
5373
	 * use the memoized version `->verify_xml_rpc_signature()`.
5374
	 *
5375
	 * @deprecated since 7.7.0
5376
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5377
	 * @internal
5378
	 */
5379
	private function internal_verify_xml_rpc_signature() {
5380
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5381
	}
5382
5383
	/**
5384
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5385
	 *
5386
	 * @deprecated since 7.7.0
5387
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5388
	 *
5389
	 * @param \WP_User|mixed $user     User object if authenticated.
5390
	 * @param string         $username Username.
5391
	 * @param string         $password Password string.
5392
	 * @return \WP_User|mixed Authenticated user or error.
5393
	 */
5394
	public function authenticate_jetpack( $user, $username, $password ) {
5395
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5396
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5397
	}
5398
5399
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5400
	// Uses the existing XMLRPC request signing implementation.
5401
	function wp_rest_authenticate( $user ) {
5402
		if ( ! empty( $user ) ) {
5403
			// Another authentication method is in effect.
5404
			return $user;
5405
		}
5406
5407
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5408
			// Nothing to do for this authentication method.
5409
			return null;
5410
		}
5411
5412
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5413
			// Nothing to do for this authentication method.
5414
			return null;
5415
		}
5416
5417
		// Ensure that we always have the request body available.  At this
5418
		// point, the WP REST API code to determine the request body has not
5419
		// run yet.  That code may try to read from 'php://input' later, but
5420
		// this can only be done once per request in PHP versions prior to 5.6.
5421
		// So we will go ahead and perform this read now if needed, and save
5422
		// the request body where both the Jetpack signature verification code
5423
		// and the WP REST API code can see it.
5424
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5425
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5426
		}
5427
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5428
5429
		// Only support specific request parameters that have been tested and
5430
		// are known to work with signature verification.  A different method
5431
		// can be passed to the WP REST API via the '?_method=' parameter if
5432
		// needed.
5433
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5434
			$this->rest_authentication_status = new WP_Error(
5435
				'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...
5436
				__( 'This request method is not supported.', 'jetpack' ),
5437
				array( 'status' => 400 )
5438
			);
5439
			return null;
5440
		}
5441
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5442
			$this->rest_authentication_status = new WP_Error(
5443
				'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...
5444
				__( 'This request method does not support body parameters.', 'jetpack' ),
5445
				array( 'status' => 400 )
5446
			);
5447
			return null;
5448
		}
5449
5450
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5451
5452
		if (
5453
			$verified &&
5454
			isset( $verified['type'] ) &&
5455
			'user' === $verified['type'] &&
5456
			! empty( $verified['user_id'] )
5457
		) {
5458
			// Authentication successful.
5459
			$this->rest_authentication_status = true;
5460
			return $verified['user_id'];
5461
		}
5462
5463
		// Something else went wrong.  Probably a signature error.
5464
		$this->rest_authentication_status = new WP_Error(
5465
			'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...
5466
			__( 'The request is not signed correctly.', 'jetpack' ),
5467
			array( 'status' => 400 )
5468
		);
5469
		return null;
5470
	}
5471
5472
	/**
5473
	 * Report authentication status to the WP REST API.
5474
	 *
5475
	 * @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...
5476
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5477
	 */
5478
	public function wp_rest_authentication_errors( $value ) {
5479
		if ( $value !== null ) {
5480
			return $value;
5481
		}
5482
		return $this->rest_authentication_status;
5483
	}
5484
5485
	/**
5486
	 * Add our nonce to this request.
5487
	 *
5488
	 * @deprecated since 7.7.0
5489
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5490
	 *
5491
	 * @param int    $timestamp Timestamp of the request.
5492
	 * @param string $nonce     Nonce string.
5493
	 */
5494
	public function add_nonce( $timestamp, $nonce ) {
5495
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5496
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5497
	}
5498
5499
	/**
5500
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5501
	 * Capture it here so we can verify the signature later.
5502
	 *
5503
	 * @deprecated since 7.7.0
5504
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5505
	 *
5506
	 * @param array $methods XMLRPC methods.
5507
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5508
	 */
5509
	public function xmlrpc_methods( $methods ) {
5510
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5511
		return $this->connection_manager->xmlrpc_methods( $methods );
5512
	}
5513
5514
	/**
5515
	 * Register additional public XMLRPC methods.
5516
	 *
5517
	 * @deprecated since 7.7.0
5518
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5519
	 *
5520
	 * @param array $methods Public XMLRPC methods.
5521
	 * @return array Public XMLRPC methods, with the getOptions one.
5522
	 */
5523
	public function public_xmlrpc_methods( $methods ) {
5524
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5525
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5526
	}
5527
5528
	/**
5529
	 * Handles a getOptions XMLRPC method call.
5530
	 *
5531
	 * @deprecated since 7.7.0
5532
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5533
	 *
5534
	 * @param array $args method call arguments.
5535
	 * @return array an amended XMLRPC server options array.
5536
	 */
5537
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5538
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5539
		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...
5540
	}
5541
5542
	/**
5543
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5544
	 *
5545
	 * @deprecated since 7.7.0
5546
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5547
	 *
5548
	 * @param array $options Standard Core options.
5549
	 * @return array Amended options.
5550
	 */
5551
	public function xmlrpc_options( $options ) {
5552
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5553
		return $this->connection_manager->xmlrpc_options( $options );
5554
	}
5555
5556
	/**
5557
	 * Cleans nonces that were saved when calling ::add_nonce.
5558
	 *
5559
	 * @deprecated since 7.7.0
5560
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5561
	 *
5562
	 * @param bool $all whether to clean even non-expired nonces.
5563
	 */
5564
	public static function clean_nonces( $all = false ) {
5565
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5566
		return self::connection()->clean_nonces( $all );
5567
	}
5568
5569
	/**
5570
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5571
	 * SET: state( $key, $value );
5572
	 * GET: $value = state( $key );
5573
	 *
5574
	 * @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...
5575
	 * @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...
5576
	 * @param bool   $restate private
5577
	 */
5578
	public static function state( $key = null, $value = null, $restate = false ) {
5579
		static $state = array();
5580
		static $path, $domain;
5581
		if ( ! isset( $path ) ) {
5582
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5583
			$admin_url = self::admin_url();
5584
			$bits      = wp_parse_url( $admin_url );
5585
5586
			if ( is_array( $bits ) ) {
5587
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5588
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5589
			} else {
5590
				$path = $domain = null;
5591
			}
5592
		}
5593
5594
		// Extract state from cookies and delete cookies
5595
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5596
			$yum = $_COOKIE['jetpackState'];
5597
			unset( $_COOKIE['jetpackState'] );
5598
			foreach ( $yum as $k => $v ) {
5599
				if ( strlen( $v ) ) {
5600
					$state[ $k ] = $v;
5601
				}
5602
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5603
			}
5604
		}
5605
5606
		if ( $restate ) {
5607
			foreach ( $state as $k => $v ) {
5608
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5609
			}
5610
			return;
5611
		}
5612
5613
		// Get a state variable
5614
		if ( isset( $key ) && ! isset( $value ) ) {
5615
			if ( array_key_exists( $key, $state ) ) {
5616
				return $state[ $key ];
5617
			}
5618
			return null;
5619
		}
5620
5621
		// Set a state variable
5622
		if ( isset( $key ) && isset( $value ) ) {
5623
			if ( is_array( $value ) && isset( $value[0] ) ) {
5624
				$value = $value[0];
5625
			}
5626
			$state[ $key ] = $value;
5627
			if ( ! headers_sent() ) {
5628
				setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5629
			}
5630
		}
5631
	}
5632
5633
	public static function restate() {
5634
		self::state( null, null, true );
5635
	}
5636
5637
	public static function check_privacy( $file ) {
5638
		static $is_site_publicly_accessible = null;
5639
5640
		if ( is_null( $is_site_publicly_accessible ) ) {
5641
			$is_site_publicly_accessible = false;
5642
5643
			$rpc = new Jetpack_IXR_Client();
5644
5645
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5646
			if ( $success ) {
5647
				$response = $rpc->getResponse();
5648
				if ( $response ) {
5649
					$is_site_publicly_accessible = true;
5650
				}
5651
			}
5652
5653
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5654
		}
5655
5656
		if ( $is_site_publicly_accessible ) {
5657
			return;
5658
		}
5659
5660
		$module_slug = self::get_module_slug( $file );
5661
5662
		$privacy_checks = self::state( 'privacy_checks' );
5663
		if ( ! $privacy_checks ) {
5664
			$privacy_checks = $module_slug;
5665
		} else {
5666
			$privacy_checks .= ",$module_slug";
5667
		}
5668
5669
		self::state( 'privacy_checks', $privacy_checks );
5670
	}
5671
5672
	/**
5673
	 * Helper method for multicall XMLRPC.
5674
	 *
5675
	 * @param ...$args Args for the async_call.
5676
	 */
5677
	public static function xmlrpc_async_call( ...$args ) {
5678
		global $blog_id;
5679
		static $clients = array();
5680
5681
		$client_blog_id = is_multisite() ? $blog_id : 0;
5682
5683
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5684
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5685
			if ( function_exists( 'ignore_user_abort' ) ) {
5686
				ignore_user_abort( true );
5687
			}
5688
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5689
		}
5690
5691
		if ( ! empty( $args[0] ) ) {
5692
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5693
		} elseif ( is_multisite() ) {
5694
			foreach ( $clients as $client_blog_id => $client ) {
5695
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5696
					continue;
5697
				}
5698
5699
				$switch_success = switch_to_blog( $client_blog_id, true );
5700
				if ( ! $switch_success ) {
5701
					continue;
5702
				}
5703
5704
				flush();
5705
				$client->query();
5706
5707
				restore_current_blog();
5708
			}
5709
		} else {
5710
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5711
				flush();
5712
				$clients[0]->query();
5713
			}
5714
		}
5715
	}
5716
5717
	public static function staticize_subdomain( $url ) {
5718
5719
		// Extract hostname from URL
5720
		$host = wp_parse_url( $url, PHP_URL_HOST );
5721
5722
		// Explode hostname on '.'
5723
		$exploded_host = explode( '.', $host );
5724
5725
		// Retrieve the name and TLD
5726
		if ( count( $exploded_host ) > 1 ) {
5727
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5728
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5729
			// Rebuild domain excluding subdomains
5730
			$domain = $name . '.' . $tld;
5731
		} else {
5732
			$domain = $host;
5733
		}
5734
		// Array of Automattic domains
5735
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5736
5737
		// Return $url if not an Automattic domain
5738
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5739
			return $url;
5740
		}
5741
5742
		if ( is_ssl() ) {
5743
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5744
		}
5745
5746
		srand( crc32( basename( $url ) ) );
5747
		$static_counter = rand( 0, 2 );
5748
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5749
5750
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5751
	}
5752
5753
	/* JSON API Authorization */
5754
5755
	/**
5756
	 * Handles the login action for Authorizing the JSON API
5757
	 */
5758
	function login_form_json_api_authorization() {
5759
		$this->verify_json_api_authorization_request();
5760
5761
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5762
5763
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5764
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5765
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5766
	}
5767
5768
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5769
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5770
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5771
			return $url;
5772
		}
5773
5774
		$parsed_url = wp_parse_url( $url );
5775
		$url        = strtok( $url, '?' );
5776
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5777
		if ( ! empty( $parsed_url['query'] ) ) {
5778
			$url .= "&{$parsed_url['query']}";
5779
		}
5780
5781
		return $url;
5782
	}
5783
5784
	// Make sure the POSTed request is handled by the same action
5785
	function preserve_action_in_login_form_for_json_api_authorization() {
5786
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5787
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5788
	}
5789
5790
	// If someone logs in to approve API access, store the Access Code in usermeta
5791
	function store_json_api_authorization_token( $user_login, $user ) {
5792
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5793
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5794
		$token = wp_generate_password( 32, false );
5795
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5796
	}
5797
5798
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5799
	function allow_wpcom_public_api_domain( $domains ) {
5800
		$domains[] = 'public-api.wordpress.com';
5801
		return $domains;
5802
	}
5803
5804
	static function is_redirect_encoded( $redirect_url ) {
5805
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5806
	}
5807
5808
	// Add all wordpress.com environments to the safe redirect whitelist
5809
	function allow_wpcom_environments( $domains ) {
5810
		$domains[] = 'wordpress.com';
5811
		$domains[] = 'wpcalypso.wordpress.com';
5812
		$domains[] = 'horizon.wordpress.com';
5813
		$domains[] = 'calypso.localhost';
5814
		return $domains;
5815
	}
5816
5817
	// Add the Access Code details to the public-api.wordpress.com redirect
5818
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5819
		return add_query_arg(
5820
			urlencode_deep(
5821
				array(
5822
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5823
					'jetpack-user-id' => (int) $user->ID,
5824
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5825
				)
5826
			),
5827
			$redirect_to
5828
		);
5829
	}
5830
5831
5832
	/**
5833
	 * Verifies the request by checking the signature
5834
	 *
5835
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5836
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5837
	 *
5838
	 * @param null|array $environment
5839
	 */
5840
	function verify_json_api_authorization_request( $environment = null ) {
5841
		$environment = is_null( $environment )
5842
			? $_REQUEST
5843
			: $environment;
5844
5845
		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...
5846
		$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...
5847
		if ( ! $token || empty( $token->secret ) ) {
5848
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5849
		}
5850
5851
		$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' );
5852
5853
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5854
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5855
			/**
5856
			 * Jetpack authorisation request Error.
5857
			 *
5858
			 * @since 7.5.0
5859
			 */
5860
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5861
			$die_error = sprintf(
5862
				/* translators: %s is a URL */
5863
				__( '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' ),
5864
				'https://jetpack.com/support/double-encoding/'
5865
			);
5866
		}
5867
5868
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5869
5870
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5871
			$signature = $jetpack_signature->sign_request(
5872
				$environment['token'],
5873
				$environment['timestamp'],
5874
				$environment['nonce'],
5875
				'',
5876
				'GET',
5877
				$environment['jetpack_json_api_original_query'],
5878
				null,
5879
				true
5880
			);
5881
		} else {
5882
			$signature = $jetpack_signature->sign_current_request(
5883
				array(
5884
					'body'   => null,
5885
					'method' => 'GET',
5886
				)
5887
			);
5888
		}
5889
5890
		if ( ! $signature ) {
5891
			wp_die( $die_error );
5892
		} elseif ( is_wp_error( $signature ) ) {
5893
			wp_die( $die_error );
5894
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5895
			if ( is_ssl() ) {
5896
				// 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
5897
				$signature = $jetpack_signature->sign_current_request(
5898
					array(
5899
						'scheme' => 'http',
5900
						'body'   => null,
5901
						'method' => 'GET',
5902
					)
5903
				);
5904
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5905
					wp_die( $die_error );
5906
				}
5907
			} else {
5908
				wp_die( $die_error );
5909
			}
5910
		}
5911
5912
		$timestamp = (int) $environment['timestamp'];
5913
		$nonce     = stripslashes( (string) $environment['nonce'] );
5914
5915
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5916
			// De-nonce the nonce, at least for 5 minutes.
5917
			// 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)
5918
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5919
			if ( $old_nonce_time < time() - 300 ) {
5920
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5921
			}
5922
		}
5923
5924
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5925
		$data_filters = array(
5926
			'state'        => 'opaque',
5927
			'client_id'    => 'int',
5928
			'client_title' => 'string',
5929
			'client_image' => 'url',
5930
		);
5931
5932
		foreach ( $data_filters as $key => $sanitation ) {
5933
			if ( ! isset( $data->$key ) ) {
5934
				wp_die( $die_error );
5935
			}
5936
5937
			switch ( $sanitation ) {
5938
				case 'int':
5939
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
5940
					break;
5941
				case 'opaque':
5942
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
5943
					break;
5944
				case 'string':
5945
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
5946
					break;
5947
				case 'url':
5948
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
5949
					break;
5950
			}
5951
		}
5952
5953
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5954
			wp_die( $die_error );
5955
		}
5956
	}
5957
5958
	function login_message_json_api_authorization( $message ) {
5959
		return '<p class="message">' . sprintf(
5960
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
5961
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5962
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5963
	}
5964
5965
	/**
5966
	 * Get $content_width, but with a <s>twist</s> filter.
5967
	 */
5968
	public static function get_content_width() {
5969
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5970
			? $GLOBALS['content_width']
5971
			: false;
5972
		/**
5973
		 * Filter the Content Width value.
5974
		 *
5975
		 * @since 2.2.3
5976
		 *
5977
		 * @param string $content_width Content Width value.
5978
		 */
5979
		return apply_filters( 'jetpack_content_width', $content_width );
5980
	}
5981
5982
	/**
5983
	 * Pings the WordPress.com Mirror Site for the specified options.
5984
	 *
5985
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5986
	 *
5987
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5988
	 */
5989
	public function get_cloud_site_options( $option_names ) {
5990
		$option_names = array_filter( (array) $option_names, 'is_string' );
5991
5992
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
5993
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5994
		if ( $xml->isError() ) {
5995
			return array(
5996
				'error_code' => $xml->getErrorCode(),
5997
				'error_msg'  => $xml->getErrorMessage(),
5998
			);
5999
		}
6000
		$cloud_site_options = $xml->getResponse();
6001
6002
		return $cloud_site_options;
6003
	}
6004
6005
	/**
6006
	 * Checks if the site is currently in an identity crisis.
6007
	 *
6008
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6009
	 */
6010
	public static function check_identity_crisis() {
6011
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6012
			return false;
6013
		}
6014
6015
		return Jetpack_Options::get_option( 'sync_error_idc' );
6016
	}
6017
6018
	/**
6019
	 * Checks whether the home and siteurl specifically are whitelisted
6020
	 * Written so that we don't have re-check $key and $value params every time
6021
	 * we want to check if this site is whitelisted, for example in footer.php
6022
	 *
6023
	 * @since  3.8.0
6024
	 * @return bool True = already whitelisted False = not whitelisted
6025
	 */
6026
	public static function is_staging_site() {
6027
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6028
		return ( new Status() )->is_staging_site();
6029
	}
6030
6031
	/**
6032
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6033
	 *
6034
	 * @since 4.4.0
6035
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6036
	 *
6037
	 * @return bool
6038
	 */
6039
	public static function validate_sync_error_idc_option() {
6040
		$is_valid = false;
6041
6042
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6043
		if ( false === $idc_allowed ) {
6044
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6045
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6046
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6047
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6048
				$transient_duration = HOUR_IN_SECONDS;
6049
			} else {
6050
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6051
				$idc_allowed        = '1';
6052
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6053
			}
6054
6055
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6056
		}
6057
6058
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6059
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6060
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6061
			$local_options = self::get_sync_error_idc_option();
6062
			// Ensure all values are set.
6063
			if ( isset( $sync_error['home'] ) && isset ( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6064
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6065
					$is_valid = true;
6066
				}
6067
			}
6068
6069
		}
6070
6071
		/**
6072
		 * Filters whether the sync_error_idc option is valid.
6073
		 *
6074
		 * @since 4.4.0
6075
		 *
6076
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6077
		 */
6078
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6079
6080
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6081
			// Since the option exists, and did not validate, delete it
6082
			Jetpack_Options::delete_option( 'sync_error_idc' );
6083
		}
6084
6085
		return $is_valid;
6086
	}
6087
6088
	/**
6089
	 * Normalizes a url by doing three things:
6090
	 *  - Strips protocol
6091
	 *  - Strips www
6092
	 *  - Adds a trailing slash
6093
	 *
6094
	 * @since 4.4.0
6095
	 * @param string $url
6096
	 * @return WP_Error|string
6097
	 */
6098
	public static function normalize_url_protocol_agnostic( $url ) {
6099
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6100
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6101
			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...
6102
		}
6103
6104
		// Strip www and protocols
6105
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6106
		return $url;
6107
	}
6108
6109
	/**
6110
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6111
	 *
6112
	 * @since 4.4.0
6113
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6114
	 *
6115
	 * @param array $response
6116
	 * @return array Array of the local urls, wpcom urls, and error code
6117
	 */
6118
	public static function get_sync_error_idc_option( $response = array() ) {
6119
		// Since the local options will hit the database directly, store the values
6120
		// in a transient to allow for autoloading and caching on subsequent views.
6121
		$local_options = get_transient( 'jetpack_idc_local' );
6122
		if ( false === $local_options ) {
6123
			$local_options = array(
6124
				'home'    => Functions::home_url(),
6125
				'siteurl' => Functions::site_url(),
6126
			);
6127
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6128
		}
6129
6130
		$options = array_merge( $local_options, $response );
6131
6132
		$returned_values = array();
6133
		foreach ( $options as $key => $option ) {
6134
			if ( 'error_code' === $key ) {
6135
				$returned_values[ $key ] = $option;
6136
				continue;
6137
			}
6138
6139
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6140
				continue;
6141
			}
6142
6143
			$returned_values[ $key ] = $normalized_url;
6144
		}
6145
6146
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6147
6148
		return $returned_values;
6149
	}
6150
6151
	/**
6152
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6153
	 * If set to true, the site will be put into staging mode.
6154
	 *
6155
	 * @since 4.3.2
6156
	 * @return bool
6157
	 */
6158
	public static function sync_idc_optin() {
6159
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6160
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6161
		} else {
6162
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6163
		}
6164
6165
		/**
6166
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6167
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6168
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6169
		 *
6170
		 * @since 4.3.2
6171
		 *
6172
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6173
		 */
6174
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6175
	}
6176
6177
	/**
6178
	 * Maybe Use a .min.css stylesheet, maybe not.
6179
	 *
6180
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6181
	 */
6182
	public static function maybe_min_asset( $url, $path, $plugin ) {
6183
		// Short out on things trying to find actual paths.
6184
		if ( ! $path || empty( $plugin ) ) {
6185
			return $url;
6186
		}
6187
6188
		$path = ltrim( $path, '/' );
6189
6190
		// Strip out the abspath.
6191
		$base = dirname( plugin_basename( $plugin ) );
6192
6193
		// Short out on non-Jetpack assets.
6194
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6195
			return $url;
6196
		}
6197
6198
		// File name parsing.
6199
		$file              = "{$base}/{$path}";
6200
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6201
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6202
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6203
		$extension         = array_shift( $file_name_parts_r );
6204
6205
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6206
			// Already pointing at the minified version.
6207
			if ( 'min' === $file_name_parts_r[0] ) {
6208
				return $url;
6209
			}
6210
6211
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6212
			if ( file_exists( $min_full_path ) ) {
6213
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6214
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6215
				if ( 'css' === $extension ) {
6216
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6217
					self::$min_assets[ $key ] = $path;
6218
				}
6219
			}
6220
		}
6221
6222
		return $url;
6223
	}
6224
6225
	/**
6226
	 * If the asset is minified, let's flag .min as the suffix.
6227
	 *
6228
	 * Attached to `style_loader_src` filter.
6229
	 *
6230
	 * @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...
6231
	 * @param string $handle The registered handle of the script in question.
6232
	 * @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...
6233
	 */
6234
	public static function set_suffix_on_min( $src, $handle ) {
6235
		if ( false === strpos( $src, '.min.css' ) ) {
6236
			return $src;
6237
		}
6238
6239
		if ( ! empty( self::$min_assets ) ) {
6240
			foreach ( self::$min_assets as $file => $path ) {
6241
				if ( false !== strpos( $src, $file ) ) {
6242
					wp_style_add_data( $handle, 'suffix', '.min' );
6243
					return $src;
6244
				}
6245
			}
6246
		}
6247
6248
		return $src;
6249
	}
6250
6251
	/**
6252
	 * Maybe inlines a stylesheet.
6253
	 *
6254
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6255
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6256
	 *
6257
	 * Attached to `style_loader_tag` filter.
6258
	 *
6259
	 * @param string $tag The tag that would link to the external asset.
6260
	 * @param string $handle The registered handle of the script in question.
6261
	 *
6262
	 * @return string
6263
	 */
6264
	public static function maybe_inline_style( $tag, $handle ) {
6265
		global $wp_styles;
6266
		$item = $wp_styles->registered[ $handle ];
6267
6268
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6269
			return $tag;
6270
		}
6271
6272
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6273
			$href = $matches[1];
6274
			// Strip off query string
6275
			if ( $pos = strpos( $href, '?' ) ) {
6276
				$href = substr( $href, 0, $pos );
6277
			}
6278
			// Strip off fragment
6279
			if ( $pos = strpos( $href, '#' ) ) {
6280
				$href = substr( $href, 0, $pos );
6281
			}
6282
		} else {
6283
			return $tag;
6284
		}
6285
6286
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6287
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6288
			return $tag;
6289
		}
6290
6291
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6292
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6293
			// And this isn't the pass that actually deals with the RTL version...
6294
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6295
				// Short out, as the RTL version will deal with it in a moment.
6296
				return $tag;
6297
			}
6298
		}
6299
6300
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6301
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6302
		if ( $css ) {
6303
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6304
			if ( empty( $item->extra['after'] ) ) {
6305
				wp_add_inline_style( $handle, $css );
6306
			} else {
6307
				array_unshift( $item->extra['after'], $css );
6308
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6309
			}
6310
		}
6311
6312
		return $tag;
6313
	}
6314
6315
	/**
6316
	 * Loads a view file from the views
6317
	 *
6318
	 * Data passed in with the $data parameter will be available in the
6319
	 * template file as $data['value']
6320
	 *
6321
	 * @param string $template - Template file to load
6322
	 * @param array  $data - Any data to pass along to the template
6323
	 * @return boolean - If template file was found
6324
	 **/
6325
	public function load_view( $template, $data = array() ) {
6326
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6327
6328
		if ( file_exists( $views_dir . $template ) ) {
6329
			require_once $views_dir . $template;
6330
			return true;
6331
		}
6332
6333
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6334
		return false;
6335
	}
6336
6337
	/**
6338
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6339
	 */
6340
	public function deprecated_hooks() {
6341
		global $wp_filter;
6342
6343
		/*
6344
		 * Format:
6345
		 * deprecated_filter_name => replacement_name
6346
		 *
6347
		 * If there is no replacement, use null for replacement_name
6348
		 */
6349
		$deprecated_list = array(
6350
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6351
			'wpl_sharing_2014_1'                           => null,
6352
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6353
			'jetpack_identity_crisis_options_to_check'     => null,
6354
			'update_option_jetpack_single_user_site'       => null,
6355
			'audio_player_default_colors'                  => null,
6356
			'add_option_jetpack_featured_images_enabled'   => null,
6357
			'add_option_jetpack_update_details'            => null,
6358
			'add_option_jetpack_updates'                   => null,
6359
			'add_option_jetpack_network_name'              => null,
6360
			'add_option_jetpack_network_allow_new_registrations' => null,
6361
			'add_option_jetpack_network_add_new_users'     => null,
6362
			'add_option_jetpack_network_site_upload_space' => null,
6363
			'add_option_jetpack_network_upload_file_types' => null,
6364
			'add_option_jetpack_network_enable_administration_menus' => null,
6365
			'add_option_jetpack_is_multi_site'             => null,
6366
			'add_option_jetpack_is_main_network'           => null,
6367
			'add_option_jetpack_main_network_site'         => null,
6368
			'jetpack_sync_all_registered_options'          => null,
6369
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6370
			'jetpack_is_post_mailable'                     => null,
6371
			'jetpack_seo_site_host'                        => null,
6372
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6373
			'jetpack_holiday_snow_option_name'             => null,
6374
			'jetpack_holiday_chance_of_snow'               => null,
6375
			'jetpack_holiday_snow_js_url'                  => null,
6376
			'jetpack_is_holiday_snow_season'               => null,
6377
			'jetpack_holiday_snow_option_updated'          => null,
6378
			'jetpack_holiday_snowing'                      => null,
6379
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6380
			'jetpack_cache_plans'                          => null,
6381
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6382
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6383
			'jetpack_enable_site_verification'             => null,
6384
			'can_display_jetpack_manage_notice'            => null,
6385
			// Removed in Jetpack 7.3.0
6386
			'atd_load_scripts'                             => null,
6387
			'atd_http_post_timeout'                        => null,
6388
			'atd_http_post_error'                          => null,
6389
			'atd_service_domain'                           => null,
6390
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6391
			// Removed in Jetpack 7.9.0
6392
			'jetpack_pwa_manifest'                         => null,
6393
			'jetpack_pwa_background_color'                 => null,
6394
			// Removed in Jetpack 8.3.0.
6395
			'jetpack_check_mobile'                         => null,
6396
			'jetpack_mobile_stylesheet'                    => null,
6397
			'jetpack_mobile_template'                      => null,
6398
			'mobile_reject_mobile'                         => null,
6399
			'mobile_force_mobile'                          => null,
6400
			'mobile_app_promo_download'                    => null,
6401
			'mobile_setup'                                 => null,
6402
			'jetpack_mobile_footer_before'                 => null,
6403
			'wp_mobile_theme_footer'                       => null,
6404
			'minileven_credits'                            => null,
6405
			'jetpack_mobile_header_before'                 => null,
6406
			'jetpack_mobile_header_after'                  => null,
6407
			'jetpack_mobile_theme_menu'                    => null,
6408
			'minileven_show_featured_images'               => null,
6409
			'minileven_attachment_size'                    => null,
6410
		);
6411
6412
		// This is a silly loop depth. Better way?
6413
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6414
			if ( has_action( $hook ) ) {
6415
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6416
					foreach ( $values as $hooked ) {
6417
						if ( is_callable( $hooked['function'] ) ) {
6418
							$function_name = 'an anonymous function';
6419
						} else {
6420
							$function_name = $hooked['function'];
6421
						}
6422
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6423
					}
6424
				}
6425
			}
6426
		}
6427
	}
6428
6429
	/**
6430
	 * Converts any url in a stylesheet, to the correct absolute url.
6431
	 *
6432
	 * Considerations:
6433
	 *  - Normal, relative URLs     `feh.png`
6434
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6435
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6436
	 *  - Absolute URLs             `http://domain.com/feh.png`
6437
	 *  - Domain root relative URLs `/feh.png`
6438
	 *
6439
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6440
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6441
	 *
6442
	 * @return mixed|string
6443
	 */
6444
	public static function absolutize_css_urls( $css, $css_file_url ) {
6445
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6446
		$css_dir = dirname( $css_file_url );
6447
		$p       = wp_parse_url( $css_dir );
6448
		$domain  = sprintf(
6449
			'%1$s//%2$s%3$s%4$s',
6450
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6451
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6452
			$p['host'],
6453
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6454
		);
6455
6456
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6457
			$find = $replace = array();
6458
			foreach ( $matches as $match ) {
6459
				$url = trim( $match['path'], "'\" \t" );
6460
6461
				// If this is a data url, we don't want to mess with it.
6462
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6463
					continue;
6464
				}
6465
6466
				// If this is an absolute or protocol-agnostic url,
6467
				// we don't want to mess with it.
6468
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6469
					continue;
6470
				}
6471
6472
				switch ( substr( $url, 0, 1 ) ) {
6473
					case '/':
6474
						$absolute = $domain . $url;
6475
						break;
6476
					default:
6477
						$absolute = $css_dir . '/' . $url;
6478
				}
6479
6480
				$find[]    = $match[0];
6481
				$replace[] = sprintf( 'url("%s")', $absolute );
6482
			}
6483
			$css = str_replace( $find, $replace, $css );
6484
		}
6485
6486
		return $css;
6487
	}
6488
6489
	/**
6490
	 * This methods removes all of the registered css files on the front end
6491
	 * from Jetpack in favor of using a single file. In effect "imploding"
6492
	 * all the files into one file.
6493
	 *
6494
	 * Pros:
6495
	 * - Uses only ONE css asset connection instead of 15
6496
	 * - Saves a minimum of 56k
6497
	 * - Reduces server load
6498
	 * - Reduces time to first painted byte
6499
	 *
6500
	 * Cons:
6501
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6502
	 *      should not cause any issues with themes.
6503
	 * - Plugins/themes dequeuing styles no longer do anything. See
6504
	 *      jetpack_implode_frontend_css filter for a workaround
6505
	 *
6506
	 * For some situations developers may wish to disable css imploding and
6507
	 * instead operate in legacy mode where each file loads seperately and
6508
	 * can be edited individually or dequeued. This can be accomplished with
6509
	 * the following line:
6510
	 *
6511
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6512
	 *
6513
	 * @since 3.2
6514
	 **/
6515
	public function implode_frontend_css( $travis_test = false ) {
6516
		$do_implode = true;
6517
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6518
			$do_implode = false;
6519
		}
6520
6521
		// Do not implode CSS when the page loads via the AMP plugin.
6522
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6523
			$do_implode = false;
6524
		}
6525
6526
		/**
6527
		 * Allow CSS to be concatenated into a single jetpack.css file.
6528
		 *
6529
		 * @since 3.2.0
6530
		 *
6531
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6532
		 */
6533
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6534
6535
		// Do not use the imploded file when default behavior was altered through the filter
6536
		if ( ! $do_implode ) {
6537
			return;
6538
		}
6539
6540
		// We do not want to use the imploded file in dev mode, or if not connected
6541
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6542
			if ( ! $travis_test ) {
6543
				return;
6544
			}
6545
		}
6546
6547
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6548
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6549
			return;
6550
		}
6551
6552
		/*
6553
		 * Now we assume Jetpack is connected and able to serve the single
6554
		 * file.
6555
		 *
6556
		 * In the future there will be a check here to serve the file locally
6557
		 * or potentially from the Jetpack CDN
6558
		 *
6559
		 * For now:
6560
		 * - Enqueue a single imploded css file
6561
		 * - Zero out the style_loader_tag for the bundled ones
6562
		 * - Be happy, drink scotch
6563
		 */
6564
6565
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6566
6567
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6568
6569
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6570
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6571
	}
6572
6573
	function concat_remove_style_loader_tag( $tag, $handle ) {
6574
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6575
			$tag = '';
6576
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6577
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6578
			}
6579
		}
6580
6581
		return $tag;
6582
	}
6583
6584
	/**
6585
	 * Add an async attribute to scripts that can be loaded asynchronously.
6586
	 * https://www.w3schools.com/tags/att_script_async.asp
6587
	 *
6588
	 * @since 7.7.0
6589
	 *
6590
	 * @param string $tag    The <script> tag for the enqueued script.
6591
	 * @param string $handle The script's registered handle.
6592
	 * @param string $src    The script's source URL.
6593
	 */
6594
	public function script_add_async( $tag, $handle, $src ) {
6595
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6596
			return preg_replace( '/^<script /i', '<script async ', $tag );
6597
		}
6598
6599
		return $tag;
6600
	}
6601
6602
	/*
6603
	 * Check the heartbeat data
6604
	 *
6605
	 * Organizes the heartbeat data by severity.  For example, if the site
6606
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6607
	 *
6608
	 * Data will be added to "caution" array, if it either:
6609
	 *  - Out of date Jetpack version
6610
	 *  - Out of date WP version
6611
	 *  - Out of date PHP version
6612
	 *
6613
	 * $return array $filtered_data
6614
	 */
6615
	public static function jetpack_check_heartbeat_data() {
6616
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6617
6618
		$good    = array();
6619
		$caution = array();
6620
		$bad     = array();
6621
6622
		foreach ( $raw_data as $stat => $value ) {
6623
6624
			// Check jetpack version
6625
			if ( 'version' == $stat ) {
6626
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6627
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6628
					continue;
6629
				}
6630
			}
6631
6632
			// Check WP version
6633
			if ( 'wp-version' == $stat ) {
6634
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6635
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6636
					continue;
6637
				}
6638
			}
6639
6640
			// Check PHP version
6641
			if ( 'php-version' == $stat ) {
6642
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6643
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_PHP_VERSION;
6644
					continue;
6645
				}
6646
			}
6647
6648
			// Check ID crisis
6649
			if ( 'identitycrisis' == $stat ) {
6650
				if ( 'yes' == $value ) {
6651
					$bad[ $stat ] = $value;
6652
					continue;
6653
				}
6654
			}
6655
6656
			// The rest are good :)
6657
			$good[ $stat ] = $value;
6658
		}
6659
6660
		$filtered_data = array(
6661
			'good'    => $good,
6662
			'caution' => $caution,
6663
			'bad'     => $bad,
6664
		);
6665
6666
		return $filtered_data;
6667
	}
6668
6669
6670
	/*
6671
	 * This method is used to organize all options that can be reset
6672
	 * without disconnecting Jetpack.
6673
	 *
6674
	 * It is used in class.jetpack-cli.php to reset options
6675
	 *
6676
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6677
	 *
6678
	 * @return array of options to delete.
6679
	 */
6680
	public static function get_jetpack_options_for_reset() {
6681
		return Jetpack_Options::get_options_for_reset();
6682
	}
6683
6684
	/*
6685
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6686
	 * so we can bring them directly to their site in calypso.
6687
	 *
6688
	 * @param string | url
6689
	 * @return string | url without the guff
6690
	 */
6691
	public static function build_raw_urls( $url ) {
6692
		$strip_http = '/.*?:\/\//i';
6693
		$url        = preg_replace( $strip_http, '', $url );
6694
		$url        = str_replace( '/', '::', $url );
6695
		return $url;
6696
	}
6697
6698
	/**
6699
	 * Stores and prints out domains to prefetch for page speed optimization.
6700
	 *
6701
	 * @param mixed $new_urls
6702
	 */
6703
	public static function dns_prefetch( $new_urls = null ) {
6704
		static $prefetch_urls = array();
6705
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6706
			echo "\r\n";
6707
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6708
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6709
			}
6710
		} elseif ( ! empty( $new_urls ) ) {
6711
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6712
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6713
			}
6714
			foreach ( (array) $new_urls as $this_new_url ) {
6715
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6716
			}
6717
			$prefetch_urls = array_unique( $prefetch_urls );
6718
		}
6719
	}
6720
6721
	public function wp_dashboard_setup() {
6722
		if ( self::is_active() ) {
6723
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6724
		}
6725
6726
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6727
			$jetpack_logo = new Jetpack_Logo();
6728
			$widget_title = sprintf(
6729
				wp_kses(
6730
					/* translators: Placeholder is a Jetpack logo. */
6731
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6732
					array( 'span' => array() )
6733
				),
6734
				$jetpack_logo->get_jp_emblem( true )
6735
			);
6736
6737
			wp_add_dashboard_widget(
6738
				'jetpack_summary_widget',
6739
				$widget_title,
6740
				array( __CLASS__, 'dashboard_widget' )
6741
			);
6742
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6743
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6744
6745
			// If we're inactive and not in development mode, sort our box to the top.
6746
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6747
				global $wp_meta_boxes;
6748
6749
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6750
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6751
6752
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6753
			}
6754
		}
6755
	}
6756
6757
	/**
6758
	 * @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...
6759
	 * @return mixed
6760
	 */
6761
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6762
		if ( ! is_array( $sorted ) ) {
6763
			return $sorted;
6764
		}
6765
6766
		foreach ( $sorted as $box_context => $ids ) {
6767
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6768
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6769
				continue;
6770
			}
6771
6772
			$ids_array = explode( ',', $ids );
6773
			$key       = array_search( 'dashboard_stats', $ids_array );
6774
6775
			if ( false !== $key ) {
6776
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6777
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6778
				$sorted[ $box_context ] = implode( ',', $ids_array );
6779
				// We've found it, stop searching, and just return.
6780
				break;
6781
			}
6782
		}
6783
6784
		return $sorted;
6785
	}
6786
6787
	public static function dashboard_widget() {
6788
		/**
6789
		 * Fires when the dashboard is loaded.
6790
		 *
6791
		 * @since 3.4.0
6792
		 */
6793
		do_action( 'jetpack_dashboard_widget' );
6794
	}
6795
6796
	public static function dashboard_widget_footer() {
6797
		?>
6798
		<footer>
6799
6800
		<div class="protect">
6801
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6802
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6803
				<p class="blocked-count">
6804
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6805
				</p>
6806
				<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>
6807
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
6808
				<a href="
6809
				<?php
6810
				echo esc_url(
6811
					wp_nonce_url(
6812
						self::admin_url(
6813
							array(
6814
								'action' => 'activate',
6815
								'module' => 'protect',
6816
							)
6817
						),
6818
						'jetpack_activate-protect'
6819
					)
6820
				);
6821
				?>
6822
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6823
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6824
				</a>
6825
			<?php else : ?>
6826
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6827
			<?php endif; ?>
6828
		</div>
6829
6830
		<div class="akismet">
6831
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6832
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6833
				<p class="blocked-count">
6834
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6835
				</p>
6836
				<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>
6837
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6838
				<a href="
6839
				<?php
6840
				echo esc_url(
6841
					wp_nonce_url(
6842
						add_query_arg(
6843
							array(
6844
								'action' => 'activate',
6845
								'plugin' => 'akismet/akismet.php',
6846
							),
6847
							admin_url( 'plugins.php' )
6848
						),
6849
						'activate-plugin_akismet/akismet.php'
6850
					)
6851
				);
6852
				?>
6853
							" class="button button-jetpack">
6854
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6855
				</a>
6856
			<?php else : ?>
6857
				<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>
6858
			<?php endif; ?>
6859
		</div>
6860
6861
		</footer>
6862
		<?php
6863
	}
6864
6865
	/*
6866
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6867
	 */
6868
	function jetpack_icon_user_connected( $columns ) {
6869
		$columns['user_jetpack'] = '';
6870
		return $columns;
6871
	}
6872
6873
	/*
6874
	 * Show Jetpack icon if the user is linked.
6875
	 */
6876
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6877
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
6878
			$jetpack_logo = new Jetpack_Logo();
6879
			$emblem_html  = sprintf(
6880
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6881
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6882
				$jetpack_logo->get_jp_emblem()
6883
			);
6884
			return $emblem_html;
6885
		}
6886
6887
		return $val;
6888
	}
6889
6890
	/*
6891
	 * Style the Jetpack user column
6892
	 */
6893
	function jetpack_user_col_style() {
6894
		global $current_screen;
6895
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
6896
			?>
6897
			<style>
6898
				.fixed .column-user_jetpack {
6899
					width: 21px;
6900
				}
6901
				.jp-emblem-user-admin svg {
6902
					width: 20px;
6903
					height: 20px;
6904
				}
6905
				.jp-emblem-user-admin path {
6906
					fill: #00BE28;
6907
				}
6908
			</style>
6909
			<?php
6910
		}
6911
	}
6912
6913
	/**
6914
	 * Checks if Akismet is active and working.
6915
	 *
6916
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6917
	 * that implied usage of methods present since more recent version.
6918
	 * See https://github.com/Automattic/jetpack/pull/9585
6919
	 *
6920
	 * @since  5.1.0
6921
	 *
6922
	 * @return bool True = Akismet available. False = Aksimet not available.
6923
	 */
6924
	public static function is_akismet_active() {
6925
		static $status = null;
6926
6927
		if ( ! is_null( $status ) ) {
6928
			return $status;
6929
		}
6930
6931
		// Check if a modern version of Akismet is active.
6932
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6933
			$status = false;
6934
			return $status;
6935
		}
6936
6937
		// Make sure there is a key known to Akismet at all before verifying key.
6938
		$akismet_key = Akismet::get_api_key();
6939
		if ( ! $akismet_key ) {
6940
			$status = false;
6941
			return $status;
6942
		}
6943
6944
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6945
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6946
6947
		// 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.
6948
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6949
		// We cache the result of the Akismet key verification for ten minutes.
6950
		if ( ! $akismet_key_state || $recheck ) {
6951
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6952
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6953
		}
6954
6955
		$status = 'valid' === $akismet_key_state;
6956
6957
		return $status;
6958
	}
6959
6960
	/**
6961
	 * @deprecated
6962
	 *
6963
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6964
	 */
6965
	public static function is_function_in_backtrace() {
6966
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6967
	}
6968
6969
	/**
6970
	 * Given a minified path, and a non-minified path, will return
6971
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6972
	 *
6973
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6974
	 * root Jetpack directory.
6975
	 *
6976
	 * @since 5.6.0
6977
	 *
6978
	 * @param string $min_path
6979
	 * @param string $non_min_path
6980
	 * @return string The URL to the file
6981
	 */
6982
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6983
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6984
	}
6985
6986
	/**
6987
	 * Checks for whether Jetpack Backup & Scan is enabled.
6988
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6989
	 *
6990
	 * @return bool|int|mixed
6991
	 */
6992
	public static function is_rewind_enabled() {
6993
		if ( ! self::is_active() ) {
6994
			return false;
6995
		}
6996
6997
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6998
		if ( false === $rewind_enabled ) {
6999
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7000
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7001
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7002
				&& ! empty( $rewind_data['state'] )
7003
				&& 'active' === $rewind_data['state'] )
7004
				? 1
7005
				: 0;
7006
7007
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7008
		}
7009
		return $rewind_enabled;
7010
	}
7011
7012
	/**
7013
	 * Return Calypso environment value; used for developing Jetpack and pairing
7014
	 * it with different Calypso enrionments, such as localhost.
7015
	 *
7016
	 * @since 7.4.0
7017
	 *
7018
	 * @return string Calypso environment
7019
	 */
7020
	public static function get_calypso_env() {
7021
		if ( isset( $_GET['calypso_env'] ) ) {
7022
			return sanitize_key( $_GET['calypso_env'] );
7023
		}
7024
7025
		if ( getenv( 'CALYPSO_ENV' ) ) {
7026
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7027
		}
7028
7029
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7030
			return sanitize_key( CALYPSO_ENV );
7031
		}
7032
7033
		return '';
7034
	}
7035
7036
	/**
7037
	 * Checks whether or not TOS has been agreed upon.
7038
	 * Will return true if a user has clicked to register, or is already connected.
7039
	 */
7040
	public static function jetpack_tos_agreed() {
7041
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7042
7043
		$terms_of_service = new Terms_Of_Service();
7044
		return $terms_of_service->has_agreed();
7045
7046
	}
7047
7048
	/**
7049
	 * Handles activating default modules as well general cleanup for the new connection.
7050
	 *
7051
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7052
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7053
	 * @param boolean $send_state_messages          Whether to send state messages.
7054
	 * @return void
7055
	 */
7056
	public static function handle_post_authorization_actions(
7057
		$activate_sso = false,
7058
		$redirect_on_activation_error = false,
7059
		$send_state_messages = true
7060
	) {
7061
		$other_modules = $activate_sso
7062
			? array( 'sso' )
7063
			: array();
7064
7065
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7066
			self::delete_active_modules();
7067
7068
			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...
7069
		} else {
7070
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7071
		}
7072
7073
		// Since this is a fresh connection, be sure to clear out IDC options
7074
		Jetpack_IDC::clear_all_idc_options();
7075
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7076
7077
		// Start nonce cleaner
7078
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7079
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7080
7081
		if ( $send_state_messages ) {
7082
			self::state( 'message', 'authorized' );
7083
		}
7084
	}
7085
7086
	/**
7087
	 * Returns a boolean for whether backups UI should be displayed or not.
7088
	 *
7089
	 * @return bool Should backups UI be displayed?
7090
	 */
7091
	public static function show_backups_ui() {
7092
		/**
7093
		 * Whether UI for backups should be displayed.
7094
		 *
7095
		 * @since 6.5.0
7096
		 *
7097
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7098
		 */
7099
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7100
	}
7101
7102
	/*
7103
	 * Deprecated manage functions
7104
	 */
7105
	function prepare_manage_jetpack_notice() {
7106
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7107
	}
7108
	function manage_activate_screen() {
7109
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7110
	}
7111
	function admin_jetpack_manage_notice() {
7112
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7113
	}
7114
	function opt_out_jetpack_manage_url() {
7115
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7116
	}
7117
	function opt_in_jetpack_manage_url() {
7118
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7119
	}
7120
	function opt_in_jetpack_manage_notice() {
7121
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7122
	}
7123
	function can_display_jetpack_manage_notice() {
7124
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7125
	}
7126
7127
	/**
7128
	 * Clean leftoveruser meta.
7129
	 *
7130
	 * Delete Jetpack-related user meta when it is no longer needed.
7131
	 *
7132
	 * @since 7.3.0
7133
	 *
7134
	 * @param int $user_id User ID being updated.
7135
	 */
7136
	public static function user_meta_cleanup( $user_id ) {
7137
		$meta_keys = array(
7138
			// AtD removed from Jetpack 7.3
7139
			'AtD_options',
7140
			'AtD_check_when',
7141
			'AtD_guess_lang',
7142
			'AtD_ignored_phrases',
7143
		);
7144
7145
		foreach ( $meta_keys as $meta_key ) {
7146
			if ( get_user_meta( $user_id, $meta_key ) ) {
7147
				delete_user_meta( $user_id, $meta_key );
7148
			}
7149
		}
7150
	}
7151
7152
	/**
7153
	 * Checks if a Jetpack site is both active and not in development.
7154
	 *
7155
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7156
	 *
7157
	 * @return bool True if Jetpack is active and not in development.
7158
	 */
7159
	public static function is_active_and_not_development_mode() {
7160
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7161
			return false;
7162
		}
7163
		return true;
7164
	}
7165
}
7166