Completed
Push — add/jetpack-search-indexing-st... ( 5cba09 )
by
unknown
06:56
created

class.jetpack.php (66 issues)

Upgrade to new PHP Analysis Engine

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
3746
3747
		switch ( current_filter() ) {
3748
			case 'wp_ajax_nopriv_jetpack_upload_file':
3749
				$response = $this->upload_handler();
3750
				break;
3751
3752
			case 'wp_ajax_nopriv_jetpack_update_file':
3753
				$response = $this->upload_handler( true );
3754
				break;
3755
			default:
3756
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

Loading history...
3757
				break;
3758
		}
3759
3760
		if ( ! $response ) {
3761
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
3762
		}
3763
3764
		if ( is_wp_error( $response ) ) {
3765
			$status_code       = $response->get_error_data();
0 ignored issues
show
The method get_error_data() does not seem to exist on object<Jetpack_Error>.

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

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

Loading history...
3766
			$error             = $response->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<Jetpack_Error>.

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

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

Loading history...
3767
			$error_description = $response->get_error_message();
0 ignored issues
show
The method get_error_message() does not seem to exist on object<Jetpack_Error>.

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

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

Loading history...
3768
3769
			if ( ! is_int( $status_code ) ) {
3770
				$status_code = 400;
3771
			}
3772
3773
			status_header( $status_code );
3774
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3775
		}
3776
3777
		status_header( 200 );
3778
		if ( true === $response ) {
3779
			exit;
3780
		}
3781
3782
		die( json_encode( (object) $response ) );
3783
	}
3784
3785
	/**
3786
	 * Uploads a file gotten from the global $_FILES.
3787
	 * If `$update_media_item` is true and `post_id` is defined
3788
	 * the attachment file of the media item (gotten through of the post_id)
3789
	 * will be updated instead of add a new one.
3790
	 *
3791
	 * @param  boolean $update_media_item - update media attachment
3792
	 * @return array - An array describing the uploadind files process
3793
	 */
3794
	function upload_handler( $update_media_item = false ) {
3795
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3796
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 405.

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

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

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

Loading history...
3797
		}
3798
3799
		$user = wp_authenticate( '', '' );
3800
		if ( ! $user || is_wp_error( $user ) ) {
3801
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 403.

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

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

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

Loading history...
3802
		}
3803
3804
		wp_set_current_user( $user->ID );
3805
3806
		if ( ! current_user_can( 'upload_files' ) ) {
3807
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

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

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

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

Loading history...
3808
		}
3809
3810
		if ( empty( $_FILES ) ) {
3811
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

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

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

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

Loading history...
3812
		}
3813
3814
		foreach ( array_keys( $_FILES ) as $files_key ) {
3815
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3816
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_hmac'.

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

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

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

Loading history...
3817
			}
3818
		}
3819
3820
		$media_keys = array_keys( $_FILES['media'] );
3821
3822
		$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...
3823
		if ( ! $token || is_wp_error( $token ) ) {
3824
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3825
		}
3826
3827
		$uploaded_files = array();
3828
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3829
		unset( $GLOBALS['post'] );
3830
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3831
			$file = array();
3832
			foreach ( $media_keys as $media_key ) {
3833
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3834
			}
3835
3836
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3837
3838
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3839
			if ( $hmac_provided !== $hmac_file ) {
3840
				$uploaded_files[ $index ] = (object) array(
3841
					'error'             => 'invalid_hmac',
3842
					'error_description' => 'The corresponding HMAC for this file does not match',
3843
				);
3844
				continue;
3845
			}
3846
3847
			$_FILES['.jetpack.upload.'] = $file;
3848
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3849
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3850
				$post_id = 0;
3851
			}
3852
3853
			if ( $update_media_item ) {
3854
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3855
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

Loading history...
3856
				}
3857
3858
				$media_array = $_FILES['media'];
3859
3860
				$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...
3861
				$file_array['type']     = $media_array['type'][0];
3862
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3863
				$file_array['error']    = $media_array['error'][0];
3864
				$file_array['size']     = $media_array['size'][0];
3865
3866
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3867
3868
				if ( is_wp_error( $edited_media_item ) ) {
3869
					return $edited_media_item;
3870
				}
3871
3872
				$response = (object) array(
3873
					'id'   => (string) $post_id,
3874
					'file' => (string) $edited_media_item->post_title,
3875
					'url'  => (string) wp_get_attachment_url( $post_id ),
3876
					'type' => (string) $edited_media_item->post_mime_type,
3877
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3878
				);
3879
3880
				return (array) array( $response );
3881
			}
3882
3883
			$attachment_id = media_handle_upload(
3884
				'.jetpack.upload.',
3885
				$post_id,
3886
				array(),
3887
				array(
3888
					'action' => 'jetpack_upload_file',
3889
				)
3890
			);
3891
3892
			if ( ! $attachment_id ) {
3893
				$uploaded_files[ $index ] = (object) array(
3894
					'error'             => 'unknown',
3895
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3896
				);
3897
			} elseif ( is_wp_error( $attachment_id ) ) {
3898
				$uploaded_files[ $index ] = (object) array(
3899
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3900
					'error_description' => $attachment_id->get_error_message(),
3901
				);
3902
			} else {
3903
				$attachment               = get_post( $attachment_id );
3904
				$uploaded_files[ $index ] = (object) array(
3905
					'id'   => (string) $attachment_id,
3906
					'file' => $attachment->post_title,
3907
					'url'  => wp_get_attachment_url( $attachment_id ),
3908
					'type' => $attachment->post_mime_type,
3909
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3910
				);
3911
				// Zip files uploads are not supported unless they are done for installation purposed
3912
				// lets delete them in case something goes wrong in this whole process
3913
				if ( 'application/zip' === $attachment->post_mime_type ) {
3914
					// Schedule a cleanup for 2 hours from now in case of failed install.
3915
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3916
				}
3917
			}
3918
		}
3919
		if ( ! is_null( $global_post ) ) {
3920
			$GLOBALS['post'] = $global_post;
3921
		}
3922
3923
		return $uploaded_files;
3924
	}
3925
3926
	/**
3927
	 * Add help to the Jetpack page
3928
	 *
3929
	 * @since Jetpack (1.2.3)
3930
	 * @return false if not the Jetpack page
3931
	 */
3932
	function admin_help() {
3933
		$current_screen = get_current_screen();
3934
3935
		// Overview
3936
		$current_screen->add_help_tab(
3937
			array(
3938
				'id'      => 'home',
3939
				'title'   => __( 'Home', 'jetpack' ),
3940
				'content' =>
3941
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3942
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3943
					'<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>',
3944
			)
3945
		);
3946
3947
		// Screen Content
3948
		if ( current_user_can( 'manage_options' ) ) {
3949
			$current_screen->add_help_tab(
3950
				array(
3951
					'id'      => 'settings',
3952
					'title'   => __( 'Settings', 'jetpack' ),
3953
					'content' =>
3954
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3955
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3956
						'<ol>' .
3957
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3958
							'<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>' .
3959
						'</ol>' .
3960
						'<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>',
3961
				)
3962
			);
3963
		}
3964
3965
		// Help Sidebar
3966
		$support_url = Redirect::get_url( 'jetpack-support' );
3967
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3968
		$current_screen->set_help_sidebar(
3969
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3970
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3971
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3972
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3973
		);
3974
	}
3975
3976
	function admin_menu_css() {
3977
		wp_enqueue_style( 'jetpack-icons' );
3978
	}
3979
3980
	function admin_menu_order() {
3981
		return true;
3982
	}
3983
3984 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3985
		$jp_menu_order = array();
3986
3987
		foreach ( $menu_order as $index => $item ) {
3988
			if ( $item != 'jetpack' ) {
3989
				$jp_menu_order[] = $item;
3990
			}
3991
3992
			if ( $index == 0 ) {
3993
				$jp_menu_order[] = 'jetpack';
3994
			}
3995
		}
3996
3997
		return $jp_menu_order;
3998
	}
3999
4000
	function admin_banner_styles() {
4001
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4002
4003 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4004
			wp_register_style(
4005
				'jetpack-dops-style',
4006
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4007
				array(),
4008
				JETPACK__VERSION
4009
			);
4010
		}
4011
4012
		wp_enqueue_style(
4013
			'jetpack',
4014
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4015
			array( 'jetpack-dops-style' ),
4016
			JETPACK__VERSION . '-20121016'
4017
		);
4018
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4019
		wp_style_add_data( 'jetpack', 'suffix', $min );
4020
	}
4021
4022
	function plugin_action_links( $actions ) {
4023
4024
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4025
4026
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4027
			return array_merge(
4028
				$jetpack_home,
4029
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4030
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4031
				$actions
4032
			);
4033
		}
4034
4035
		return array_merge( $jetpack_home, $actions );
4036
	}
4037
4038
	/**
4039
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4040
	 *
4041
	 * @param string $login_url The wp-login URL.
4042
	 * @param string $redirect  URL to redirect users after logging in.
4043
	 * @since Jetpack 8.4
4044
	 * @return string
4045
	 */
4046
	public function login_url( $login_url, $redirect ) {
4047
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4048
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4049
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4050
		}
4051
		return $login_url;
4052
	}
4053
4054
	/**
4055
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4056
	 *
4057
	 * @since Jetpack 8.4
4058
	 */
4059
	public function login_init() {
4060
		// phpcs:ignore WordPress.Security.NonceVerification
4061
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4062
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4063
			wp_safe_redirect(
4064
				add_query_arg(
4065
					array(
4066
						'forceInstall' => 1,
4067
						'url'          => rawurlencode( get_site_url() ),
4068
					),
4069
					// @todo provide way to go to specific calypso env.
4070
					self::get_calypso_host() . 'jetpack/connect'
4071
				)
4072
			);
4073
			exit;
4074
		}
4075
	}
4076
4077
	/*
4078
	 * Registration flow:
4079
	 * 1 - ::admin_page_load() action=register
4080
	 * 2 - ::try_registration()
4081
	 * 3 - ::register()
4082
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4083
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4084
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4085
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4086
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4087
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4088
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4089
	 *       jetpack_id, jetpack_secret, jetpack_public
4090
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4091
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4092
	 * 5 - user logs in with WP.com account
4093
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4094
	 *		- Manager::authorize()
4095
	 *		- Manager::get_token()
4096
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4097
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4098
	 *			- which responds with access_token, token_type, scope
4099
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4100
	 *		- Jetpack::activate_default_modules()
4101
	 *     		- Deactivates deprecated plugins
4102
	 *     		- Activates all default modules
4103
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4104
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4105
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4106
	 *     Done!
4107
	 */
4108
4109
	/**
4110
	 * Handles the page load events for the Jetpack admin page
4111
	 */
4112
	function admin_page_load() {
4113
		$error = false;
4114
4115
		// Make sure we have the right body class to hook stylings for subpages off of.
4116
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4117
4118
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4119
			// Should only be used in intermediate redirects to preserve state across redirects
4120
			self::restate();
4121
		}
4122
4123
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4124
			// @todo: Add validation against a known whitelist
4125
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4126
			// User clicked in the iframe to link their accounts
4127
			if ( ! self::is_user_connected() ) {
4128
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4129
4130
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4131
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4132
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4133
4134
				if ( isset( $_GET['notes_iframe'] ) ) {
4135
					$connect_url .= '&notes_iframe';
4136
				}
4137
				wp_redirect( $connect_url );
4138
				exit;
4139
			} else {
4140
				if ( ! isset( $_GET['calypso_env'] ) ) {
4141
					self::state( 'message', 'already_authorized' );
4142
					wp_safe_redirect( self::admin_url() );
4143
					exit;
4144
				} else {
4145
					$connect_url  = $this->build_connect_url( true, false, $from );
4146
					$connect_url .= '&already_authorized=true';
4147
					wp_redirect( $connect_url );
4148
					exit;
4149
				}
4150
			}
4151
		}
4152
4153
		if ( isset( $_GET['action'] ) ) {
4154
			switch ( $_GET['action'] ) {
4155
				case 'authorize':
4156
					if ( self::is_active() && self::is_user_connected() ) {
4157
						self::state( 'message', 'already_authorized' );
4158
						wp_safe_redirect( self::admin_url() );
4159
						exit;
4160
					}
4161
					self::log( 'authorize' );
4162
					$client_server = new Jetpack_Client_Server();
4163
					$client_server->client_authorize();
4164
					exit;
4165
				case 'register':
4166
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4167
						$error = 'cheatin';
4168
						break;
4169
					}
4170
					check_admin_referer( 'jetpack-register' );
4171
					self::log( 'register' );
4172
					self::maybe_set_version_option();
4173
					$registered = self::try_registration();
4174 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4175
						$error = $registered->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

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

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

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

Loading history...
4178
4179
						/**
4180
						 * Jetpack registration Error.
4181
						 *
4182
						 * @since 7.5.0
4183
						 *
4184
						 * @param string|int $error The error code.
4185
						 * @param \WP_Error $registered The error object.
4186
						 */
4187
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4188
						break;
4189
					}
4190
4191
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4192
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4193
4194
					/**
4195
					 * Jetpack registration Success.
4196
					 *
4197
					 * @since 7.5.0
4198
					 *
4199
					 * @param string $from 'from' GET parameter;
4200
					 */
4201
					do_action( 'jetpack_connection_register_success', $from );
4202
4203
					$url = $this->build_connect_url( true, $redirect, $from );
4204
4205
					if ( ! empty( $_GET['onboarding'] ) ) {
4206
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4207
					}
4208
4209
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4210
						$url = add_query_arg( 'auth_approved', 'true', $url );
4211
					}
4212
4213
					wp_redirect( $url );
4214
					exit;
4215
				case 'activate':
4216
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4217
						$error = 'cheatin';
4218
						break;
4219
					}
4220
4221
					$module = stripslashes( $_GET['module'] );
4222
					check_admin_referer( "jetpack_activate-$module" );
4223
					self::log( 'activate', $module );
4224
					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...
4225
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4226
					}
4227
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4228
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4229
					exit;
4230
				case 'activate_default_modules':
4231
					check_admin_referer( 'activate_default_modules' );
4232
					self::log( 'activate_default_modules' );
4233
					self::restate();
4234
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4235
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4236
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4237
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4238
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4239
					exit;
4240
				case 'disconnect':
4241
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4242
						$error = 'cheatin';
4243
						break;
4244
					}
4245
4246
					check_admin_referer( 'jetpack-disconnect' );
4247
					self::log( 'disconnect' );
4248
					self::disconnect();
4249
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4250
					exit;
4251
				case 'reconnect':
4252
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4253
						$error = 'cheatin';
4254
						break;
4255
					}
4256
4257
					check_admin_referer( 'jetpack-reconnect' );
4258
					self::log( 'reconnect' );
4259
					$this->disconnect();
4260
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4261
					exit;
4262 View Code Duplication
				case 'deactivate':
4263
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4264
						$error = 'cheatin';
4265
						break;
4266
					}
4267
4268
					$modules = stripslashes( $_GET['module'] );
4269
					check_admin_referer( "jetpack_deactivate-$modules" );
4270
					foreach ( explode( ',', $modules ) as $module ) {
4271
						self::log( 'deactivate', $module );
4272
						self::deactivate_module( $module );
4273
						self::state( 'message', 'module_deactivated' );
4274
					}
4275
					self::state( 'module', $modules );
4276
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4277
					exit;
4278
				case 'unlink':
4279
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4280
					check_admin_referer( 'jetpack-unlink' );
4281
					self::log( 'unlink' );
4282
					Connection_Manager::disconnect_user();
4283
					self::state( 'message', 'unlinked' );
4284
					if ( 'sub-unlink' == $redirect ) {
4285
						wp_safe_redirect( admin_url() );
4286
					} else {
4287
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4288
					}
4289
					exit;
4290
				case 'onboard':
4291
					if ( ! current_user_can( 'manage_options' ) ) {
4292
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4293
					} else {
4294
						self::create_onboarding_token();
4295
						$url = $this->build_connect_url( true );
4296
4297
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4298
							$url = add_query_arg( 'onboarding', $token, $url );
4299
						}
4300
4301
						$calypso_env = $this->get_calypso_env();
4302
						if ( ! empty( $calypso_env ) ) {
4303
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4304
						}
4305
4306
						wp_redirect( $url );
4307
						exit;
4308
					}
4309
					exit;
4310
				default:
4311
					/**
4312
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4313
					 *
4314
					 * @since 2.6.0
4315
					 *
4316
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4317
					 */
4318
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4319
			}
4320
		}
4321
4322
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4323
			self::activate_new_modules( true );
4324
		}
4325
4326
		$message_code = self::state( 'message' );
4327
		if ( self::state( 'optin-manage' ) ) {
4328
			$activated_manage = $message_code;
4329
			$message_code     = 'jetpack-manage';
4330
		}
4331
4332
		switch ( $message_code ) {
4333
			case 'jetpack-manage':
4334
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4335
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4336
				$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), $sites_url ) . '</strong>';
4337
				if ( $activated_manage ) {
0 ignored issues
show
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

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

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

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

Loading history...
4534
			: 'should-not-happen';
4535
4536
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4537
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4538
			// No need to update the option if we already have
4539
			// this code stored.
4540
			return;
4541
		}
4542
		$xmlrpc_errors[ $code ] = true;
4543
4544
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4545
	}
4546
4547
	/**
4548
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4549
	 */
4550
	function stat( $group, $detail ) {
4551
		if ( ! isset( $this->stats[ $group ] ) ) {
4552
			$this->stats[ $group ] = array();
4553
		}
4554
		$this->stats[ $group ][] = $detail;
4555
	}
4556
4557
	/**
4558
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4559
	 */
4560
	function do_stats( $method = '' ) {
4561
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4562
			foreach ( $this->stats as $group => $stats ) {
4563
				if ( is_array( $stats ) && count( $stats ) ) {
4564
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4565
					if ( 'server_side' === $method ) {
4566
						self::do_server_side_stat( $args );
4567
					} else {
4568
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4569
					}
4570
				}
4571
				unset( $this->stats[ $group ] );
4572
			}
4573
		}
4574
	}
4575
4576
	/**
4577
	 * Runs stats code for a one-off, server-side.
4578
	 *
4579
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4580
	 *
4581
	 * @return bool If it worked.
4582
	 */
4583
	static function do_server_side_stat( $args ) {
4584
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4585
		if ( is_wp_error( $response ) ) {
4586
			return false;
4587
		}
4588
4589
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4590
			return false;
4591
		}
4592
4593
		return true;
4594
	}
4595
4596
	/**
4597
	 * Builds the stats url.
4598
	 *
4599
	 * @param $args array|string The arguments to append to the URL.
4600
	 *
4601
	 * @return string The URL to be pinged.
4602
	 */
4603
	static function build_stats_url( $args ) {
4604
		$defaults = array(
4605
			'v'    => 'wpcom2',
4606
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4607
		);
4608
		$args     = wp_parse_args( $args, $defaults );
0 ignored issues
show
$defaults is of type array<string,string,{"v"...ring","rand":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4609
		/**
4610
		 * Filter the URL used as the Stats tracking pixel.
4611
		 *
4612
		 * @since 2.3.2
4613
		 *
4614
		 * @param string $url Base URL used as the Stats tracking pixel.
4615
		 */
4616
		$base_url = apply_filters(
4617
			'jetpack_stats_base_url',
4618
			'https://pixel.wp.com/g.gif'
4619
		);
4620
		$url      = add_query_arg( $args, $base_url );
4621
		return $url;
4622
	}
4623
4624
	/**
4625
	 * Get the role of the current user.
4626
	 *
4627
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4628
	 *
4629
	 * @access public
4630
	 * @static
4631
	 *
4632
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4633
	 */
4634
	public static function translate_current_user_to_role() {
4635
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4636
4637
		$roles = new Roles();
4638
		return $roles->translate_current_user_to_role();
4639
	}
4640
4641
	/**
4642
	 * Get the role of a particular user.
4643
	 *
4644
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4645
	 *
4646
	 * @access public
4647
	 * @static
4648
	 *
4649
	 * @param \WP_User $user User object.
4650
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4651
	 */
4652
	public static function translate_user_to_role( $user ) {
4653
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4654
4655
		$roles = new Roles();
4656
		return $roles->translate_user_to_role( $user );
4657
	}
4658
4659
	/**
4660
	 * Get the minimum capability for a role.
4661
	 *
4662
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4663
	 *
4664
	 * @access public
4665
	 * @static
4666
	 *
4667
	 * @param string $role Role name.
4668
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4669
	 */
4670
	public static function translate_role_to_cap( $role ) {
4671
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4672
4673
		$roles = new Roles();
4674
		return $roles->translate_role_to_cap( $role );
4675
	}
4676
4677
	/**
4678
	 * Sign a user role with the master access token.
4679
	 * If not specified, will default to the current user.
4680
	 *
4681
	 * @deprecated since 7.7
4682
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4683
	 *
4684
	 * @access public
4685
	 * @static
4686
	 *
4687
	 * @param string $role    User role.
4688
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
4689
	 * @return string Signed user role.
4690
	 */
4691
	public static function sign_role( $role, $user_id = null ) {
4692
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4693
		return self::connection()->sign_role( $role, $user_id );
4694
	}
4695
4696
	/**
4697
	 * Builds a URL to the Jetpack connection auth page
4698
	 *
4699
	 * @since 3.9.5
4700
	 *
4701
	 * @param bool        $raw If true, URL will not be escaped.
4702
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4703
	 *                              If string, will be a custom redirect.
4704
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4705
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4706
	 *
4707
	 * @return string Connect URL
4708
	 */
4709
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4710
		$site_id    = Jetpack_Options::get_option( 'id' );
4711
		$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...
4712
4713
		if ( $register || ! $blog_token || ! $site_id ) {
4714
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4715
4716
			if ( ! empty( $redirect ) ) {
4717
				$url = add_query_arg(
4718
					'redirect',
4719
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4720
					$url
4721
				);
4722
			}
4723
4724
			if ( is_network_admin() ) {
4725
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4726
			}
4727
4728
			$calypso_env = self::get_calypso_env();
4729
4730
			if ( ! empty( $calypso_env ) ) {
4731
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4732
			}
4733
		} else {
4734
4735
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4736
			// because otherwise this logic can get us in to a loop.
4737
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4738
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4739
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4740
4741
				$response = Client::wpcom_json_api_request_as_blog(
4742
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4743
					'1.1'
4744
				);
4745
4746
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4747
4748
					// Generating a register URL instead to refresh the existing token
4749
					return $this->build_connect_url( $raw, $redirect, $from, true );
4750
				}
4751
			}
4752
4753
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4709 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...
4754
		}
4755
4756
		if ( $from ) {
4757
			$url = add_query_arg( 'from', $from, $url );
4758
		}
4759
4760
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4761
		/**
4762
		 * Filter the URL used when connecting a user to a WordPress.com account.
4763
		 *
4764
		 * @since 8.1.0
4765
		 *
4766
		 * @param string $url Connection URL.
4767
		 * @param bool   $raw If true, URL will not be escaped.
4768
		 */
4769
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4770
	}
4771
4772
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4773
4774
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4775
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4776
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4777
4778
		if ( $iframe ) {
4779
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4780
		}
4781
4782
		$c8n = self::connection();
4783
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
$redirect is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4784
4785
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4786
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4787
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4788
4789
		if ( $iframe ) {
4790
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4791
		}
4792
4793
		return $url;
4794
	}
4795
4796
	/**
4797
	 * Filters the connection URL parameter array.
4798
	 *
4799
	 * @param Array $args default URL parameters used by the package.
4800
	 * @return Array the modified URL arguments array.
4801
	 */
4802
	public static function filter_connect_request_body( $args ) {
4803
		if (
4804
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4805
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4806
		) {
4807
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4808
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4809
				? $gp_locale->slug
4810
				: '';
4811
		}
4812
4813
		$tracking        = new Tracking();
4814
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4815
4816
		$args = array_merge(
4817
			$args,
4818
			array(
4819
				'_ui' => $tracks_identity['_ui'],
4820
				'_ut' => $tracks_identity['_ut'],
4821
			)
4822
		);
4823
4824
		$calypso_env = self::get_calypso_env();
4825
4826
		if ( ! empty( $calypso_env ) ) {
4827
			$args['calypso_env'] = $calypso_env;
4828
		}
4829
4830
		return $args;
4831
	}
4832
4833
	/**
4834
	 * Filters the URL that will process the connection data. It can be different from the URL
4835
	 * that we send the user to after everything is done.
4836
	 *
4837
	 * @param String $processing_url the default redirect URL used by the package.
4838
	 * @return String the modified URL.
4839
	 */
4840
	public static function filter_connect_processing_url( $processing_url ) {
4841
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4842
		return $processing_url;
4843
	}
4844
4845
	/**
4846
	 * Filters the redirection URL that is used for connect requests. The redirect
4847
	 * URL should return the user back to the Jetpack console.
4848
	 *
4849
	 * @param String $redirect the default redirect URL used by the package.
4850
	 * @return String the modified URL.
4851
	 */
4852
	public static function filter_connect_redirect_url( $redirect ) {
4853
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4854
		$redirect           = $redirect
4855
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4856
			: $jetpack_admin_page;
4857
4858
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4859
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4860
		}
4861
4862
		return $redirect;
4863
	}
4864
4865
	/**
4866
	 * This action fires at the beginning of the Manager::authorize method.
4867
	 */
4868
	public static function authorize_starting() {
4869
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4870
		// Checking if site has been active/connected previously before recording unique connection.
4871
		if ( ! $jetpack_unique_connection ) {
4872
			// jetpack_unique_connection option has never been set.
4873
			$jetpack_unique_connection = array(
4874
				'connected'    => 0,
4875
				'disconnected' => 0,
4876
				'version'      => '3.6.1',
4877
			);
4878
4879
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4880
4881
			// Track unique connection.
4882
			$jetpack = self::init();
4883
4884
			$jetpack->stat( 'connections', 'unique-connection' );
4885
			$jetpack->do_stats( 'server_side' );
4886
		}
4887
4888
		// Increment number of times connected.
4889
		$jetpack_unique_connection['connected'] += 1;
4890
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4891
	}
4892
4893
	/**
4894
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4895
	 * linked.
4896
	 */
4897
	public static function authorize_ending_linked() {
4898
		// Don't activate anything since we are just connecting a user.
4899
		self::state( 'message', 'linked' );
4900
	}
4901
4902
	/**
4903
	 * This action fires at the end of the Manager::authorize method when the master user is
4904
	 * authorized.
4905
	 *
4906
	 * @param array $data The request data.
4907
	 */
4908
	public static function authorize_ending_authorized( $data ) {
4909
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4910
		self::invalidate_onboarding_token();
4911
4912
		// If redirect_uri is SSO, ensure SSO module is enabled.
4913
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4914
4915
		/** This filter is documented in class.jetpack-cli.php */
4916
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4917
4918
		$activate_sso = (
4919
			isset( $redirect_options['action'] ) &&
4920
			'jetpack-sso' === $redirect_options['action'] &&
4921
			$jetpack_start_enable_sso
4922
		);
4923
4924
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4925
4926
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4927
	}
4928
4929
	/**
4930
	 * Get our assumed site creation date.
4931
	 * Calculated based on the earlier date of either:
4932
	 * - Earliest admin user registration date.
4933
	 * - Earliest date of post of any post type.
4934
	 *
4935
	 * @since 7.2.0
4936
	 * @deprecated since 7.8.0
4937
	 *
4938
	 * @return string Assumed site creation date and time.
4939
	 */
4940
	public static function get_assumed_site_creation_date() {
4941
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4942
		return self::connection()->get_assumed_site_creation_date();
4943
	}
4944
4945 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4946
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4947
4948
		if ( $activation_source_name ) {
4949
			$args['_as'] = urlencode( $activation_source_name );
4950
		}
4951
4952
		if ( $activation_source_keyword ) {
4953
			$args['_ak'] = urlencode( $activation_source_keyword );
4954
		}
4955
	}
4956
4957
	function build_reconnect_url( $raw = false ) {
4958
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4959
		return $raw ? $url : esc_url( $url );
4960
	}
4961
4962
	public static function admin_url( $args = null ) {
4963
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4964
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4965
		return $url;
4966
	}
4967
4968
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4969
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4970
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4971
	}
4972
4973
	function dismiss_jetpack_notice() {
4974
4975
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4976
			return;
4977
		}
4978
4979
		switch ( $_GET['jetpack-notice'] ) {
4980
			case 'dismiss':
4981
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4982
4983
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4984
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4985
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4986
				}
4987
				break;
4988
		}
4989
	}
4990
4991
	public static function sort_modules( $a, $b ) {
4992
		if ( $a['sort'] == $b['sort'] ) {
4993
			return 0;
4994
		}
4995
4996
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4997
	}
4998
4999
	function ajax_recheck_ssl() {
5000
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5001
		$result = self::permit_ssl( true );
5002
		wp_send_json(
5003
			array(
5004
				'enabled' => $result,
5005
				'message' => get_transient( 'jetpack_https_test_message' ),
5006
			)
5007
		);
5008
	}
5009
5010
	/* Client API */
5011
5012
	/**
5013
	 * Returns the requested Jetpack API URL
5014
	 *
5015
	 * @deprecated since 7.7
5016
	 * @return string
5017
	 */
5018
	public static function api_url( $relative_url ) {
5019
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5020
		$connection = self::connection();
5021
		return $connection->api_url( $relative_url );
5022
	}
5023
5024
	/**
5025
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5026
	 *
5027
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5028
	 */
5029
	public static function fix_url_for_bad_hosts( $url ) {
5030
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5031
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5032
	}
5033
5034
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5035
		// Default to a blog token.
5036
		$token_type = 'blog';
5037
5038
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5039
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5040
			if ( ! empty( $_GET['onboarding'] ) ) {
5041
				$jpo = $_GET;
5042
			} else {
5043
				$jpo = json_decode( $request_data, true );
5044
			}
5045
5046
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5047
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5048
5049
			if (
5050
				isset( $jpo_user )
5051
				&& isset( $jpo_token )
5052
				&& is_email( $jpo_user )
5053
				&& ctype_alnum( $jpo_token )
5054
				&& isset( $_GET['rest_route'] )
5055
				&& self::validate_onboarding_token_action(
5056
					$jpo_token,
5057
					$_GET['rest_route']
5058
				)
5059
			) {
5060
				$jp_user = get_user_by( 'email', $jpo_user );
5061
				if ( is_a( $jp_user, 'WP_User' ) ) {
5062
					wp_set_current_user( $jp_user->ID );
5063
					$user_can = is_multisite()
5064
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5065
						: current_user_can( 'manage_options' );
5066
					if ( $user_can ) {
5067
						$token_type              = 'user';
5068
						$token->external_user_id = $jp_user->ID;
5069
					}
5070
				}
5071
			}
5072
5073
			$token_data['type']    = $token_type;
5074
			$token_data['user_id'] = $token->external_user_id;
5075
		}
5076
5077
		return $token_data;
5078
	}
5079
5080
	/**
5081
	 * Create a random secret for validating onboarding payload
5082
	 *
5083
	 * @return string Secret token
5084
	 */
5085
	public static function create_onboarding_token() {
5086
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5087
			$token = wp_generate_password( 32, false );
5088
			Jetpack_Options::update_option( 'onboarding', $token );
5089
		}
5090
5091
		return $token;
5092
	}
5093
5094
	/**
5095
	 * Remove the onboarding token
5096
	 *
5097
	 * @return bool True on success, false on failure
5098
	 */
5099
	public static function invalidate_onboarding_token() {
5100
		return Jetpack_Options::delete_option( 'onboarding' );
5101
	}
5102
5103
	/**
5104
	 * Validate an onboarding token for a specific action
5105
	 *
5106
	 * @return boolean True if token/action pair is accepted, false if not
5107
	 */
5108
	public static function validate_onboarding_token_action( $token, $action ) {
5109
		// Compare tokens, bail if tokens do not match
5110
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5111
			return false;
5112
		}
5113
5114
		// List of valid actions we can take
5115
		$valid_actions = array(
5116
			'/jetpack/v4/settings',
5117
		);
5118
5119
		// Whitelist the action
5120
		if ( ! in_array( $action, $valid_actions ) ) {
5121
			return false;
5122
		}
5123
5124
		return true;
5125
	}
5126
5127
	/**
5128
	 * Checks to see if the URL is using SSL to connect with Jetpack
5129
	 *
5130
	 * @since 2.3.3
5131
	 * @return boolean
5132
	 */
5133
	public static function permit_ssl( $force_recheck = false ) {
5134
		// Do some fancy tests to see if ssl is being supported
5135
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5136
			$message = '';
5137
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5138
				$ssl = 0;
5139
			} else {
5140
				switch ( JETPACK_CLIENT__HTTPS ) {
5141
					case 'NEVER':
5142
						$ssl     = 0;
5143
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5144
						break;
5145
					case 'ALWAYS':
5146
					case 'AUTO':
5147
					default:
5148
						$ssl = 1;
5149
						break;
5150
				}
5151
5152
				// If it's not 'NEVER', test to see
5153
				if ( $ssl ) {
5154
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5155
						$ssl     = 0;
5156
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5157
					} else {
5158
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5159
						if ( is_wp_error( $response ) ) {
5160
							$ssl     = 0;
5161
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5162
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5163
							$ssl     = 0;
5164
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5165
						}
5166
					}
5167
				}
5168
			}
5169
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5170
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5171
		}
5172
5173
		return (bool) $ssl;
5174
	}
5175
5176
	/*
5177
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5178
	 */
5179
	public function alert_auto_ssl_fail() {
5180
		if ( ! current_user_can( 'manage_options' ) ) {
5181
			return;
5182
		}
5183
5184
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5185
		?>
5186
5187
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5188
			<div class="jp-banner__content">
5189
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5190
				<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>
5191
				<p>
5192
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5193
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5194
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5195
				</p>
5196
				<p>
5197
					<?php
5198
					printf(
5199
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5200
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5201
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5202
					);
5203
					?>
5204
				</p>
5205
			</div>
5206
		</div>
5207
		<style>
5208
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5209
		</style>
5210
		<script type="text/javascript">
5211
			jQuery( document ).ready( function( $ ) {
5212
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5213
					var $this = $( this );
5214
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5215
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5216
					e.preventDefault();
5217
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5218
					$.post( ajaxurl, data )
5219
					  .done( function( response ) {
5220
						  if ( response.enabled ) {
5221
							  $( '#jetpack-ssl-warning' ).hide();
5222
						  } else {
5223
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5224
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5225
						  }
5226
					  }.bind( $this ) );
5227
				} );
5228
			} );
5229
		</script>
5230
5231
		<?php
5232
	}
5233
5234
	/**
5235
	 * Returns the Jetpack XML-RPC API
5236
	 *
5237
	 * @deprecated 8.0 Use Connection_Manager instead.
5238
	 * @return string
5239
	 */
5240
	public static function xmlrpc_api_url() {
5241
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5242
		return self::connection()->xmlrpc_api_url();
5243
	}
5244
5245
	/**
5246
	 * Returns the connection manager object.
5247
	 *
5248
	 * @return Automattic\Jetpack\Connection\Manager
5249
	 */
5250
	public static function connection() {
5251
		$jetpack = static::init();
5252
5253
		// If the connection manager hasn't been instantiated, do that now.
5254
		if ( ! $jetpack->connection_manager ) {
5255
			$jetpack->connection_manager = new Connection_Manager();
5256
		}
5257
5258
		return $jetpack->connection_manager;
5259
	}
5260
5261
	/**
5262
	 * Creates two secret tokens and the end of life timestamp for them.
5263
	 *
5264
	 * Note these tokens are unique per call, NOT static per site for connecting.
5265
	 *
5266
	 * @since 2.6
5267
	 * @param String  $action  The action name.
5268
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be false|integer?

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

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

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

Loading history...
5269
	 * @param Integer $exp     Expiration time in seconds.
5270
	 * @return array
5271
	 */
5272
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5273
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5274
	}
5275
5276
	public static function get_secrets( $action, $user_id ) {
5277
		$secrets = self::connection()->get_secrets( $action, $user_id );
5278
5279
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5280
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

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

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

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

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

Loading history...
5285
		}
5286
5287
		return $secrets;
5288
	}
5289
5290
	/**
5291
	 * @deprecated 7.5 Use Connection_Manager instead.
5292
	 *
5293
	 * @param $action
5294
	 * @param $user_id
5295
	 */
5296
	public static function delete_secrets( $action, $user_id ) {
5297
		return self::connection()->delete_secrets( $action, $user_id );
5298
	}
5299
5300
	/**
5301
	 * Builds the timeout limit for queries talking with the wpcom servers.
5302
	 *
5303
	 * Based on local php max_execution_time in php.ini
5304
	 *
5305
	 * @since 2.6
5306
	 * @return int
5307
	 * @deprecated
5308
	 **/
5309
	public function get_remote_query_timeout_limit() {
5310
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5311
		return self::get_max_execution_time();
5312
	}
5313
5314
	/**
5315
	 * Builds the timeout limit for queries talking with the wpcom servers.
5316
	 *
5317
	 * Based on local php max_execution_time in php.ini
5318
	 *
5319
	 * @since 5.4
5320
	 * @return int
5321
	 **/
5322
	public static function get_max_execution_time() {
5323
		$timeout = (int) ini_get( 'max_execution_time' );
5324
5325
		// Ensure exec time set in php.ini
5326
		if ( ! $timeout ) {
5327
			$timeout = 30;
5328
		}
5329
		return $timeout;
5330
	}
5331
5332
	/**
5333
	 * Sets a minimum request timeout, and returns the current timeout
5334
	 *
5335
	 * @since 5.4
5336
	 **/
5337 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5338
		$timeout = self::get_max_execution_time();
5339
		if ( $timeout < $min_timeout ) {
5340
			$timeout = $min_timeout;
5341
			set_time_limit( $timeout );
5342
		}
5343
		return $timeout;
5344
	}
5345
5346
	/**
5347
	 * Takes the response from the Jetpack register new site endpoint and
5348
	 * verifies it worked properly.
5349
	 *
5350
	 * @since 2.6
5351
	 * @deprecated since 7.7.0
5352
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5353
	 **/
5354
	public function validate_remote_register_response() {
5355
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5356
	}
5357
5358
	/**
5359
	 * @return bool|WP_Error
5360
	 */
5361
	public static function register() {
5362
		$tracking = new Tracking();
5363
		$tracking->record_user_event( 'jpc_register_begin' );
5364
5365
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5366
5367
		$connection   = self::connection();
5368
		$registration = $connection->register();
5369
5370
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5371
5372
		if ( ! $registration || is_wp_error( $registration ) ) {
5373
			return $registration;
5374
		}
5375
5376
		return true;
5377
	}
5378
5379
	/**
5380
	 * Filters the registration request body to include tracking properties.
5381
	 *
5382
	 * @param Array $properties
5383
	 * @return Array amended properties.
5384
	 */
5385 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5386
		$tracking        = new Tracking();
5387
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5388
5389
		return array_merge(
5390
			$properties,
5391
			array(
5392
				'_ui' => $tracks_identity['_ui'],
5393
				'_ut' => $tracks_identity['_ut'],
5394
			)
5395
		);
5396
	}
5397
5398
	/**
5399
	 * Filters the token request body to include tracking properties.
5400
	 *
5401
	 * @param Array $properties
5402
	 * @return Array amended properties.
5403
	 */
5404 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5405
		$tracking        = new Tracking();
5406
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5407
5408
		return array_merge(
5409
			$properties,
5410
			array(
5411
				'_ui' => $tracks_identity['_ui'],
5412
				'_ut' => $tracks_identity['_ut'],
5413
			)
5414
		);
5415
	}
5416
5417
	/**
5418
	 * If the db version is showing something other that what we've got now, bump it to current.
5419
	 *
5420
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5421
	 */
5422
	public static function maybe_set_version_option() {
5423
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5424
		if ( JETPACK__VERSION != $version ) {
5425
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5426
5427
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5428
				/** This action is documented in class.jetpack.php */
5429
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5430
			}
5431
5432
			return true;
5433
		}
5434
		return false;
5435
	}
5436
5437
	/* Client Server API */
5438
5439
	/**
5440
	 * Loads the Jetpack XML-RPC client.
5441
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5442
	 *
5443
	 * @deprecated since 7.7.0
5444
	 */
5445
	public static function load_xml_rpc_client() {
5446
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5447
	}
5448
5449
	/**
5450
	 * Resets the saved authentication state in between testing requests.
5451
	 */
5452
	public function reset_saved_auth_state() {
5453
		$this->rest_authentication_status = null;
5454
5455
		if ( ! $this->connection_manager ) {
5456
			$this->connection_manager = new Connection_Manager();
5457
		}
5458
5459
		$this->connection_manager->reset_saved_auth_state();
5460
	}
5461
5462
	/**
5463
	 * Verifies the signature of the current request.
5464
	 *
5465
	 * @deprecated since 7.7.0
5466
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5467
	 *
5468
	 * @return false|array
5469
	 */
5470
	public function verify_xml_rpc_signature() {
5471
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5472
		return self::connection()->verify_xml_rpc_signature();
5473
	}
5474
5475
	/**
5476
	 * Verifies the signature of the current request.
5477
	 *
5478
	 * This function has side effects and should not be used. Instead,
5479
	 * use the memoized version `->verify_xml_rpc_signature()`.
5480
	 *
5481
	 * @deprecated since 7.7.0
5482
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5483
	 * @internal
5484
	 */
5485
	private function internal_verify_xml_rpc_signature() {
5486
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5487
	}
5488
5489
	/**
5490
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5491
	 *
5492
	 * @deprecated since 7.7.0
5493
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5494
	 *
5495
	 * @param \WP_User|mixed $user     User object if authenticated.
5496
	 * @param string         $username Username.
5497
	 * @param string         $password Password string.
5498
	 * @return \WP_User|mixed Authenticated user or error.
5499
	 */
5500 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5501
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5502
5503
		if ( ! $this->connection_manager ) {
5504
			$this->connection_manager = new Connection_Manager();
5505
		}
5506
5507
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5508
	}
5509
5510
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5511
	// Uses the existing XMLRPC request signing implementation.
5512
	function wp_rest_authenticate( $user ) {
5513
		if ( ! empty( $user ) ) {
5514
			// Another authentication method is in effect.
5515
			return $user;
5516
		}
5517
5518
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5519
			// Nothing to do for this authentication method.
5520
			return null;
5521
		}
5522
5523
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5524
			// Nothing to do for this authentication method.
5525
			return null;
5526
		}
5527
5528
		// Ensure that we always have the request body available.  At this
5529
		// point, the WP REST API code to determine the request body has not
5530
		// run yet.  That code may try to read from 'php://input' later, but
5531
		// this can only be done once per request in PHP versions prior to 5.6.
5532
		// So we will go ahead and perform this read now if needed, and save
5533
		// the request body where both the Jetpack signature verification code
5534
		// and the WP REST API code can see it.
5535
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5536
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5537
		}
5538
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5539
5540
		// Only support specific request parameters that have been tested and
5541
		// are known to work with signature verification.  A different method
5542
		// can be passed to the WP REST API via the '?_method=' parameter if
5543
		// needed.
5544
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5545
			$this->rest_authentication_status = new WP_Error(
5546
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5547
				__( 'This request method is not supported.', 'jetpack' ),
5548
				array( 'status' => 400 )
5549
			);
5550
			return null;
5551
		}
5552
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5553
			$this->rest_authentication_status = new WP_Error(
5554
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5555
				__( 'This request method does not support body parameters.', 'jetpack' ),
5556
				array( 'status' => 400 )
5557
			);
5558
			return null;
5559
		}
5560
5561
		if ( ! $this->connection_manager ) {
5562
			$this->connection_manager = new Connection_Manager();
5563
		}
5564
5565
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5566
5567
		if (
5568
			$verified &&
5569
			isset( $verified['type'] ) &&
5570
			'user' === $verified['type'] &&
5571
			! empty( $verified['user_id'] )
5572
		) {
5573
			// Authentication successful.
5574
			$this->rest_authentication_status = true;
5575
			return $verified['user_id'];
5576
		}
5577
5578
		// Something else went wrong.  Probably a signature error.
5579
		$this->rest_authentication_status = new WP_Error(
5580
			'rest_invalid_signature',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5581
			__( 'The request is not signed correctly.', 'jetpack' ),
5582
			array( 'status' => 400 )
5583
		);
5584
		return null;
5585
	}
5586
5587
	/**
5588
	 * Report authentication status to the WP REST API.
5589
	 *
5590
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5591
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5592
	 */
5593
	public function wp_rest_authentication_errors( $value ) {
5594
		if ( $value !== null ) {
5595
			return $value;
5596
		}
5597
		return $this->rest_authentication_status;
5598
	}
5599
5600
	/**
5601
	 * Add our nonce to this request.
5602
	 *
5603
	 * @deprecated since 7.7.0
5604
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5605
	 *
5606
	 * @param int    $timestamp Timestamp of the request.
5607
	 * @param string $nonce     Nonce string.
5608
	 */
5609 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5610
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5611
5612
		if ( ! $this->connection_manager ) {
5613
			$this->connection_manager = new Connection_Manager();
5614
		}
5615
5616
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5617
	}
5618
5619
	/**
5620
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5621
	 * Capture it here so we can verify the signature later.
5622
	 *
5623
	 * @deprecated since 7.7.0
5624
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5625
	 *
5626
	 * @param array $methods XMLRPC methods.
5627
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5628
	 */
5629 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5630
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5631
5632
		if ( ! $this->connection_manager ) {
5633
			$this->connection_manager = new Connection_Manager();
5634
		}
5635
5636
		return $this->connection_manager->xmlrpc_methods( $methods );
5637
	}
5638
5639
	/**
5640
	 * Register additional public XMLRPC methods.
5641
	 *
5642
	 * @deprecated since 7.7.0
5643
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5644
	 *
5645
	 * @param array $methods Public XMLRPC methods.
5646
	 * @return array Public XMLRPC methods, with the getOptions one.
5647
	 */
5648 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5649
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5650
5651
		if ( ! $this->connection_manager ) {
5652
			$this->connection_manager = new Connection_Manager();
5653
		}
5654
5655
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5656
	}
5657
5658
	/**
5659
	 * Handles a getOptions XMLRPC method call.
5660
	 *
5661
	 * @deprecated since 7.7.0
5662
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5663
	 *
5664
	 * @param array $args method call arguments.
5665
	 * @return array an amended XMLRPC server options array.
5666
	 */
5667 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5668
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5669
5670
		if ( ! $this->connection_manager ) {
5671
			$this->connection_manager = new Connection_Manager();
5672
		}
5673
5674
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

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

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

Loading history...
5675
	}
5676
5677
	/**
5678
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5679
	 *
5680
	 * @deprecated since 7.7.0
5681
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5682
	 *
5683
	 * @param array $options Standard Core options.
5684
	 * @return array Amended options.
5685
	 */
5686 View Code Duplication
	public function xmlrpc_options( $options ) {
5687
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5688
5689
		if ( ! $this->connection_manager ) {
5690
			$this->connection_manager = new Connection_Manager();
5691
		}
5692
5693
		return $this->connection_manager->xmlrpc_options( $options );
5694
	}
5695
5696
	/**
5697
	 * Cleans nonces that were saved when calling ::add_nonce.
5698
	 *
5699
	 * @deprecated since 7.7.0
5700
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5701
	 *
5702
	 * @param bool $all whether to clean even non-expired nonces.
5703
	 */
5704
	public static function clean_nonces( $all = false ) {
5705
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5706
		return self::connection()->clean_nonces( $all );
5707
	}
5708
5709
	/**
5710
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5711
	 * SET: state( $key, $value );
5712
	 * GET: $value = state( $key );
5713
	 *
5714
	 * @param string $key
0 ignored issues
show
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

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

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

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

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

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

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

Loading history...
6246
		}
6247
6248
		// Strip www and protocols
6249
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6250
		return $url;
6251
	}
6252
6253
	/**
6254
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6255
	 *
6256
	 * @since 4.4.0
6257
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6258
	 *
6259
	 * @param array $response
6260
	 * @return array Array of the local urls, wpcom urls, and error code
6261
	 */
6262
	public static function get_sync_error_idc_option( $response = array() ) {
6263
		// Since the local options will hit the database directly, store the values
6264
		// in a transient to allow for autoloading and caching on subsequent views.
6265
		$local_options = get_transient( 'jetpack_idc_local' );
6266
		if ( false === $local_options ) {
6267
			$local_options = array(
6268
				'home'    => Functions::home_url(),
6269
				'siteurl' => Functions::site_url(),
6270
			);
6271
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6272
		}
6273
6274
		$options = array_merge( $local_options, $response );
6275
6276
		$returned_values = array();
6277
		foreach ( $options as $key => $option ) {
6278
			if ( 'error_code' === $key ) {
6279
				$returned_values[ $key ] = $option;
6280
				continue;
6281
			}
6282
6283
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6284
				continue;
6285
			}
6286
6287
			$returned_values[ $key ] = $normalized_url;
6288
		}
6289
6290
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6291
6292
		return $returned_values;
6293
	}
6294
6295
	/**
6296
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6297
	 * If set to true, the site will be put into staging mode.
6298
	 *
6299
	 * @since 4.3.2
6300
	 * @return bool
6301
	 */
6302
	public static function sync_idc_optin() {
6303
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6304
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6305
		} else {
6306
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6307
		}
6308
6309
		/**
6310
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6311
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6312
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6313
		 *
6314
		 * @since 4.3.2
6315
		 *
6316
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6317
		 */
6318
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6319
	}
6320
6321
	/**
6322
	 * Maybe Use a .min.css stylesheet, maybe not.
6323
	 *
6324
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6325
	 */
6326
	public static function maybe_min_asset( $url, $path, $plugin ) {
6327
		// Short out on things trying to find actual paths.
6328
		if ( ! $path || empty( $plugin ) ) {
6329
			return $url;
6330
		}
6331
6332
		$path = ltrim( $path, '/' );
6333
6334
		// Strip out the abspath.
6335
		$base = dirname( plugin_basename( $plugin ) );
6336
6337
		// Short out on non-Jetpack assets.
6338
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6339
			return $url;
6340
		}
6341
6342
		// File name parsing.
6343
		$file              = "{$base}/{$path}";
6344
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6345
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6346
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6347
		$extension         = array_shift( $file_name_parts_r );
6348
6349
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6350
			// Already pointing at the minified version.
6351
			if ( 'min' === $file_name_parts_r[0] ) {
6352
				return $url;
6353
			}
6354
6355
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6356
			if ( file_exists( $min_full_path ) ) {
6357
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6358
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6359
				if ( 'css' === $extension ) {
6360
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6361
					self::$min_assets[ $key ] = $path;
6362
				}
6363
			}
6364
		}
6365
6366
		return $url;
6367
	}
6368
6369
	/**
6370
	 * If the asset is minified, let's flag .min as the suffix.
6371
	 *
6372
	 * Attached to `style_loader_src` filter.
6373
	 *
6374
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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