Completed
Push — try/move-comment-likes-to-pack... ( 1d1808...10f739 )
by
unknown
11:06 queued 04:43
created

class.jetpack.php (63 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
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * The handles of scripts that can be loaded asynchronously.
86
	 *
87
	 * @var array
88
	 */
89
	public $async_script_handles = array(
90
		'woocommerce-analytics',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
115
	);
116
117
	/**
118
	 * Map of roles we care about, and their corresponding minimum capabilities.
119
	 *
120
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
121
	 *
122
	 * @access public
123
	 * @static
124
	 *
125
	 * @var array
126
	 */
127
	public static $capability_translations = array(
128
		'administrator' => 'manage_options',
129
		'editor'        => 'edit_others_posts',
130
		'author'        => 'publish_posts',
131
		'contributor'   => 'edit_posts',
132
		'subscriber'    => 'read',
133
	);
134
135
	/**
136
	 * Map of modules that have conflicts with plugins and should not be auto-activated
137
	 * if the plugins are active.  Used by filter_default_modules
138
	 *
139
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
140
	 * change `module-slug` and add this to your plugin:
141
	 *
142
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
143
	 * function my_jetpack_get_default_modules( $modules ) {
144
	 *     return array_diff( $modules, array( 'module-slug' ) );
145
	 * }
146
	 *
147
	 * @var array
148
	 */
149
	private $conflicting_plugins = array(
150
		'comments'          => array(
151
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
152
			'Disqus'                               => 'disqus-comment-system/disqus.php',
153
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
154
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
155
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
156
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
157
		),
158
		'contact-form'      => array(
159
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
160
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
161
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
162
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
163
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
164
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
165
		),
166
		'minileven'         => array(
167
			'WPtouch'                              => 'wptouch/wptouch.php',
168
		),
169
		'latex'             => array(
170
			'LaTeX for WordPress'                  => 'latex/latex.php',
171
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
172
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
173
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
174
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
175
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
176
		),
177
		'protect'           => array(
178
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
179
			'Captcha'                              => 'captcha/captcha.php',
180
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
181
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
182
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
183
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
184
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
185
			'Security-protection'                  => 'security-protection/security-protection.php',
186
			'Login Security'                       => 'login-security/login-security.php',
187
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
188
			'Wordfence Security'                   => 'wordfence/wordfence.php',
189
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
190
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
191
		),
192
		'random-redirect'   => array(
193
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
194
		),
195
		'related-posts'     => array(
196
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
197
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
198
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
199
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
200
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
201
			'outbrain'                             => 'outbrain/outbrain.php',
202
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
203
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
204
		),
205
		'sharedaddy'        => array(
206
			'AddThis'                              => 'addthis/addthis_social_widget.php',
207
			'Add To Any'                           => 'add-to-any/add-to-any.php',
208
			'ShareThis'                            => 'share-this/sharethis.php',
209
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
210
		),
211
		'seo-tools' => array(
212
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
213
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
214
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
215
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
216
			'The SEO Framework'                    => 'autodescription/autodescription.php',
217
		),
218
		'verification-tools' => array(
219
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
220
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
221
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
222
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
223
			'The SEO Framework'                    => 'autodescription/autodescription.php',
224
		),
225
		'widget-visibility' => array(
226
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
227
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
228
		),
229
		'sitemaps' => array(
230
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
231
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
232
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
233
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
234
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
235
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
236
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
237
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
238
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
239
			'The SEO Framework'                    => 'autodescription/autodescription.php',
240
			'Sitemap'                              => 'sitemap/sitemap.php',
241
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
242
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
243
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
244
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
245
		),
246
		'lazy-images' => array(
247
			'Lazy Load'              => 'lazy-load/lazy-load.php',
248
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
249
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
250
		),
251
	);
252
253
	/**
254
	 * Plugins for which we turn off our Facebook OG Tags implementation.
255
	 *
256
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
257
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
258
	 *
259
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
260
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
261
	 */
262
	private $open_graph_conflicting_plugins = array(
263
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
264
		                                                         // 2 Click Social Media Buttons
265
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
266
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
267
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
268
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
269
		                                                         // Open Graph Meta Tags by Heateor
270
		'facebook/facebook.php',                                 // Facebook (official plugin)
271
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
272
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
273
		                                                         // Facebook Featured Image & OG Meta Tags
274
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
275
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
276
		                                                         // Facebook Open Graph Meta Tags for WordPress
277
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
278
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
279
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
280
		                                                         // Fedmich's Facebook Open Graph Meta
281
		'network-publisher/networkpub.php',                      // Network Publisher
282
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
283
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
284
		                                                         // NextScripts SNAP
285
		'og-tags/og-tags.php',                                   // OG Tags
286
		'opengraph/opengraph.php',                               // Open Graph
287
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
288
		                                                         // Open Graph Protocol Framework
289
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
290
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
291
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
292
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
293
		'sharepress/sharepress.php',                             // SharePress
294
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
295
		'social-discussions/social-discussions.php',             // Social Discussions
296
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
297
		'socialize/socialize.php',                               // Socialize
298
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
299
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
300
		                                                         // Tweet, Like, Google +1 and Share
301
		'wordbooker/wordbooker.php',                             // Wordbooker
302
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
303
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
304
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
305
		                                                         // WP Facebook Like Send & Open Graph Meta
306
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
307
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
308
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
309
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
310
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
311
	);
312
313
	/**
314
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
315
	 */
316
	private $twitter_cards_conflicting_plugins = array(
317
	//	'twitter/twitter.php',                       // The official one handles this on its own.
318
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
319
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
320
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
321
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
322
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
323
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
324
		'twitter-cards/twitter-cards.php',           // Twitter Cards
325
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
326
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
327
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
328
	);
329
330
	/**
331
	 * Message to display in admin_notice
332
	 * @var string
333
	 */
334
	public $message = '';
335
336
	/**
337
	 * Error to display in admin_notice
338
	 * @var string
339
	 */
340
	public $error = '';
341
342
	/**
343
	 * Modules that need more privacy description.
344
	 * @var string
345
	 */
346
	public $privacy_checks = '';
347
348
	/**
349
	 * Stats to record once the page loads
350
	 *
351
	 * @var array
352
	 */
353
	public $stats = array();
354
355
	/**
356
	 * Jetpack_Sync object
357
	 */
358
	public $sync;
359
360
	/**
361
	 * Verified data for JSON authorization request
362
	 */
363
	public $json_api_authorization_request = array();
364
365
	/**
366
	 * @var \Automattic\Jetpack\Connection\Manager
367
	 */
368
	protected $connection_manager;
369
370
	/**
371
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
372
	 */
373
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
374
375
	/**
376
	 * Holds the singleton instance of this class
377
	 * @since 2.3.3
378
	 * @var Jetpack
379
	 */
380
	static $instance = false;
381
382
	/**
383
	 * Singleton
384
	 * @static
385
	 */
386
	public static function init() {
387
		if ( ! self::$instance ) {
388
			self::$instance = new Jetpack;
389
390
			self::$instance->plugin_upgrade();
391
		}
392
393
		return self::$instance;
394
	}
395
396
	/**
397
	 * Must never be called statically
398
	 */
399
	function plugin_upgrade() {
400
		if ( Jetpack::is_active() ) {
401
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
402
			if ( JETPACK__VERSION != $version ) {
403
				// Prevent multiple upgrades at once - only a single process should trigger
404
				// an upgrade to avoid stampedes
405
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
406
					return;
407
				}
408
409
				// Set a short lock to prevent multiple instances of the upgrade
410
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
411
412
				// check which active modules actually exist and remove others from active_modules list
413
				$unfiltered_modules = Jetpack::get_active_modules();
414
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
415
				if ( array_diff( $unfiltered_modules, $modules ) ) {
416
					Jetpack::update_active_modules( $modules );
417
				}
418
419
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
420
421
				// Upgrade to 4.3.0
422
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
423
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
424
				}
425
426
				// Make sure Markdown for posts gets turned back on
427
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
428
					update_option( 'wpcom_publish_posts_with_markdown', true );
429
				}
430
431
				if ( did_action( 'wp_loaded' ) ) {
432
					self::upgrade_on_load();
433
				} else {
434
					add_action(
435
						'wp_loaded',
436
						array( __CLASS__, 'upgrade_on_load' )
437
					);
438
				}
439
			}
440
		}
441
	}
442
443
	/**
444
	 * Runs upgrade routines that need to have modules loaded.
445
	 */
446
	static function upgrade_on_load() {
447
448
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
449
		// This can happen in case Jetpack has been just upgraded and is
450
		// being initialized late during the page load. In this case we wait
451
		// until the next proper admin page load with Jetpack active.
452
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
453
			delete_transient( self::$plugin_upgrade_lock_key );
454
455
			return;
456
		}
457
458
		Jetpack::maybe_set_version_option();
459
460
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
461
			Jetpack_Widget_Conditions::migrate_post_type_rules();
462
		}
463
464
		if (
465
			class_exists( 'Jetpack_Sitemap_Manager' )
466
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
467
		) {
468
			do_action( 'jetpack_sitemaps_purge_data' );
469
		}
470
471
		// Delete old stats cache
472
		delete_option( 'jetpack_restapi_stats_cache' );
473
474
		delete_transient( self::$plugin_upgrade_lock_key );
475
	}
476
477
	/**
478
	 * Saves all the currently active modules to options.
479
	 * Also fires Action hooks for each newly activated and deactivated module.
480
	 *
481
	 * @param $modules Array Array of active modules to be saved in options.
482
	 *
483
	 * @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...
484
	 */
485
	static function update_active_modules( $modules ) {
486
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
487
		$active_modules       = Jetpack::get_active_modules();
488
		$new_active_modules   = array_diff( $modules, $current_modules );
489
		$new_inactive_modules = array_diff( $active_modules, $modules );
490
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
491
		$reindexed_modules    = array_values( $new_current_modules );
492
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
493
494
		foreach ( $new_active_modules as $module ) {
495
			/**
496
			 * Fires when a specific module is activated.
497
			 *
498
			 * @since 1.9.0
499
			 *
500
			 * @param string $module Module slug.
501
			 * @param boolean $success whether the module was activated. @since 4.2
502
			 */
503
			do_action( 'jetpack_activate_module', $module, $success );
504
			/**
505
			 * Fires when a module is activated.
506
			 * The dynamic part of the filter, $module, is the module slug.
507
			 *
508
			 * @since 1.9.0
509
			 *
510
			 * @param string $module Module slug.
511
			 */
512
			do_action( "jetpack_activate_module_$module", $module );
513
		}
514
515
		foreach ( $new_inactive_modules as $module ) {
516
			/**
517
			 * Fired after a module has been deactivated.
518
			 *
519
			 * @since 4.2.0
520
			 *
521
			 * @param string $module Module slug.
522
			 * @param boolean $success whether the module was deactivated.
523
			 */
524
			do_action( 'jetpack_deactivate_module', $module, $success );
525
			/**
526
			 * Fires when a module is deactivated.
527
			 * The dynamic part of the filter, $module, is the module slug.
528
			 *
529
			 * @since 1.9.0
530
			 *
531
			 * @param string $module Module slug.
532
			 */
533
			do_action( "jetpack_deactivate_module_$module", $module );
534
		}
535
536
		return $success;
537
	}
538
539
	static function delete_active_modules() {
540
		self::update_active_modules( array() );
541
	}
542
543
	/**
544
	 * Constructor.  Initializes WordPress hooks
545
	 */
546
	private function __construct() {
547
		/*
548
		 * Check for and alert any deprecated hooks
549
		 */
550
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
551
552
		/*
553
		 * Enable enhanced handling of previewing sites in Calypso
554
		 */
555
		if ( Jetpack::is_active() ) {
556
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
557
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
558
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
559
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
560
		}
561
562
		if ( self::jetpack_tos_agreed() ) {
563
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
564
			add_action( 'init', array( $tracking, 'init' ) );
565
		}
566
567
568
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
569
			return function() {
570
				return wp_generate_password( 32, false );
571
			};
572
		} );
573
574
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
575
576
		$this->connection_manager = new Connection_Manager();
577
		$this->connection_manager->init();
578
579
		/*
580
		 * Load things that should only be in Network Admin.
581
		 *
582
		 * For now blow away everything else until a more full
583
		 * understanding of what is needed at the network level is
584
		 * available
585
		 */
586
		if ( is_multisite() ) {
587
			$network = Jetpack_Network::init();
588
			$network->set_connection( $this->connection_manager );
589
		}
590
591
		add_filter(
592
			'jetpack_signature_check_token',
593
			array( __CLASS__, 'verify_onboarding_token' ),
594
			10,
595
			3
596
		);
597
598
		/**
599
		 * Prepare Gutenberg Editor functionality
600
		 */
601
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
602
		Jetpack_Gutenberg::init();
603
		Jetpack_Gutenberg::load_independent_blocks();
604
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
605
606
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
607
608
		// Unlink user before deleting the user from WP.com.
609
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
610
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
611
612
		// Initialize remote file upload request handlers.
613
		$this->add_remote_request_handlers();
614
615
		if ( Jetpack::is_active() ) {
616
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
617
618
			Jetpack_Heartbeat::init();
619
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
620
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
621
				Jetpack_Search_Performance_Logger::init();
622
			}
623
		}
624
625
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
626
627
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
628
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
629
630
		add_action( 'admin_init', array( $this, 'admin_init' ) );
631
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
632
633
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
634
635
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
636
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
637
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
638
639
		// returns HTTPS support status
640
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
641
642
		// JITM AJAX callback function
643
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
644
645
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
646
647
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
648
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
649
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
650
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
651
652
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
653
654
		/**
655
		 * These actions run checks to load additional files.
656
		 * They check for external files or plugins, so they need to run as late as possible.
657
		 */
658
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
659
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
660
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
661
662
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
663
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
664
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
665
666
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
667
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
668
669
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
670
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
671
672
		// A filter to control all just in time messages
673
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
674
675
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
676
677
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
678
		// We should make sure to only do this for front end links.
679
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
680
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
681
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
682
683
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
684
			//so they point moderation links on emails to Calypso
685
			jetpack_require_lib( 'functions.wp-notify' );
686
		}
687
688
		// Hide edit post link if mobile app.
689
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
690
			add_filter( 'edit_post_link', '__return_empty_string' );
691
		}
692
693
		// Update the Jetpack plan from API on heartbeats
694
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
695
696
		/**
697
		 * This is the hack to concatenate all css files into one.
698
		 * For description and reasoning see the implode_frontend_css method
699
		 *
700
		 * Super late priority so we catch all the registered styles
701
		 */
702
		if( !is_admin() ) {
703
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
704
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
705
		}
706
707
708
		/**
709
		 * These are sync actions that we need to keep track of for jitms
710
		 */
711
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
712
713
		// Actually push the stats on shutdown.
714
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
715
			add_action( 'shutdown', array( $this, 'push_stats' ) );
716
		}
717
718
		/*
719
		 * Load some scripts asynchronously.
720
		 */
721
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
722
	}
723
724
	/**
725
	 * Sets up the XMLRPC request handlers.
726
	 *
727
	 * @deprecated since 7.7.0
728
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
729
	 *
730
	 * @param Array                 $request_params Incoming request parameters.
731
	 * @param Boolean               $is_active      Whether the connection is currently active.
732
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
733
	 * @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...
734
	 */
735
	public function setup_xmlrpc_handlers(
736
		$request_params,
737
		$is_active,
738
		$is_signed,
739
		Jetpack_XMLRPC_Server $xmlrpc_server = null
740
	) {
741
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
742
		return $this->connection_manager->setup_xmlrpc_handlers(
743
			$request_params,
744
			$is_active,
745
			$is_signed,
746
			$xmlrpc_server
747
		);
748
	}
749
750
	/**
751
	 * Initialize REST API registration connector.
752
	 *
753
	 * @deprecated since 7.7.0
754
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
755
	 */
756
	public function initialize_rest_api_registration_connector() {
757
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
758
		$this->connection_manager->initialize_rest_api_registration_connector();
759
	}
760
761
	/**
762
	 * This is ported over from the manage module, which has been deprecated and baked in here.
763
	 *
764
	 * @param $domains
765
	 */
766
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
767
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
768
	}
769
770
	/**
771
	 * Return $domains, with 'wordpress.com' appended.
772
	 * This is ported over from the manage module, which has been deprecated and baked in here.
773
	 *
774
	 * @param $domains
775
	 * @return array
776
	 */
777
	function allow_wpcom_domain( $domains ) {
778
		if ( empty( $domains ) ) {
779
			$domains = array();
780
		}
781
		$domains[] = 'wordpress.com';
782
		return array_unique( $domains );
783
	}
784
785
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
786
		$post = get_post( $post_id );
787
788
		if ( empty( $post ) ) {
789
			return $default_url;
790
		}
791
792
		$post_type = $post->post_type;
793
794
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
795
		// https://en.support.wordpress.com/custom-post-types/
796
		$allowed_post_types = array(
797
			'post' => 'post',
798
			'page' => 'page',
799
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
800
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
801
		);
802
803
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
804
			return $default_url;
805
		}
806
807
		$path_prefix = $allowed_post_types[ $post_type ];
808
809
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
810
811
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
812
	}
813
814
	function point_edit_comment_links_to_calypso( $url ) {
815
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
816
		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...
817
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
818
			Jetpack::build_raw_urls( get_home_url() ),
819
			$query_args['amp;c']
820
		) );
821
	}
822
823
	function jetpack_track_last_sync_callback( $params ) {
824
		/**
825
		 * Filter to turn off jitm caching
826
		 *
827
		 * @since 5.4.0
828
		 *
829
		 * @param bool false Whether to cache just in time messages
830
		 */
831
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
832
			return $params;
833
		}
834
835
		if ( is_array( $params ) && isset( $params[0] ) ) {
836
			$option = $params[0];
837
			if ( 'active_plugins' === $option ) {
838
				// use the cache if we can, but not terribly important if it gets evicted
839
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
840
			}
841
		}
842
843
		return $params;
844
	}
845
846
	function jetpack_connection_banner_callback() {
847
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
848
849
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
850
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
851
			wp_send_json_success();
852
		}
853
854
		wp_die();
855
	}
856
857
	/**
858
	 * Removes all XML-RPC methods that are not `jetpack.*`.
859
	 * Only used in our alternate XML-RPC endpoint, where we want to
860
	 * ensure that Core and other plugins' methods are not exposed.
861
	 *
862
	 * @deprecated since 7.7.0
863
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
864
	 *
865
	 * @param array $methods A list of registered WordPress XMLRPC methods.
866
	 * @return array Filtered $methods
867
	 */
868
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
869
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
870
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
871
	}
872
873
	/**
874
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
875
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
876
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
877
	 * which is accessible via a different URI. Most of the below is copied directly
878
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
879
	 *
880
	 * @deprecated since 7.7.0
881
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
882
	 */
883
	public function alternate_xmlrpc() {
884
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
885
		$this->connection_manager->alternate_xmlrpc();
886
	}
887
888
	/**
889
	 * The callback for the JITM ajax requests.
890
	 */
891
	function jetpack_jitm_ajax_callback() {
892
		// Check for nonce
893
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
894
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
895
		}
896
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
897
			$module_slug = $_REQUEST['jitmModule'];
898
			Jetpack::log( 'activate', $module_slug );
899
			Jetpack::activate_module( $module_slug, false, false );
900
			Jetpack::state( 'message', 'no_message' );
901
902
			//A Jetpack module is being activated through a JITM, track it
903
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
904
			$this->do_stats( 'server_side' );
905
906
			wp_send_json_success();
907
		}
908
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
909
			// get the hide_jitm options array
910
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
911
			$module_slug = $_REQUEST['jitmModule'];
912
913
			if( ! $jetpack_hide_jitm ) {
914
				$jetpack_hide_jitm = array(
915
					$module_slug => 'hide'
916
				);
917
			} else {
918
				$jetpack_hide_jitm[$module_slug] = 'hide';
919
			}
920
921
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
922
923
			//jitm is being dismissed forever, track it
924
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
925
			$this->do_stats( 'server_side' );
926
927
			wp_send_json_success();
928
		}
929 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
930
			$module_slug = $_REQUEST['jitmModule'];
931
932
			// User went to WordPress.com, track this
933
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
934
			$this->do_stats( 'server_side' );
935
936
			wp_send_json_success();
937
		}
938 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
939
			$track = $_REQUEST['jitmModule'];
940
941
			// User is viewing JITM, track it.
942
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
943
			$this->do_stats( 'server_side' );
944
945
			wp_send_json_success();
946
		}
947
	}
948
949
	/**
950
	 * If there are any stats that need to be pushed, but haven't been, push them now.
951
	 */
952
	function push_stats() {
953
		if ( ! empty( $this->stats ) ) {
954
			$this->do_stats( 'server_side' );
955
		}
956
	}
957
958
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
959
		switch( $cap ) {
960
			case 'jetpack_connect' :
961
			case 'jetpack_reconnect' :
962
				if ( Jetpack::is_development_mode() ) {
963
					$caps = array( 'do_not_allow' );
964
					break;
965
				}
966
				/**
967
				 * Pass through. If it's not development mode, these should match disconnect.
968
				 * Let users disconnect if it's development mode, just in case things glitch.
969
				 */
970
			case 'jetpack_disconnect' :
971
				/**
972
				 * In multisite, can individual site admins manage their own connection?
973
				 *
974
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
975
				 */
976
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
977
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
978
						/**
979
						 * We need to update the option name -- it's terribly unclear which
980
						 * direction the override goes.
981
						 *
982
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
983
						 */
984
						$caps = array( 'do_not_allow' );
985
						break;
986
					}
987
				}
988
989
				$caps = array( 'manage_options' );
990
				break;
991
			case 'jetpack_manage_modules' :
992
			case 'jetpack_activate_modules' :
993
			case 'jetpack_deactivate_modules' :
994
				$caps = array( 'manage_options' );
995
				break;
996
			case 'jetpack_configure_modules' :
997
				$caps = array( 'manage_options' );
998
				break;
999
			case 'jetpack_manage_autoupdates' :
1000
				$caps = array(
1001
					'manage_options',
1002
					'update_plugins',
1003
				);
1004
				break;
1005
			case 'jetpack_network_admin_page':
1006
			case 'jetpack_network_settings_page':
1007
				$caps = array( 'manage_network_plugins' );
1008
				break;
1009
			case 'jetpack_network_sites_page':
1010
				$caps = array( 'manage_sites' );
1011
				break;
1012
			case 'jetpack_admin_page' :
1013
				if ( Jetpack::is_development_mode() ) {
1014
					$caps = array( 'manage_options' );
1015
					break;
1016
				} else {
1017
					$caps = array( 'read' );
1018
				}
1019
				break;
1020
			case 'jetpack_connect_user' :
1021
				if ( Jetpack::is_development_mode() ) {
1022
					$caps = array( 'do_not_allow' );
1023
					break;
1024
				}
1025
				$caps = array( 'read' );
1026
				break;
1027
		}
1028
		return $caps;
1029
	}
1030
1031
	/**
1032
	 * Require a Jetpack authentication.
1033
	 *
1034
	 * @deprecated since 7.7.0
1035
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1036
	 */
1037
	public function require_jetpack_authentication() {
1038
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1039
		$this->connection_manager->require_jetpack_authentication();
1040
	}
1041
1042
	/**
1043
	 * Load language files
1044
	 * @action plugins_loaded
1045
	 */
1046
	public static function plugin_textdomain() {
1047
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1048
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1049
	}
1050
1051
	/**
1052
	 * Register assets for use in various modules and the Jetpack admin page.
1053
	 *
1054
	 * @uses wp_script_is, wp_register_script, plugins_url
1055
	 * @action wp_loaded
1056
	 * @return null
1057
	 */
1058
	public function register_assets() {
1059
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1060
			wp_register_script(
1061
				'spin',
1062
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1063
				false,
1064
				'1.3'
1065
			);
1066
		}
1067
1068 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1069
			wp_register_script(
1070
				'jquery.spin',
1071
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1072
				array( 'jquery', 'spin' ),
1073
				'1.3'
1074
			);
1075
		}
1076
1077 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1078
			wp_register_script(
1079
				'jetpack-gallery-settings',
1080
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1081
				array( 'media-views' ),
1082
				'20121225'
1083
			);
1084
		}
1085
1086 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1087
			wp_register_script(
1088
				'jetpack-twitter-timeline',
1089
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1090
				array( 'jquery' ),
1091
				'4.0.0',
1092
				true
1093
			);
1094
		}
1095
1096
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1097
			wp_register_script(
1098
				'jetpack-facebook-embed',
1099
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1100
				array( 'jquery' ),
1101
				null,
1102
				true
1103
			);
1104
1105
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1106
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1107
			if ( ! is_numeric( $fb_app_id ) ) {
1108
				$fb_app_id = '';
1109
			}
1110
			wp_localize_script(
1111
				'jetpack-facebook-embed',
1112
				'jpfbembed',
1113
				array(
1114
					'appid' => $fb_app_id,
1115
					'locale' => $this->get_locale(),
1116
				)
1117
			);
1118
		}
1119
1120
		/**
1121
		 * As jetpack_register_genericons is by default fired off a hook,
1122
		 * the hook may have already fired by this point.
1123
		 * So, let's just trigger it manually.
1124
		 */
1125
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1126
		jetpack_register_genericons();
1127
1128
		/**
1129
		 * Register the social logos
1130
		 */
1131
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1132
		jetpack_register_social_logos();
1133
1134 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1135
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1136
	}
1137
1138
	/**
1139
	 * Guess locale from language code.
1140
	 *
1141
	 * @param string $lang Language code.
1142
	 * @return string|bool
1143
	 */
1144 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1145
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1146
			return 'en_US';
1147
		}
1148
1149
		if ( ! class_exists( 'GP_Locales' ) ) {
1150
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1151
				return false;
1152
			}
1153
1154
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1155
		}
1156
1157
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1158
			// WP.com: get_locale() returns 'it'
1159
			$locale = GP_Locales::by_slug( $lang );
1160
		} else {
1161
			// Jetpack: get_locale() returns 'it_IT';
1162
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1163
		}
1164
1165
		if ( ! $locale ) {
1166
			return false;
1167
		}
1168
1169
		if ( empty( $locale->facebook_locale ) ) {
1170
			if ( empty( $locale->wp_locale ) ) {
1171
				return false;
1172
			} else {
1173
				// Facebook SDK is smart enough to fall back to en_US if a
1174
				// locale isn't supported. Since supported Facebook locales
1175
				// can fall out of sync, we'll attempt to use the known
1176
				// wp_locale value and rely on said fallback.
1177
				return $locale->wp_locale;
1178
			}
1179
		}
1180
1181
		return $locale->facebook_locale;
1182
	}
1183
1184
	/**
1185
	 * Get the locale.
1186
	 *
1187
	 * @return string|bool
1188
	 */
1189
	function get_locale() {
1190
		$locale = $this->guess_locale_from_lang( get_locale() );
1191
1192
		if ( ! $locale ) {
1193
			$locale = 'en_US';
1194
		}
1195
1196
		return $locale;
1197
	}
1198
1199
	/**
1200
	 * Device Pixels support
1201
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1202
	 */
1203
	function devicepx() {
1204
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1205
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1206
		}
1207
	}
1208
1209
	/**
1210
	 * Return the network_site_url so that .com knows what network this site is a part of.
1211
	 * @param  bool $option
1212
	 * @return string
1213
	 */
1214
	public function jetpack_main_network_site_option( $option ) {
1215
		return network_site_url();
1216
	}
1217
	/**
1218
	 * Network Name.
1219
	 */
1220
	static function network_name( $option = null ) {
1221
		global $current_site;
1222
		return $current_site->site_name;
1223
	}
1224
	/**
1225
	 * Does the network allow new user and site registrations.
1226
	 * @return string
1227
	 */
1228
	static function network_allow_new_registrations( $option = null ) {
1229
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1230
	}
1231
	/**
1232
	 * Does the network allow admins to add new users.
1233
	 * @return boolian
1234
	 */
1235
	static function network_add_new_users( $option = null ) {
1236
		return (bool) get_site_option( 'add_new_users' );
1237
	}
1238
	/**
1239
	 * File upload psace left per site in MB.
1240
	 *  -1 means NO LIMIT.
1241
	 * @return number
1242
	 */
1243
	static function network_site_upload_space( $option = null ) {
1244
		// value in MB
1245
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1246
	}
1247
1248
	/**
1249
	 * Network allowed file types.
1250
	 * @return string
1251
	 */
1252
	static function network_upload_file_types( $option = null ) {
1253
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1254
	}
1255
1256
	/**
1257
	 * Maximum file upload size set by the network.
1258
	 * @return number
1259
	 */
1260
	static function network_max_upload_file_size( $option = null ) {
1261
		// value in KB
1262
		return get_site_option( 'fileupload_maxk', 300 );
1263
	}
1264
1265
	/**
1266
	 * Lets us know if a site allows admins to manage the network.
1267
	 * @return array
1268
	 */
1269
	static function network_enable_administration_menus( $option = null ) {
1270
		return get_site_option( 'menu_items' );
1271
	}
1272
1273
	/**
1274
	 * If a user has been promoted to or demoted from admin, we need to clear the
1275
	 * jetpack_other_linked_admins transient.
1276
	 *
1277
	 * @since 4.3.2
1278
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1279
	 *
1280
	 * @param int    $user_id   The user ID whose role changed.
1281
	 * @param string $role      The new role.
1282
	 * @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...
1283
	 */
1284
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1285
		if ( 'administrator' == $role
1286
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1287
			|| is_null( $old_roles )
1288
		) {
1289
			delete_transient( 'jetpack_other_linked_admins' );
1290
		}
1291
	}
1292
1293
	/**
1294
	 * Checks to see if there are any other users available to become primary
1295
	 * Users must both:
1296
	 * - Be linked to wpcom
1297
	 * - Be an admin
1298
	 *
1299
	 * @return mixed False if no other users are linked, Int if there are.
1300
	 */
1301
	static function get_other_linked_admins() {
1302
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1303
1304
		if ( false === $other_linked_users ) {
1305
			$admins = get_users( array( 'role' => 'administrator' ) );
1306
			if ( count( $admins ) > 1 ) {
1307
				$available = array();
1308
				foreach ( $admins as $admin ) {
1309
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1310
						$available[] = $admin->ID;
1311
					}
1312
				}
1313
1314
				$count_connected_admins = count( $available );
1315
				if ( count( $available ) > 1 ) {
1316
					$other_linked_users = $count_connected_admins;
1317
				} else {
1318
					$other_linked_users = 0;
1319
				}
1320
			} else {
1321
				$other_linked_users = 0;
1322
			}
1323
1324
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1325
		}
1326
1327
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1328
	}
1329
1330
	/**
1331
	 * Return whether we are dealing with a multi network setup or not.
1332
	 * The reason we are type casting this is because we want to avoid the situation where
1333
	 * the result is false since when is_main_network_option return false it cases
1334
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1335
	 * database which could be set to anything as opposed to what this function returns.
1336
	 * @param  bool  $option
1337
	 *
1338
	 * @return boolean
1339
	 */
1340
	public function is_main_network_option( $option ) {
1341
		// return '1' or ''
1342
		return (string) (bool) Jetpack::is_multi_network();
1343
	}
1344
1345
	/**
1346
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1347
	 *
1348
	 * @param  string  $option
1349
	 * @return boolean
1350
	 */
1351
	public function is_multisite( $option ) {
1352
		return (string) (bool) is_multisite();
1353
	}
1354
1355
	/**
1356
	 * Implemented since there is no core is multi network function
1357
	 * Right now there is no way to tell if we which network is the dominant network on the system
1358
	 *
1359
	 * @since  3.3
1360
	 * @return boolean
1361
	 */
1362 View Code Duplication
	public static function is_multi_network() {
1363
		global  $wpdb;
1364
1365
		// if we don't have a multi site setup no need to do any more
1366
		if ( ! is_multisite() ) {
1367
			return false;
1368
		}
1369
1370
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1371
		if ( $num_sites > 1 ) {
1372
			return true;
1373
		} else {
1374
			return false;
1375
		}
1376
	}
1377
1378
	/**
1379
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1380
	 * @return null
1381
	 */
1382
	function update_jetpack_main_network_site_option() {
1383
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1384
	}
1385
	/**
1386
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1387
	 *
1388
	 */
1389
	function update_jetpack_network_settings() {
1390
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1391
		// Only sync this info for the main network site.
1392
	}
1393
1394
	/**
1395
	 * Get back if the current site is single user site.
1396
	 *
1397
	 * @return bool
1398
	 */
1399 View Code Duplication
	public static function is_single_user_site() {
1400
		global $wpdb;
1401
1402
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1403
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1404
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1405
		}
1406
		return 1 === (int) $some_users;
1407
	}
1408
1409
	/**
1410
	 * Returns true if the site has file write access false otherwise.
1411
	 * @return string ( '1' | '0' )
1412
	 **/
1413
	public static function file_system_write_access() {
1414
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1415
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1416
		}
1417
1418
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1419
1420
		$filesystem_method = get_filesystem_method();
1421
		if ( $filesystem_method === 'direct' ) {
1422
			return 1;
1423
		}
1424
1425
		ob_start();
1426
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1427
		ob_end_clean();
1428
		if ( $filesystem_credentials_are_stored ) {
1429
			return 1;
1430
		}
1431
		return 0;
1432
	}
1433
1434
	/**
1435
	 * Finds out if a site is using a version control system.
1436
	 * @return string ( '1' | '0' )
1437
	 **/
1438
	public static function is_version_controlled() {
1439
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1440
		return (string) (int) Functions::is_version_controlled();
1441
	}
1442
1443
	/**
1444
	 * Determines whether the current theme supports featured images or not.
1445
	 * @return string ( '1' | '0' )
1446
	 */
1447
	public static function featured_images_enabled() {
1448
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1449
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1450
	}
1451
1452
	/**
1453
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1454
	 *
1455
	 * @deprecated 4.7 use get_avatar_url instead.
1456
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1457
	 * @param int $size Size of the avatar image
1458
	 * @param string $default URL to a default image to use if no avatar is available
1459
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1460
	 *
1461
	 * @return array
1462
	 */
1463
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1464
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1465
		return get_avatar_url( $id_or_email, array(
1466
			'size' => $size,
1467
			'default' => $default,
1468
			'force_default' => $force_display,
1469
		) );
1470
	}
1471
1472
	/**
1473
	 * jetpack_updates is saved in the following schema:
1474
	 *
1475
	 * array (
1476
	 *      'plugins'                       => (int) Number of plugin updates available.
1477
	 *      'themes'                        => (int) Number of theme updates available.
1478
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1479
	 *      'translations'                  => (int) Number of translation updates available.
1480
	 *      'total'                         => (int) Total of all available updates.
1481
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1482
	 * )
1483
	 * @return array
1484
	 */
1485
	public static function get_updates() {
1486
		$update_data = wp_get_update_data();
1487
1488
		// Stores the individual update counts as well as the total count.
1489
		if ( isset( $update_data['counts'] ) ) {
1490
			$updates = $update_data['counts'];
1491
		}
1492
1493
		// If we need to update WordPress core, let's find the latest version number.
1494 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1495
			$cur = get_preferred_from_update_core();
1496
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1497
				$updates['wp_update_version'] = $cur->current;
1498
			}
1499
		}
1500
		return isset( $updates ) ? $updates : array();
1501
	}
1502
1503
	public static function get_update_details() {
1504
		$update_details = array(
1505
			'update_core' => get_site_transient( 'update_core' ),
1506
			'update_plugins' => get_site_transient( 'update_plugins' ),
1507
			'update_themes' => get_site_transient( 'update_themes' ),
1508
		);
1509
		return $update_details;
1510
	}
1511
1512
	public static function refresh_update_data() {
1513
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1514
1515
	}
1516
1517
	public static function refresh_theme_data() {
1518
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1519
	}
1520
1521
	/**
1522
	 * Is Jetpack active?
1523
	 */
1524
	public static function is_active() {
1525
		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...
1526
	}
1527
1528
	/**
1529
	 * Make an API call to WordPress.com for plan status
1530
	 *
1531
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1532
	 *
1533
	 * @return bool True if plan is updated, false if no update
1534
	 */
1535
	public static function refresh_active_plan_from_wpcom() {
1536
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1537
		return Jetpack_Plan::refresh_from_wpcom();
1538
	}
1539
1540
	/**
1541
	 * Get the plan that this Jetpack site is currently using
1542
	 *
1543
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1544
	 * @return array Active Jetpack plan details.
1545
	 */
1546
	public static function get_active_plan() {
1547
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1548
		return Jetpack_Plan::get();
1549
	}
1550
1551
	/**
1552
	 * Determine whether the active plan supports a particular feature
1553
	 *
1554
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1555
	 * @return bool True if plan supports feature, false if not.
1556
	 */
1557
	public static function active_plan_supports( $feature ) {
1558
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1559
		return Jetpack_Plan::supports( $feature );
1560
	}
1561
1562
	/**
1563
	 * Is Jetpack in development (offline) mode?
1564
	 */
1565 View Code Duplication
	public static function is_development_mode() {
1566
		$development_mode = false;
1567
1568
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1569
			$development_mode = JETPACK_DEV_DEBUG;
1570
		} elseif ( $site_url = site_url() ) {
1571
			$development_mode = false === strpos( $site_url, '.' );
1572
		}
1573
1574
		/**
1575
		 * Filters Jetpack's development mode.
1576
		 *
1577
		 * @see https://jetpack.com/support/development-mode/
1578
		 *
1579
		 * @since 2.2.1
1580
		 *
1581
		 * @param bool $development_mode Is Jetpack's development mode active.
1582
		 */
1583
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1584
		return $development_mode;
1585
	}
1586
1587
	/**
1588
	 * Whether the site is currently onboarding or not.
1589
	 * A site is considered as being onboarded if it currently has an onboarding token.
1590
	 *
1591
	 * @since 5.8
1592
	 *
1593
	 * @access public
1594
	 * @static
1595
	 *
1596
	 * @return bool True if the site is currently onboarding, false otherwise
1597
	 */
1598
	public static function is_onboarding() {
1599
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1600
	}
1601
1602
	/**
1603
	 * Determines reason for Jetpack development mode.
1604
	 */
1605
	public static function development_mode_trigger_text() {
1606
		if ( ! Jetpack::is_development_mode() ) {
1607
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1608
		}
1609
1610
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1611
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1612
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1613
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1614
		} else {
1615
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1616
		}
1617
1618
		return $notice;
1619
1620
	}
1621
	/**
1622
	* Get Jetpack development mode notice text and notice class.
1623
	*
1624
	* Mirrors the checks made in Jetpack::is_development_mode
1625
	*
1626
	*/
1627
	public static function show_development_mode_notice() {
1628 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1629
			$notice = sprintf(
1630
			/* translators: %s is a URL */
1631
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1632
				'https://jetpack.com/support/development-mode/'
1633
			);
1634
1635
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1636
1637
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1638
		}
1639
1640
		// Throw up a notice if using a development version and as for feedback.
1641
		if ( Jetpack::is_development_version() ) {
1642
			/* translators: %s is a URL */
1643
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), 'https://jetpack.com/contact-support/beta-group/' );
1644
1645
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1646
		}
1647
		// Throw up a notice if using staging mode
1648
		if ( Jetpack::is_staging_site() ) {
1649
			/* translators: %s is a URL */
1650
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1651
1652
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1653
		}
1654
	}
1655
1656
	/**
1657
	 * Whether Jetpack's version maps to a public release, or a development version.
1658
	 */
1659
	public static function is_development_version() {
1660
		/**
1661
		 * Allows filtering whether this is a development version of Jetpack.
1662
		 *
1663
		 * This filter is especially useful for tests.
1664
		 *
1665
		 * @since 4.3.0
1666
		 *
1667
		 * @param bool $development_version Is this a develoment version of Jetpack?
1668
		 */
1669
		return (bool) apply_filters(
1670
			'jetpack_development_version',
1671
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1672
		);
1673
	}
1674
1675
	/**
1676
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1677
	 */
1678
	public static function is_user_connected( $user_id = false ) {
1679
		return self::connection()->is_user_connected( $user_id );
1680
	}
1681
1682
	/**
1683
	 * Get the wpcom user data of the current|specified connected user.
1684
	 */
1685 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1686
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1687
		if ( ! $user_id ) {
1688
			$user_id = get_current_user_id();
1689
		}
1690
1691
		$transient_key = "jetpack_connected_user_data_$user_id";
1692
1693
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1694
			return $cached_user_data;
1695
		}
1696
1697
		$xml = new Jetpack_IXR_Client( array(
1698
			'user_id' => $user_id,
1699
		) );
1700
		$xml->query( 'wpcom.getUser' );
1701
		if ( ! $xml->isError() ) {
1702
			$user_data = $xml->getResponse();
1703
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1704
			return $user_data;
1705
		}
1706
1707
		return false;
1708
	}
1709
1710
	/**
1711
	 * Get the wpcom email of the current|specified connected user.
1712
	 */
1713
	public static function get_connected_user_email( $user_id = null ) {
1714
		if ( ! $user_id ) {
1715
			$user_id = get_current_user_id();
1716
		}
1717
1718
		$xml = new Jetpack_IXR_Client( array(
1719
			'user_id' => $user_id,
1720
		) );
1721
		$xml->query( 'wpcom.getUserEmail' );
1722
		if ( ! $xml->isError() ) {
1723
			return $xml->getResponse();
1724
		}
1725
		return false;
1726
	}
1727
1728
	/**
1729
	 * Get the wpcom email of the master user.
1730
	 */
1731
	public static function get_master_user_email() {
1732
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1733
		if ( $master_user_id ) {
1734
			return self::get_connected_user_email( $master_user_id );
1735
		}
1736
		return '';
1737
	}
1738
1739
	/**
1740
	 * Whether the current user is the connection owner.
1741
	 *
1742
	 * @deprecated since 7.7
1743
	 *
1744
	 * @return bool Whether the current user is the connection owner.
1745
	 */
1746
	public function current_user_is_connection_owner() {
1747
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1748
		return self::connection()->is_connection_owner();
1749
	}
1750
1751
	/**
1752
	 * Gets current user IP address.
1753
	 *
1754
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1755
	 *
1756
	 * @return string                  Current user IP address.
1757
	 */
1758
	public static function current_user_ip( $check_all_headers = false ) {
1759
		if ( $check_all_headers ) {
1760
			foreach ( array(
1761
				'HTTP_CF_CONNECTING_IP',
1762
				'HTTP_CLIENT_IP',
1763
				'HTTP_X_FORWARDED_FOR',
1764
				'HTTP_X_FORWARDED',
1765
				'HTTP_X_CLUSTER_CLIENT_IP',
1766
				'HTTP_FORWARDED_FOR',
1767
				'HTTP_FORWARDED',
1768
				'HTTP_VIA',
1769
			) as $key ) {
1770
				if ( ! empty( $_SERVER[ $key ] ) ) {
1771
					return $_SERVER[ $key ];
1772
				}
1773
			}
1774
		}
1775
1776
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1777
	}
1778
1779
	/**
1780
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1781
	 */
1782
	function extra_oembed_providers() {
1783
		// Cloudup: https://dev.cloudup.com/#oembed
1784
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1785
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1786
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1787
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1788
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1789
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1790
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1791
	}
1792
1793
	/**
1794
	 * Synchronize connected user role changes
1795
	 */
1796
	function user_role_change( $user_id ) {
1797
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1798
		Users::user_role_change( $user_id );
1799
	}
1800
1801
	/**
1802
	 * Loads the currently active modules.
1803
	 */
1804
	public static function load_modules() {
1805
		if (
1806
			! self::is_active()
1807
			&& ! self::is_development_mode()
1808
			&& ! self::is_onboarding()
1809
			&& (
1810
				! is_multisite()
1811
				|| ! get_site_option( 'jetpack_protect_active' )
1812
			)
1813
		) {
1814
			return;
1815
		}
1816
1817
		$version = Jetpack_Options::get_option( 'version' );
1818 View Code Duplication
		if ( ! $version ) {
1819
			$version = $old_version = JETPACK__VERSION . ':' . time();
1820
			/** This action is documented in class.jetpack.php */
1821
			do_action( 'updating_jetpack_version', $version, false );
1822
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1823
		}
1824
		list( $version ) = explode( ':', $version );
1825
1826
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1827
1828
		$modules_data = array();
1829
1830
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1831
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1832
			$updated_modules = array();
1833
			foreach ( $modules as $module ) {
1834
				$modules_data[ $module ] = Jetpack::get_module( $module );
1835
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1836
					continue;
1837
				}
1838
1839
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1840
					continue;
1841
				}
1842
1843
				$updated_modules[] = $module;
1844
			}
1845
1846
			$modules = array_diff( $modules, $updated_modules );
1847
		}
1848
1849
		$is_development_mode = Jetpack::is_development_mode();
1850
1851
		foreach ( $modules as $index => $module ) {
1852
			// If we're in dev mode, disable modules requiring a connection
1853
			if ( $is_development_mode ) {
1854
				// Prime the pump if we need to
1855
				if ( empty( $modules_data[ $module ] ) ) {
1856
					$modules_data[ $module ] = Jetpack::get_module( $module );
1857
				}
1858
				// If the module requires a connection, but we're in local mode, don't include it.
1859
				if ( $modules_data[ $module ]['requires_connection'] ) {
1860
					continue;
1861
				}
1862
			}
1863
1864
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1865
				continue;
1866
			}
1867
1868
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1869
				unset( $modules[ $index ] );
1870
				self::update_active_modules( array_values( $modules ) );
1871
				continue;
1872
			}
1873
1874
			/**
1875
			 * Fires when a specific module is loaded.
1876
			 * The dynamic part of the hook, $module, is the module slug.
1877
			 *
1878
			 * @since 1.1.0
1879
			 */
1880
			do_action( 'jetpack_module_loaded_' . $module );
1881
		}
1882
1883
		/**
1884
		 * Fires when all the modules are loaded.
1885
		 *
1886
		 * @since 1.1.0
1887
		 */
1888
		do_action( 'jetpack_modules_loaded' );
1889
1890
		// 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.
1891
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1892
	}
1893
1894
	/**
1895
	 * Check if Jetpack's REST API compat file should be included
1896
	 * @action plugins_loaded
1897
	 * @return null
1898
	 */
1899
	public function check_rest_api_compat() {
1900
		/**
1901
		 * Filters the list of REST API compat files to be included.
1902
		 *
1903
		 * @since 2.2.5
1904
		 *
1905
		 * @param array $args Array of REST API compat files to include.
1906
		 */
1907
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1908
1909
		if ( function_exists( 'bbpress' ) )
1910
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1911
1912
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1913
			require_once $_jetpack_rest_api_compat_include;
1914
	}
1915
1916
	/**
1917
	 * Gets all plugins currently active in values, regardless of whether they're
1918
	 * traditionally activated or network activated.
1919
	 *
1920
	 * @todo Store the result in core's object cache maybe?
1921
	 */
1922
	public static function get_active_plugins() {
1923
		$active_plugins = (array) get_option( 'active_plugins', array() );
1924
1925
		if ( is_multisite() ) {
1926
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1927
			// whereas active_plugins stores them in the values.
1928
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1929
			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...
1930
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1931
			}
1932
		}
1933
1934
		sort( $active_plugins );
1935
1936
		return array_unique( $active_plugins );
1937
	}
1938
1939
	/**
1940
	 * Gets and parses additional plugin data to send with the heartbeat data
1941
	 *
1942
	 * @since 3.8.1
1943
	 *
1944
	 * @return array Array of plugin data
1945
	 */
1946
	public static function get_parsed_plugin_data() {
1947
		if ( ! function_exists( 'get_plugins' ) ) {
1948
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1949
		}
1950
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1951
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1952
		$active_plugins = Jetpack::get_active_plugins();
1953
1954
		$plugins = array();
1955
		foreach ( $all_plugins as $path => $plugin_data ) {
1956
			$plugins[ $path ] = array(
1957
					'is_active' => in_array( $path, $active_plugins ),
1958
					'file'      => $path,
1959
					'name'      => $plugin_data['Name'],
1960
					'version'   => $plugin_data['Version'],
1961
					'author'    => $plugin_data['Author'],
1962
			);
1963
		}
1964
1965
		return $plugins;
1966
	}
1967
1968
	/**
1969
	 * Gets and parses theme data to send with the heartbeat data
1970
	 *
1971
	 * @since 3.8.1
1972
	 *
1973
	 * @return array Array of theme data
1974
	 */
1975
	public static function get_parsed_theme_data() {
1976
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1977
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1978
1979
		$themes = array();
1980
		foreach ( $all_themes as $slug => $theme_data ) {
1981
			$theme_headers = array();
1982
			foreach ( $header_keys as $header_key ) {
1983
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1984
			}
1985
1986
			$themes[ $slug ] = array(
1987
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1988
					'slug' => $slug,
1989
					'theme_root' => $theme_data->get_theme_root_uri(),
1990
					'parent' => $theme_data->parent(),
1991
					'headers' => $theme_headers
1992
			);
1993
		}
1994
1995
		return $themes;
1996
	}
1997
1998
	/**
1999
	 * Checks whether a specific plugin is active.
2000
	 *
2001
	 * We don't want to store these in a static variable, in case
2002
	 * there are switch_to_blog() calls involved.
2003
	 */
2004
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2005
		return in_array( $plugin, self::get_active_plugins() );
2006
	}
2007
2008
	/**
2009
	 * Check if Jetpack's Open Graph tags should be used.
2010
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2011
	 *
2012
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2013
	 * @action plugins_loaded
2014
	 * @return null
2015
	 */
2016
	public function check_open_graph() {
2017
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2018
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2019
		}
2020
2021
		$active_plugins = self::get_active_plugins();
2022
2023
		if ( ! empty( $active_plugins ) ) {
2024
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2025
				if ( in_array( $plugin, $active_plugins ) ) {
2026
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2027
					break;
2028
				}
2029
			}
2030
		}
2031
2032
		/**
2033
		 * Allow the addition of Open Graph Meta Tags to all pages.
2034
		 *
2035
		 * @since 2.0.3
2036
		 *
2037
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2038
		 */
2039
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2040
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2041
		}
2042
	}
2043
2044
	/**
2045
	 * Check if Jetpack's Twitter tags should be used.
2046
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2047
	 *
2048
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2049
	 * @action plugins_loaded
2050
	 * @return null
2051
	 */
2052
	public function check_twitter_tags() {
2053
2054
		$active_plugins = self::get_active_plugins();
2055
2056
		if ( ! empty( $active_plugins ) ) {
2057
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2058
				if ( in_array( $plugin, $active_plugins ) ) {
2059
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2060
					break;
2061
				}
2062
			}
2063
		}
2064
2065
		/**
2066
		 * Allow Twitter Card Meta tags to be disabled.
2067
		 *
2068
		 * @since 2.6.0
2069
		 *
2070
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2071
		 */
2072
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2073
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2074
		}
2075
	}
2076
2077
	/**
2078
	 * Allows plugins to submit security reports.
2079
 	 *
2080
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2081
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2082
	 * @param array   $args         See definitions above
2083
	 */
2084
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2085
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2086
	}
2087
2088
/* Jetpack Options API */
2089
2090
	public static function get_option_names( $type = 'compact' ) {
2091
		return Jetpack_Options::get_option_names( $type );
2092
	}
2093
2094
	/**
2095
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2096
 	 *
2097
	 * @param string $name    Option name
2098
	 * @param mixed  $default (optional)
2099
	 */
2100
	public static function get_option( $name, $default = false ) {
2101
		return Jetpack_Options::get_option( $name, $default );
2102
	}
2103
2104
	/**
2105
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2106
 	 *
2107
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2108
	 * @param string $name  Option name
2109
	 * @param mixed  $value Option value
2110
	 */
2111
	public static function update_option( $name, $value ) {
2112
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2113
		return Jetpack_Options::update_option( $name, $value );
2114
	}
2115
2116
	/**
2117
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2118
 	 *
2119
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2120
	 * @param array $array array( option name => option value, ... )
2121
	 */
2122
	public static function update_options( $array ) {
2123
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2124
		return Jetpack_Options::update_options( $array );
2125
	}
2126
2127
	/**
2128
	 * Deletes the given option.  May be passed multiple option names as an array.
2129
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2130
	 *
2131
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2132
	 * @param string|array $names
2133
	 */
2134
	public static function delete_option( $names ) {
2135
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2136
		return Jetpack_Options::delete_option( $names );
2137
	}
2138
2139
	/**
2140
	 * Enters a user token into the user_tokens option
2141
	 *
2142
	 * @param int $user_id
2143
	 * @param string $token
2144
	 * return bool
2145
	 */
2146
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2147
		// not designed for concurrent updates
2148
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2149
		if ( ! is_array( $user_tokens ) )
2150
			$user_tokens = array();
2151
		$user_tokens[$user_id] = $token;
2152
		if ( $is_master_user ) {
2153
			$master_user = $user_id;
2154
			$options     = compact( 'user_tokens', 'master_user' );
2155
		} else {
2156
			$options = compact( 'user_tokens' );
2157
		}
2158
		return Jetpack_Options::update_options( $options );
2159
	}
2160
2161
	/**
2162
	 * Returns an array of all PHP files in the specified absolute path.
2163
	 * Equivalent to glob( "$absolute_path/*.php" ).
2164
	 *
2165
	 * @param string $absolute_path The absolute path of the directory to search.
2166
	 * @return array Array of absolute paths to the PHP files.
2167
	 */
2168
	public static function glob_php( $absolute_path ) {
2169
		if ( function_exists( 'glob' ) ) {
2170
			return glob( "$absolute_path/*.php" );
2171
		}
2172
2173
		$absolute_path = untrailingslashit( $absolute_path );
2174
		$files = array();
2175
		if ( ! $dir = @opendir( $absolute_path ) ) {
2176
			return $files;
2177
		}
2178
2179
		while ( false !== $file = readdir( $dir ) ) {
2180
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2181
				continue;
2182
			}
2183
2184
			$file = "$absolute_path/$file";
2185
2186
			if ( ! is_file( $file ) ) {
2187
				continue;
2188
			}
2189
2190
			$files[] = $file;
2191
		}
2192
2193
		closedir( $dir );
2194
2195
		return $files;
2196
	}
2197
2198
	public static function activate_new_modules( $redirect = false ) {
2199
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2200
			return;
2201
		}
2202
2203
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2204 View Code Duplication
		if ( ! $jetpack_old_version ) {
2205
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2206
			/** This action is documented in class.jetpack.php */
2207
			do_action( 'updating_jetpack_version', $version, false );
2208
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2209
		}
2210
2211
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2212
2213
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2214
			return;
2215
		}
2216
2217
		$active_modules     = Jetpack::get_active_modules();
2218
		$reactivate_modules = array();
2219
		foreach ( $active_modules as $active_module ) {
2220
			$module = Jetpack::get_module( $active_module );
2221
			if ( ! isset( $module['changed'] ) ) {
2222
				continue;
2223
			}
2224
2225
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2226
				continue;
2227
			}
2228
2229
			$reactivate_modules[] = $active_module;
2230
			Jetpack::deactivate_module( $active_module );
2231
		}
2232
2233
		$new_version = JETPACK__VERSION . ':' . time();
2234
		/** This action is documented in class.jetpack.php */
2235
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2236
		Jetpack_Options::update_options(
2237
			array(
2238
				'version'     => $new_version,
2239
				'old_version' => $jetpack_old_version,
2240
			)
2241
		);
2242
2243
		Jetpack::state( 'message', 'modules_activated' );
2244
		Jetpack::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...
2245
2246
		if ( $redirect ) {
2247
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2248
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2249
				$page = $_GET['page'];
2250
			}
2251
2252
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2253
			exit;
2254
		}
2255
	}
2256
2257
	/**
2258
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2259
	 * Make sure to tuck away module "library" files in a sub-directory.
2260
	 */
2261
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2262
		static $modules = null;
2263
2264
		if ( ! isset( $modules ) ) {
2265
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2266
			// Use the cache if we're on the front-end and it's available...
2267
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2268
				$modules = $available_modules_option[ JETPACK__VERSION ];
2269
			} else {
2270
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2271
2272
				$modules = array();
2273
2274
				foreach ( $files as $file ) {
2275
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2276
						continue;
2277
					}
2278
2279
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2280
				}
2281
2282
				Jetpack_Options::update_option( 'available_modules', array(
2283
					JETPACK__VERSION => $modules,
2284
				) );
2285
			}
2286
		}
2287
2288
		/**
2289
		 * Filters the array of modules available to be activated.
2290
		 *
2291
		 * @since 2.4.0
2292
		 *
2293
		 * @param array $modules Array of available modules.
2294
		 * @param string $min_version Minimum version number required to use modules.
2295
		 * @param string $max_version Maximum version number required to use modules.
2296
		 */
2297
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2298
2299
		if ( ! $min_version && ! $max_version ) {
2300
			return array_keys( $mods );
2301
		}
2302
2303
		$r = array();
2304
		foreach ( $mods as $slug => $introduced ) {
2305
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2306
				continue;
2307
			}
2308
2309
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2310
				continue;
2311
			}
2312
2313
			$r[] = $slug;
2314
		}
2315
2316
		return $r;
2317
	}
2318
2319
	/**
2320
	 * Default modules loaded on activation.
2321
	 */
2322
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2323
		$return = array();
2324
2325
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2326
			$module_data = Jetpack::get_module( $module );
2327
2328
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2329
				case 'yes' :
2330
					$return[] = $module;
2331
					break;
2332
				case 'public' :
2333
					if ( Jetpack_Options::get_option( 'public' ) ) {
2334
						$return[] = $module;
2335
					}
2336
					break;
2337
				case 'no' :
2338
				default :
2339
					break;
2340
			}
2341
		}
2342
		/**
2343
		 * Filters the array of default modules.
2344
		 *
2345
		 * @since 2.5.0
2346
		 *
2347
		 * @param array $return Array of default modules.
2348
		 * @param string $min_version Minimum version number required to use modules.
2349
		 * @param string $max_version Maximum version number required to use modules.
2350
		 */
2351
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2352
	}
2353
2354
	/**
2355
	 * Checks activated modules during auto-activation to determine
2356
	 * if any of those modules are being deprecated.  If so, close
2357
	 * them out, and add any replacement modules.
2358
	 *
2359
	 * Runs at priority 99 by default.
2360
	 *
2361
	 * This is run late, so that it can still activate a module if
2362
	 * the new module is a replacement for another that the user
2363
	 * currently has active, even if something at the normal priority
2364
	 * would kibosh everything.
2365
	 *
2366
	 * @since 2.6
2367
	 * @uses jetpack_get_default_modules filter
2368
	 * @param array $modules
2369
	 * @return array
2370
	 */
2371
	function handle_deprecated_modules( $modules ) {
2372
		$deprecated_modules = array(
2373
			'debug'            => null,  // Closed out and moved to the debugger library.
2374
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2375
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2376
		);
2377
2378
		// Don't activate SSO if they never completed activating WPCC.
2379
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2380
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2381
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2382
				$deprecated_modules['wpcc'] = null;
2383
			}
2384
		}
2385
2386
		foreach ( $deprecated_modules as $module => $replacement ) {
2387
			if ( Jetpack::is_module_active( $module ) ) {
2388
				self::deactivate_module( $module );
2389
				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...
2390
					$modules[] = $replacement;
2391
				}
2392
			}
2393
		}
2394
2395
		return array_unique( $modules );
2396
	}
2397
2398
	/**
2399
	 * Checks activated plugins during auto-activation to determine
2400
	 * if any of those plugins are in the list with a corresponding module
2401
	 * that is not compatible with the plugin. The module will not be allowed
2402
	 * to auto-activate.
2403
	 *
2404
	 * @since 2.6
2405
	 * @uses jetpack_get_default_modules filter
2406
	 * @param array $modules
2407
	 * @return array
2408
	 */
2409
	function filter_default_modules( $modules ) {
2410
2411
		$active_plugins = self::get_active_plugins();
2412
2413
		if ( ! empty( $active_plugins ) ) {
2414
2415
			// For each module we'd like to auto-activate...
2416
			foreach ( $modules as $key => $module ) {
2417
				// If there are potential conflicts for it...
2418
				$module_conflicting_plugins = apply_filters( 'jetpack_module_conflicting_plugins', $this->conflicting_plugins[ $module ] ?? array(), $module );
2419
				if ( ! empty( $module_conflicting_plugins ) ) {
2420
					// For each potential conflict...
2421
					foreach ( $module_conflicting_plugins as $title => $plugin ) {
2422
						// If that conflicting plugin is active...
2423
						if ( in_array( $plugin, $active_plugins ) ) {
2424
							// Remove that item from being auto-activated.
2425
							unset( $modules[ $key ] );
2426
						}
2427
					}
2428
				}
2429
			}
2430
		}
2431
2432
		return $modules;
2433
	}
2434
2435
	/**
2436
	 * Extract a module's slug from its full path.
2437
	 */
2438
	public static function get_module_slug( $file ) {
2439
		return str_replace( '.php', '', basename( $file ) );
2440
	}
2441
2442
	/**
2443
	 * Generate a module's path from its slug.
2444
	 */
2445
	public static function get_module_path( $slug ) {
2446
		/**
2447
		 * Filters the path of a modules.
2448
		 *
2449
		 * @since 7.4.0
2450
		 *
2451
		 * @param array $return The absolute path to a module's root php file
2452
		 * @param string $slug The module slug
2453
		 */
2454
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2455
	}
2456
2457
	/**
2458
	 * Load module data from module file. Headers differ from WordPress
2459
	 * plugin headers to avoid them being identified as standalone
2460
	 * plugins on the WordPress plugins page.
2461
	 */
2462
	public static function get_module( $module ) {
2463
		$headers = array(
2464
			'name'                      => 'Module Name',
2465
			'description'               => 'Module Description',
2466
			'sort'                      => 'Sort Order',
2467
			'recommendation_order'      => 'Recommendation Order',
2468
			'introduced'                => 'First Introduced',
2469
			'changed'                   => 'Major Changes In',
2470
			'deactivate'                => 'Deactivate',
2471
			'free'                      => 'Free',
2472
			'requires_connection'       => 'Requires Connection',
2473
			'auto_activate'             => 'Auto Activate',
2474
			'module_tags'               => 'Module Tags',
2475
			'feature'                   => 'Feature',
2476
			'additional_search_queries' => 'Additional Search Queries',
2477
			'plan_classes'              => 'Plans',
2478
		);
2479
2480
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2481
2482
		$mod = Jetpack::get_file_data( $file, $headers );
2483
		if ( empty( $mod['name'] ) ) {
2484
			return false;
2485
		}
2486
2487
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2488
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2489
		$mod['deactivate']              = empty( $mod['deactivate'] );
2490
		$mod['free']                    = empty( $mod['free'] );
2491
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2492
2493
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2494
			$mod['auto_activate'] = 'No';
2495
		} else {
2496
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2497
		}
2498
2499
		if ( $mod['module_tags'] ) {
2500
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2501
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2502
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2503
		} else {
2504
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2505
		}
2506
2507 View Code Duplication
		if ( $mod['plan_classes'] ) {
2508
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2509
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2510
		} else {
2511
			$mod['plan_classes'] = array( 'free' );
2512
		}
2513
2514 View Code Duplication
		if ( $mod['feature'] ) {
2515
			$mod['feature'] = explode( ',', $mod['feature'] );
2516
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2517
		} else {
2518
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2519
		}
2520
2521
		/**
2522
		 * Filters the feature array on a module.
2523
		 *
2524
		 * This filter allows you to control where each module is filtered: Recommended,
2525
		 * and the default "Other" listing.
2526
		 *
2527
		 * @since 3.5.0
2528
		 *
2529
		 * @param array   $mod['feature'] The areas to feature this module:
2530
		 *     'Recommended' shows on the main Jetpack admin screen.
2531
		 *     'Other' should be the default if no other value is in the array.
2532
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2533
		 * @param array   $mod All the currently assembled module data.
2534
		 */
2535
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2536
2537
		/**
2538
		 * Filter the returned data about a module.
2539
		 *
2540
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2541
		 * so please be careful.
2542
		 *
2543
		 * @since 3.6.0
2544
		 *
2545
		 * @param array   $mod    The details of the requested module.
2546
		 * @param string  $module The slug of the module, e.g. sharedaddy
2547
		 * @param string  $file   The path to the module source file.
2548
		 */
2549
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2550
	}
2551
2552
	/**
2553
	 * Like core's get_file_data implementation, but caches the result.
2554
	 */
2555
	public static function get_file_data( $file, $headers ) {
2556
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2557
		$file_name = basename( $file );
2558
2559
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2560
2561
		$file_data_option = get_transient( $cache_key );
2562
2563
		if ( false === $file_data_option ) {
2564
			$file_data_option = array();
2565
		}
2566
2567
		$key           = md5( $file_name . serialize( $headers ) );
2568
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2569
2570
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2571
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2572
			return $file_data_option[ $key ];
2573
		}
2574
2575
		$data = get_file_data( $file, $headers );
2576
2577
		$file_data_option[ $key ] = $data;
2578
2579
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2580
2581
		return $data;
2582
	}
2583
2584
2585
	/**
2586
	 * Return translated module tag.
2587
	 *
2588
	 * @param string $tag Tag as it appears in each module heading.
2589
	 *
2590
	 * @return mixed
2591
	 */
2592
	public static function translate_module_tag( $tag ) {
2593
		return jetpack_get_module_i18n_tag( $tag );
2594
	}
2595
2596
	/**
2597
	 * Get i18n strings as a JSON-encoded string
2598
	 *
2599
	 * @return string The locale as JSON
2600
	 */
2601
	public static function get_i18n_data_json() {
2602
2603
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2604
		// JSON files with the file they should be included for. This is an md5
2605
		// of '_inc/build/admin.js'.
2606
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2607
2608
		$i18n_json =
2609
				   JETPACK__PLUGIN_DIR
2610
				   . 'languages/json/jetpack-'
2611
				   . get_user_locale()
2612
				   . '-'
2613
				   . $path_md5
2614
				   . '.json';
2615
2616
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2617
			$locale_data = @file_get_contents( $i18n_json );
2618
			if ( $locale_data ) {
2619
				return $locale_data;
2620
			}
2621
		}
2622
2623
		// Return valid empty Jed locale
2624
		return '{ "locale_data": { "messages": { "": {} } } }';
2625
	}
2626
2627
	/**
2628
	 * Add locale data setup to wp-i18n
2629
	 *
2630
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2631
	 *
2632
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2633
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2634
	 *
2635
	 * This method provides a safe way to request the setup multiple times but add the script at
2636
	 * most once.
2637
	 *
2638
	 * @since 6.7.0
2639
	 *
2640
	 * @return void
2641
	 */
2642
	public static function setup_wp_i18n_locale_data() {
2643
		static $script_added = false;
2644
		if ( ! $script_added ) {
2645
			$script_added = true;
2646
			wp_add_inline_script(
2647
				'wp-i18n',
2648
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2649
			);
2650
		}
2651
	}
2652
2653
	/**
2654
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2655
	 *
2656
	 * @since 3.9.2
2657
	 *
2658
	 * @param array $modules
2659
	 *
2660
	 * @return string|void
2661
	 */
2662
	public static function get_translated_modules( $modules ) {
2663
		foreach ( $modules as $index => $module ) {
2664
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2665
			if ( isset( $module['name'] ) ) {
2666
				$modules[ $index ]['name'] = $i18n_module['name'];
2667
			}
2668
			if ( isset( $module['description'] ) ) {
2669
				$modules[ $index ]['description'] = $i18n_module['description'];
2670
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2671
			}
2672
		}
2673
		return $modules;
2674
	}
2675
2676
	/**
2677
	 * Get a list of activated modules as an array of module slugs.
2678
	 */
2679
	public static function get_active_modules() {
2680
		$active = Jetpack_Options::get_option( 'active_modules' );
2681
2682
		if ( ! is_array( $active ) ) {
2683
			$active = array();
2684
		}
2685
2686
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2687
			$active[] = 'vaultpress';
2688
		} else {
2689
			$active = array_diff( $active, array( 'vaultpress' ) );
2690
		}
2691
2692
		//If protect is active on the main site of a multisite, it should be active on all sites.
2693
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2694
			$active[] = 'protect';
2695
		}
2696
2697
		/**
2698
		 * Allow filtering of the active modules.
2699
		 *
2700
		 * Gives theme and plugin developers the power to alter the modules that
2701
		 * are activated on the fly.
2702
		 *
2703
		 * @since 5.8.0
2704
		 *
2705
		 * @param array $active Array of active module slugs.
2706
		 */
2707
		$active = apply_filters( 'jetpack_active_modules', $active );
2708
2709
		return array_unique( $active );
2710
	}
2711
2712
	/**
2713
	 * Check whether or not a Jetpack module is active.
2714
	 *
2715
	 * @param string $module The slug of a Jetpack module.
2716
	 * @return bool
2717
	 *
2718
	 * @static
2719
	 */
2720
	public static function is_module_active( $module ) {
2721
		return in_array( $module, self::get_active_modules() );
2722
	}
2723
2724
	public static function is_module( $module ) {
2725
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2726
	}
2727
2728
	/**
2729
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2730
	 *
2731
	 * @param bool $catch True to start catching, False to stop.
2732
	 *
2733
	 * @static
2734
	 */
2735
	public static function catch_errors( $catch ) {
2736
		static $display_errors, $error_reporting;
2737
2738
		if ( $catch ) {
2739
			$display_errors  = @ini_set( 'display_errors', 1 );
2740
			$error_reporting = @error_reporting( E_ALL );
2741
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2742
		} else {
2743
			@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...
2744
			@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...
2745
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2746
		}
2747
	}
2748
2749
	/**
2750
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2751
	 */
2752
	public static function catch_errors_on_shutdown() {
2753
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2754
	}
2755
2756
	/**
2757
	 * Rewrite any string to make paths easier to read.
2758
	 *
2759
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2760
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2761
	 *
2762
	 * @param $string
2763
	 * @return mixed
2764
	 */
2765
	public static function alias_directories( $string ) {
2766
		// ABSPATH has a trailing slash.
2767
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2768
		// WP_CONTENT_DIR does not have a trailing slash.
2769
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2770
2771
		return $string;
2772
	}
2773
2774
	public static function activate_default_modules(
2775
		$min_version = false,
2776
		$max_version = false,
2777
		$other_modules = array(),
2778
		$redirect = null,
2779
		$send_state_messages = null
2780
	) {
2781
		$jetpack = Jetpack::init();
2782
2783
		if ( is_null( $redirect ) ) {
2784
			if (
2785
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2786
			||
2787
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2788
			||
2789
				( defined( 'WP_CLI' ) && WP_CLI )
2790
			||
2791
				( defined( 'DOING_CRON' ) && DOING_CRON )
2792
			||
2793
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2794
			) {
2795
				$redirect = false;
2796
			} elseif ( is_admin() ) {
2797
				$redirect = true;
2798
			} else {
2799
				$redirect = false;
2800
			}
2801
		}
2802
2803
		if ( is_null( $send_state_messages ) ) {
2804
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2805
		}
2806
2807
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2808
		$modules = array_merge( $other_modules, $modules );
2809
2810
		// Look for standalone plugins and disable if active.
2811
2812
		$to_deactivate = array();
2813
		foreach ( $modules as $module ) {
2814
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2815
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2816
			}
2817
		}
2818
2819
		$deactivated = array();
2820
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2821
			list( $probable_file, $probable_title ) = $deactivate_me;
2822
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2823
				$deactivated[] = $module;
2824
			}
2825
		}
2826
2827
		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...
2828
			if ( $send_state_messages ) {
2829
				Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2830
			}
2831
2832
			if ( $redirect ) {
2833
				$url = add_query_arg(
2834
					array(
2835
						'action'   => 'activate_default_modules',
2836
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2837
					),
2838
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2839
				);
2840
				wp_safe_redirect( $url );
2841
				exit;
2842
			}
2843
		}
2844
2845
		/**
2846
		 * Fires before default modules are activated.
2847
		 *
2848
		 * @since 1.9.0
2849
		 *
2850
		 * @param string $min_version Minimum version number required to use modules.
2851
		 * @param string $max_version Maximum version number required to use modules.
2852
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2853
		 */
2854
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2855
2856
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2857
		if ( $send_state_messages ) {
2858
			Jetpack::restate();
2859
			Jetpack::catch_errors( true );
2860
		}
2861
2862
		$active = Jetpack::get_active_modules();
2863
2864
		foreach ( $modules as $module ) {
2865
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2866
				$active[] = $module;
2867
				self::update_active_modules( $active );
2868
				continue;
2869
			}
2870
2871
			if ( $send_state_messages && in_array( $module, $active ) ) {
2872
				$module_info = Jetpack::get_module( $module );
2873 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2874
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2875
					if ( $active_state = Jetpack::state( $state ) ) {
2876
						$active_state = explode( ',', $active_state );
2877
					} else {
2878
						$active_state = array();
2879
					}
2880
					$active_state[] = $module;
2881
					Jetpack::state( $state, implode( ',', $active_state ) );
2882
				}
2883
				continue;
2884
			}
2885
2886
			$file = Jetpack::get_module_path( $module );
2887
			if ( ! file_exists( $file ) ) {
2888
				continue;
2889
			}
2890
2891
			// we'll override this later if the plugin can be included without fatal error
2892
			if ( $redirect ) {
2893
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2894
			}
2895
2896
			if ( $send_state_messages ) {
2897
				Jetpack::state( 'error', 'module_activation_failed' );
2898
				Jetpack::state( 'module', $module );
2899
			}
2900
2901
			ob_start();
2902
			require_once $file;
2903
2904
			$active[] = $module;
2905
2906 View Code Duplication
			if ( $send_state_messages ) {
2907
2908
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2909
				if ( $active_state = Jetpack::state( $state ) ) {
2910
					$active_state = explode( ',', $active_state );
2911
				} else {
2912
					$active_state = array();
2913
				}
2914
				$active_state[] = $module;
2915
				Jetpack::state( $state, implode( ',', $active_state ) );
2916
			}
2917
2918
			Jetpack::update_active_modules( $active );
2919
2920
			ob_end_clean();
2921
		}
2922
2923
		if ( $send_state_messages ) {
2924
			Jetpack::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...
2925
			Jetpack::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...
2926
		}
2927
2928
		Jetpack::catch_errors( false );
2929
		/**
2930
		 * Fires when default modules are activated.
2931
		 *
2932
		 * @since 1.9.0
2933
		 *
2934
		 * @param string $min_version Minimum version number required to use modules.
2935
		 * @param string $max_version Maximum version number required to use modules.
2936
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2937
		 */
2938
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2939
	}
2940
2941
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2942
		/**
2943
		 * Fires before a module is activated.
2944
		 *
2945
		 * @since 2.6.0
2946
		 *
2947
		 * @param string $module Module slug.
2948
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2949
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2950
		 */
2951
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2952
2953
		$jetpack = Jetpack::init();
2954
2955
		if ( ! strlen( $module ) )
2956
			return false;
2957
2958
		if ( ! Jetpack::is_module( $module ) )
2959
			return false;
2960
2961
		// If it's already active, then don't do it again
2962
		$active = Jetpack::get_active_modules();
2963
		foreach ( $active as $act ) {
2964
			if ( $act == $module )
2965
				return true;
2966
		}
2967
2968
		$module_data = Jetpack::get_module( $module );
2969
2970
		if ( ! Jetpack::is_active() ) {
2971
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2972
				return false;
2973
2974
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2975
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2976
				return false;
2977
		}
2978
2979
		// Check and see if the old plugin is active
2980
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2981
			// Deactivate the old plugin
2982
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2983
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2984
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2985
				Jetpack::state( 'deactivated_plugins', $module );
2986
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2987
				exit;
2988
			}
2989
		}
2990
2991
		// Protect won't work with mis-configured IPs
2992
		if ( 'protect' === $module ) {
2993
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2994
			if ( ! jetpack_protect_get_ip() ) {
2995
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2996
				return false;
2997
			}
2998
		}
2999
3000
		if ( ! Jetpack_Plan::supports( $module ) ) {
3001
			return false;
3002
		}
3003
3004
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3005
		Jetpack::state( 'module', $module );
3006
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3007
3008
		Jetpack::catch_errors( true );
3009
		ob_start();
3010
		require Jetpack::get_module_path( $module );
3011
		/** This action is documented in class.jetpack.php */
3012
		do_action( 'jetpack_activate_module', $module );
3013
		$active[] = $module;
3014
		Jetpack::update_active_modules( $active );
3015
3016
		Jetpack::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...
3017
		ob_end_clean();
3018
		Jetpack::catch_errors( false );
3019
3020
		if ( $redirect ) {
3021
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3022
		}
3023
		if ( $exit ) {
3024
			exit;
3025
		}
3026
		return true;
3027
	}
3028
3029
	function activate_module_actions( $module ) {
3030
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3031
	}
3032
3033
	public static function deactivate_module( $module ) {
3034
		/**
3035
		 * Fires when a module is deactivated.
3036
		 *
3037
		 * @since 1.9.0
3038
		 *
3039
		 * @param string $module Module slug.
3040
		 */
3041
		do_action( 'jetpack_pre_deactivate_module', $module );
3042
3043
		$jetpack = Jetpack::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...
3044
3045
		$active = Jetpack::get_active_modules();
3046
		$new    = array_filter( array_diff( $active, (array) $module ) );
3047
3048
		return self::update_active_modules( $new );
3049
	}
3050
3051
	public static function enable_module_configurable( $module ) {
3052
		$module = Jetpack::get_module_slug( $module );
3053
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3054
	}
3055
3056
	/**
3057
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3058
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3059
	 *
3060
	 * @param string $module Module slug
3061
	 * @return string $url module configuration URL
3062
	 */
3063
	public static function module_configuration_url( $module ) {
3064
		$module = Jetpack::get_module_slug( $module );
3065
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3066
		/**
3067
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3068
		 *
3069
		 * @since 6.9.0
3070
		 *
3071
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3072
		 */
3073
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3074
3075
		return $url;
3076
	}
3077
3078
/* Installation */
3079
	public static function bail_on_activation( $message, $deactivate = true ) {
3080
?>
3081
<!doctype html>
3082
<html>
3083
<head>
3084
<meta charset="<?php bloginfo( 'charset' ); ?>">
3085
<style>
3086
* {
3087
	text-align: center;
3088
	margin: 0;
3089
	padding: 0;
3090
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3091
}
3092
p {
3093
	margin-top: 1em;
3094
	font-size: 18px;
3095
}
3096
</style>
3097
<body>
3098
<p><?php echo esc_html( $message ); ?></p>
3099
</body>
3100
</html>
3101
<?php
3102
		if ( $deactivate ) {
3103
			$plugins = get_option( 'active_plugins' );
3104
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3105
			$update  = false;
3106
			foreach ( $plugins as $i => $plugin ) {
3107
				if ( $plugin === $jetpack ) {
3108
					$plugins[$i] = false;
3109
					$update = true;
3110
				}
3111
			}
3112
3113
			if ( $update ) {
3114
				update_option( 'active_plugins', array_filter( $plugins ) );
3115
			}
3116
		}
3117
		exit;
3118
	}
3119
3120
	/**
3121
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3122
	 * @static
3123
	 */
3124
	public static function plugin_activation( $network_wide ) {
3125
		Jetpack_Options::update_option( 'activated', 1 );
3126
3127
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3128
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3129
		}
3130
3131
		if ( $network_wide )
3132
			Jetpack::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...
3133
3134
		// For firing one-off events (notices) immediately after activation
3135
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3136
3137
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3138
3139
		Jetpack::plugin_initialize();
3140
	}
3141
3142
	public static function get_activation_source( $referer_url ) {
3143
3144
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3145
			return array( 'wp-cli', null );
3146
		}
3147
3148
		$referer = parse_url( $referer_url );
3149
3150
		$source_type = 'unknown';
3151
		$source_query = null;
3152
3153
		if ( ! is_array( $referer ) ) {
3154
			return array( $source_type, $source_query );
3155
		}
3156
3157
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3158
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3159
3160
		if ( isset( $referer['query'] ) ) {
3161
			parse_str( $referer['query'], $query_parts );
3162
		} else {
3163
			$query_parts = array();
3164
		}
3165
3166
		if ( $plugins_path === $referer['path'] ) {
3167
			$source_type = 'list';
3168
		} elseif ( $plugins_install_path === $referer['path'] ) {
3169
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3170
			switch( $tab ) {
3171
				case 'popular':
3172
					$source_type = 'popular';
3173
					break;
3174
				case 'recommended':
3175
					$source_type = 'recommended';
3176
					break;
3177
				case 'favorites':
3178
					$source_type = 'favorites';
3179
					break;
3180
				case 'search':
3181
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3182
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3183
					break;
3184
				default:
3185
					$source_type = 'featured';
3186
			}
3187
		}
3188
3189
		return array( $source_type, $source_query );
3190
	}
3191
3192
	/**
3193
	 * Runs before bumping version numbers up to a new version
3194
	 * @param  string $version    Version:timestamp
3195
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3196
	 * @return null              [description]
3197
	 */
3198
	public static function do_version_bump( $version, $old_version ) {
3199
		if ( ! $old_version ) { // For new sites
3200
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3201
		}
3202
	}
3203
3204
	/**
3205
	 * Sets the internal version number and activation state.
3206
	 * @static
3207
	 */
3208
	public static function plugin_initialize() {
3209
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3210
			Jetpack_Options::update_option( 'activated', 2 );
3211
		}
3212
3213 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3214
			$version = $old_version = JETPACK__VERSION . ':' . time();
3215
			/** This action is documented in class.jetpack.php */
3216
			do_action( 'updating_jetpack_version', $version, false );
3217
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3218
		}
3219
3220
		Jetpack::load_modules();
3221
3222
		Jetpack_Options::delete_option( 'do_activate' );
3223
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3224
	}
3225
3226
	/**
3227
	 * Removes all connection options
3228
	 * @static
3229
	 */
3230
	public static function plugin_deactivation( ) {
3231
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3232
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3233
			Jetpack_Network::init()->deactivate();
3234
		} else {
3235
			Jetpack::disconnect( false );
3236
			//Jetpack_Heartbeat::init()->deactivate();
3237
		}
3238
	}
3239
3240
	/**
3241
	 * Disconnects from the Jetpack servers.
3242
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3243
	 * @static
3244
	 */
3245
	public static function disconnect( $update_activated_state = true ) {
3246
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3247
		$connection = self::connection();
3248
		$connection->clean_nonces( true );
3249
3250
		// If the site is in an IDC because sync is not allowed,
3251
		// let's make sure to not disconnect the production site.
3252
		if ( ! self::validate_sync_error_idc_option() ) {
3253
			$tracking = new Tracking();
3254
			$tracking->record_user_event( 'disconnect_site', array() );
3255
3256
			$xml = new Jetpack_IXR_Client();
3257
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3258
		}
3259
3260
		Jetpack_Options::delete_option(
3261
			array(
3262
				'blog_token',
3263
				'user_token',
3264
				'user_tokens',
3265
				'master_user',
3266
				'time_diff',
3267
				'fallback_no_verify_ssl_certs',
3268
			)
3269
		);
3270
3271
		Jetpack_IDC::clear_all_idc_options();
3272
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3273
3274
		if ( $update_activated_state ) {
3275
			Jetpack_Options::update_option( 'activated', 4 );
3276
		}
3277
3278
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3279
			// Check then record unique disconnection if site has never been disconnected previously
3280
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3281
				$jetpack_unique_connection['disconnected'] = 1;
3282
			} else {
3283
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3284
					//track unique disconnect
3285
					$jetpack = Jetpack::init();
3286
3287
					$jetpack->stat( 'connections', 'unique-disconnect' );
3288
					$jetpack->do_stats( 'server_side' );
3289
				}
3290
				// increment number of times disconnected
3291
				$jetpack_unique_connection['disconnected'] += 1;
3292
			}
3293
3294
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3295
		}
3296
3297
		// Delete cached connected user data
3298
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3299
		delete_transient( $transient_key );
3300
3301
		// Delete all the sync related data. Since it could be taking up space.
3302
		Sender::get_instance()->uninstall();
3303
3304
		// Disable the Heartbeat cron
3305
		Jetpack_Heartbeat::init()->deactivate();
3306
	}
3307
3308
	/**
3309
	 * Unlinks the current user from the linked WordPress.com user.
3310
	 *
3311
	 * @deprecated since 7.7
3312
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3313
	 *
3314
	 * @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...
3315
	 * @return Boolean Whether the disconnection of the user was successful.
3316
	 */
3317
	public static function unlink_user( $user_id = null ) {
3318
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3319
		return Connection_Manager::disconnect_user( $user_id );
3320
	}
3321
3322
	/**
3323
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3324
	 */
3325
	public static function try_registration() {
3326
		// The user has agreed to the TOS at some point by now.
3327
		Jetpack_Options::update_option( 'tos_agreed', true );
3328
3329
		// Let's get some testing in beta versions and such.
3330
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3331
			// Before attempting to connect, let's make sure that the domains are viable.
3332
			$domains_to_check = array_unique( array(
3333
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3334
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3335
			) );
3336
			foreach ( $domains_to_check as $domain ) {
3337
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3336 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3338
				if ( is_wp_error( $result ) ) {
3339
					return $result;
3340
				}
3341
			}
3342
		}
3343
3344
		$result = Jetpack::register();
3345
3346
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3347
		if ( ! $result || is_wp_error( $result ) ) {
3348
			return $result;
3349
		} else {
3350
			return true;
3351
		}
3352
	}
3353
3354
	/**
3355
	 * Tracking an internal event log. Try not to put too much chaff in here.
3356
	 *
3357
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3358
	 */
3359
	public static function log( $code, $data = null ) {
3360
		// only grab the latest 200 entries
3361
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3362
3363
		// Append our event to the log
3364
		$log_entry = array(
3365
			'time'    => time(),
3366
			'user_id' => get_current_user_id(),
3367
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3368
			'code'    => $code,
3369
		);
3370
		// Don't bother storing it unless we've got some.
3371
		if ( ! is_null( $data ) ) {
3372
			$log_entry['data'] = $data;
3373
		}
3374
		$log[] = $log_entry;
3375
3376
		// Try add_option first, to make sure it's not autoloaded.
3377
		// @todo: Add an add_option method to Jetpack_Options
3378
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3379
			Jetpack_Options::update_option( 'log', $log );
3380
		}
3381
3382
		/**
3383
		 * Fires when Jetpack logs an internal event.
3384
		 *
3385
		 * @since 3.0.0
3386
		 *
3387
		 * @param array $log_entry {
3388
		 *	Array of details about the log entry.
3389
		 *
3390
		 *	@param string time Time of the event.
3391
		 *	@param int user_id ID of the user who trigerred the event.
3392
		 *	@param int blog_id Jetpack Blog ID.
3393
		 *	@param string code Unique name for the event.
3394
		 *	@param string data Data about the event.
3395
		 * }
3396
		 */
3397
		do_action( 'jetpack_log_entry', $log_entry );
3398
	}
3399
3400
	/**
3401
	 * Get the internal event log.
3402
	 *
3403
	 * @param $event (string) - only return the specific log events
3404
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3405
	 *
3406
	 * @return array of log events || WP_Error for invalid params
3407
	 */
3408
	public static function get_log( $event = false, $num = false ) {
3409
		if ( $event && ! is_string( $event ) ) {
3410
			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...
3411
		}
3412
3413
		if ( $num && ! is_numeric( $num ) ) {
3414
			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...
3415
		}
3416
3417
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3418
3419
		// If nothing set - act as it did before, otherwise let's start customizing the output
3420
		if ( ! $num && ! $event ) {
3421
			return $entire_log;
3422
		} else {
3423
			$entire_log = array_reverse( $entire_log );
3424
		}
3425
3426
		$custom_log_output = array();
3427
3428
		if ( $event ) {
3429
			foreach ( $entire_log as $log_event ) {
3430
				if ( $event == $log_event[ 'code' ] ) {
3431
					$custom_log_output[] = $log_event;
3432
				}
3433
			}
3434
		} else {
3435
			$custom_log_output = $entire_log;
3436
		}
3437
3438
		if ( $num ) {
3439
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3440
		}
3441
3442
		return $custom_log_output;
3443
	}
3444
3445
	/**
3446
	 * Log modification of important settings.
3447
	 */
3448
	public static function log_settings_change( $option, $old_value, $value ) {
3449
		switch( $option ) {
3450
			case 'jetpack_sync_non_public_post_stati':
3451
				self::log( $option, $value );
3452
				break;
3453
		}
3454
	}
3455
3456
	/**
3457
	 * Return stat data for WPCOM sync
3458
	 */
3459
	public static function get_stat_data( $encode = true, $extended = true ) {
3460
		$data = Jetpack_Heartbeat::generate_stats_array();
3461
3462
		if ( $extended ) {
3463
			$additional_data = self::get_additional_stat_data();
3464
			$data = array_merge( $data, $additional_data );
3465
		}
3466
3467
		if ( $encode ) {
3468
			return json_encode( $data );
3469
		}
3470
3471
		return $data;
3472
	}
3473
3474
	/**
3475
	 * Get additional stat data to sync to WPCOM
3476
	 */
3477
	public static function get_additional_stat_data( $prefix = '' ) {
3478
		$return["{$prefix}themes"]         = Jetpack::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...
3479
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3480
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3481
		$return["{$prefix}site-count"]     = 0;
3482
3483
		if ( function_exists( 'get_blog_count' ) ) {
3484
			$return["{$prefix}site-count"] = get_blog_count();
3485
		}
3486
		return $return;
3487
	}
3488
3489
	private static function get_site_user_count() {
3490
		global $wpdb;
3491
3492
		if ( function_exists( 'wp_is_large_network' ) ) {
3493
			if ( wp_is_large_network( 'users' ) ) {
3494
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3495
			}
3496
		}
3497
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3498
			// It wasn't there, so regenerate the data and save the transient
3499
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3500
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3501
		}
3502
		return $user_count;
3503
	}
3504
3505
	/* Admin Pages */
3506
3507
	function admin_init() {
3508
		// If the plugin is not connected, display a connect message.
3509
		if (
3510
			// the plugin was auto-activated and needs its candy
3511
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3512
		||
3513
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3514
			! Jetpack_Options::get_option( 'activated' )
3515
		) {
3516
			Jetpack::plugin_initialize();
3517
		}
3518
3519
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3520
			Jetpack_Connection_Banner::init();
3521
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3522
			// Upgrade: 1.1 -> 1.1.1
3523
			// Check and see if host can verify the Jetpack servers' SSL certificate
3524
			$args = array();
3525
			$connection = self::connection();
3526
			Client::_wp_remote_request(
3527
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3528
				$args,
3529
				true
3530
			);
3531
		}
3532
3533
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3534
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3535
		}
3536
3537
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3538
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3539
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3540
3541
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3542
			// Artificially throw errors in certain whitelisted cases during plugin activation
3543
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3544
		}
3545
3546
		// Add custom column in wp-admin/users.php to show whether user is linked.
3547
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3548
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3549
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3550
	}
3551
3552
	function admin_body_class( $admin_body_class = '' ) {
3553
		$classes = explode( ' ', trim( $admin_body_class ) );
3554
3555
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3556
3557
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3558
		return " $admin_body_class ";
3559
	}
3560
3561
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3562
		return $admin_body_class . ' jetpack-pagestyles ';
3563
	}
3564
3565
	/**
3566
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3567
	 * This function artificially throws errors for such cases (whitelisted).
3568
	 *
3569
	 * @param string $plugin The activated plugin.
3570
	 */
3571
	function throw_error_on_activate_plugin( $plugin ) {
3572
		$active_modules = Jetpack::get_active_modules();
3573
3574
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3575
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3576
			$throw = false;
3577
3578
			// Try and make sure it really was the stats plugin
3579
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3580
				if ( 'stats.php' == basename( $plugin ) ) {
3581
					$throw = true;
3582
				}
3583
			} else {
3584
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3585
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3586
					$throw = true;
3587
				}
3588
			}
3589
3590
			if ( $throw ) {
3591
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3592
			}
3593
		}
3594
	}
3595
3596
	function intercept_plugin_error_scrape_init() {
3597
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3598
	}
3599
3600
	function intercept_plugin_error_scrape( $action, $result ) {
3601
		if ( ! $result ) {
3602
			return;
3603
		}
3604
3605
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3606
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3607
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3608
			}
3609
		}
3610
	}
3611
3612
	/**
3613
	 * Register the remote file upload request handlers, if needed.
3614
	 *
3615
	 * @access public
3616
	 */
3617
	public function add_remote_request_handlers() {
3618
		// Remote file uploads are allowed only via AJAX requests.
3619
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3620
			return;
3621
		}
3622
3623
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3624
		$remote_request_actions = array(
3625
			'jetpack_upload_file',
3626
			'jetpack_update_file',
3627
		);
3628
3629
		// phpcs:ignore WordPress.Security.NonceVerification
3630
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3631
			return;
3632
		}
3633
3634
		// Require Jetpack authentication for the remote file upload AJAX requests.
3635
		$this->connection_manager->require_jetpack_authentication();
3636
3637
		// Register the remote file upload AJAX handlers.
3638
		foreach ( $remote_request_actions as $action ) {
3639
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3640
		}
3641
	}
3642
3643
	/**
3644
	 * Handler for Jetpack remote file uploads.
3645
	 *
3646
	 * @access public
3647
	 */
3648
	public function remote_request_handlers() {
3649
		$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...
3650
3651
		switch ( current_filter() ) {
3652
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3653
			$response = $this->upload_handler();
3654
			break;
3655
3656
		case 'wp_ajax_nopriv_jetpack_update_file' :
3657
			$response = $this->upload_handler( true );
3658
			break;
3659
		default :
3660
			$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...
3661
			break;
3662
		}
3663
3664
		if ( ! $response ) {
3665
			$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...
3666
		}
3667
3668
		if ( is_wp_error( $response ) ) {
3669
			$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...
3670
			$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...
3671
			$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...
3672
3673
			if ( ! is_int( $status_code ) ) {
3674
				$status_code = 400;
3675
			}
3676
3677
			status_header( $status_code );
3678
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3679
		}
3680
3681
		status_header( 200 );
3682
		if ( true === $response ) {
3683
			exit;
3684
		}
3685
3686
		die( json_encode( (object) $response ) );
3687
	}
3688
3689
	/**
3690
	 * Uploads a file gotten from the global $_FILES.
3691
	 * If `$update_media_item` is true and `post_id` is defined
3692
	 * the attachment file of the media item (gotten through of the post_id)
3693
	 * will be updated instead of add a new one.
3694
	 *
3695
	 * @param  boolean $update_media_item - update media attachment
3696
	 * @return array - An array describing the uploadind files process
3697
	 */
3698
	function upload_handler( $update_media_item = false ) {
3699
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3700
			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...
3701
		}
3702
3703
		$user = wp_authenticate( '', '' );
3704
		if ( ! $user || is_wp_error( $user ) ) {
3705
			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...
3706
		}
3707
3708
		wp_set_current_user( $user->ID );
3709
3710
		if ( ! current_user_can( 'upload_files' ) ) {
3711
			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...
3712
		}
3713
3714
		if ( empty( $_FILES ) ) {
3715
			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...
3716
		}
3717
3718
		foreach ( array_keys( $_FILES ) as $files_key ) {
3719
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3720
				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...
3721
			}
3722
		}
3723
3724
		$media_keys = array_keys( $_FILES['media'] );
3725
3726
		$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...
3727
		if ( ! $token || is_wp_error( $token ) ) {
3728
			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...
3729
		}
3730
3731
		$uploaded_files = array();
3732
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3733
		unset( $GLOBALS['post'] );
3734
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3735
			$file = array();
3736
			foreach ( $media_keys as $media_key ) {
3737
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3738
			}
3739
3740
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3741
3742
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3743
			if ( $hmac_provided !== $hmac_file ) {
3744
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3745
				continue;
3746
			}
3747
3748
			$_FILES['.jetpack.upload.'] = $file;
3749
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3750
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3751
				$post_id = 0;
3752
			}
3753
3754
			if ( $update_media_item ) {
3755
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3756
					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...
3757
				}
3758
3759
				$media_array = $_FILES['media'];
3760
3761
				$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...
3762
				$file_array['type'] = $media_array['type'][0];
3763
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3764
				$file_array['error'] = $media_array['error'][0];
3765
				$file_array['size'] = $media_array['size'][0];
3766
3767
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3768
3769
				if ( is_wp_error( $edited_media_item ) ) {
3770
					return $edited_media_item;
3771
				}
3772
3773
				$response = (object) array(
3774
					'id'   => (string) $post_id,
3775
					'file' => (string) $edited_media_item->post_title,
3776
					'url'  => (string) wp_get_attachment_url( $post_id ),
3777
					'type' => (string) $edited_media_item->post_mime_type,
3778
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3779
				);
3780
3781
				return (array) array( $response );
3782
			}
3783
3784
			$attachment_id = media_handle_upload(
3785
				'.jetpack.upload.',
3786
				$post_id,
3787
				array(),
3788
				array(
3789
					'action' => 'jetpack_upload_file',
3790
				)
3791
			);
3792
3793
			if ( ! $attachment_id ) {
3794
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3795
			} elseif ( is_wp_error( $attachment_id ) ) {
3796
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3797
			} else {
3798
				$attachment = get_post( $attachment_id );
3799
				$uploaded_files[$index] = (object) array(
3800
					'id'   => (string) $attachment_id,
3801
					'file' => $attachment->post_title,
3802
					'url'  => wp_get_attachment_url( $attachment_id ),
3803
					'type' => $attachment->post_mime_type,
3804
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3805
				);
3806
				// Zip files uploads are not supported unless they are done for installation purposed
3807
				// lets delete them in case something goes wrong in this whole process
3808
				if ( 'application/zip' === $attachment->post_mime_type ) {
3809
					// Schedule a cleanup for 2 hours from now in case of failed install.
3810
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3811
				}
3812
			}
3813
		}
3814
		if ( ! is_null( $global_post ) ) {
3815
			$GLOBALS['post'] = $global_post;
3816
		}
3817
3818
		return $uploaded_files;
3819
	}
3820
3821
	/**
3822
	 * Add help to the Jetpack page
3823
	 *
3824
	 * @since Jetpack (1.2.3)
3825
	 * @return false if not the Jetpack page
3826
	 */
3827
	function admin_help() {
3828
		$current_screen = get_current_screen();
3829
3830
		// Overview
3831
		$current_screen->add_help_tab(
3832
			array(
3833
				'id'		=> 'home',
3834
				'title'		=> __( 'Home', 'jetpack' ),
3835
				'content'	=>
3836
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3837
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3838
					'<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>',
3839
			)
3840
		);
3841
3842
		// Screen Content
3843
		if ( current_user_can( 'manage_options' ) ) {
3844
			$current_screen->add_help_tab(
3845
				array(
3846
					'id'		=> 'settings',
3847
					'title'		=> __( 'Settings', 'jetpack' ),
3848
					'content'	=>
3849
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3850
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3851
						'<ol>' .
3852
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3853
							'<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>' .
3854
						'</ol>' .
3855
						'<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>'
3856
				)
3857
			);
3858
		}
3859
3860
		// Help Sidebar
3861
		$current_screen->set_help_sidebar(
3862
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3863
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3864
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3865
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3866
		);
3867
	}
3868
3869
	function admin_menu_css() {
3870
		wp_enqueue_style( 'jetpack-icons' );
3871
	}
3872
3873
	function admin_menu_order() {
3874
		return true;
3875
	}
3876
3877 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3878
		$jp_menu_order = array();
3879
3880
		foreach ( $menu_order as $index => $item ) {
3881
			if ( $item != 'jetpack' ) {
3882
				$jp_menu_order[] = $item;
3883
			}
3884
3885
			if ( $index == 0 ) {
3886
				$jp_menu_order[] = 'jetpack';
3887
			}
3888
		}
3889
3890
		return $jp_menu_order;
3891
	}
3892
3893
	function admin_banner_styles() {
3894
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3895
3896
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3897
			wp_register_style(
3898
				'jetpack-dops-style',
3899
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3900
				array(),
3901
				JETPACK__VERSION
3902
			);
3903
		}
3904
3905
		wp_enqueue_style(
3906
			'jetpack',
3907
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3908
			array( 'jetpack-dops-style' ),
3909
			 JETPACK__VERSION . '-20121016'
3910
		);
3911
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3912
		wp_style_add_data( 'jetpack', 'suffix', $min );
3913
	}
3914
3915
	function plugin_action_links( $actions ) {
3916
3917
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3918
3919
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3920
			return array_merge(
3921
				$jetpack_home,
3922
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3923
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3924
				$actions
3925
				);
3926
			}
3927
3928
		return array_merge( $jetpack_home, $actions );
3929
	}
3930
3931
	/*
3932
	 * Registration flow:
3933
	 * 1 - ::admin_page_load() action=register
3934
	 * 2 - ::try_registration()
3935
	 * 3 - ::register()
3936
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3937
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3938
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3939
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3940
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3941
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3942
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3943
	 *       jetpack_id, jetpack_secret, jetpack_public
3944
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3945
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3946
	 * 5 - user logs in with WP.com account
3947
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3948
	 *		- Jetpack_Client_Server::authorize()
3949
	 *		- Jetpack_Client_Server::get_token()
3950
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3951
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3952
	 *			- which responds with access_token, token_type, scope
3953
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3954
	 *		- Jetpack::activate_default_modules()
3955
	 *     		- Deactivates deprecated plugins
3956
	 *     		- Activates all default modules
3957
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3958
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3959
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3960
	 *     Done!
3961
	 */
3962
3963
	/**
3964
	 * Handles the page load events for the Jetpack admin page
3965
	 */
3966
	function admin_page_load() {
3967
		$error = false;
3968
3969
		// Make sure we have the right body class to hook stylings for subpages off of.
3970
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3971
3972
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3973
			// Should only be used in intermediate redirects to preserve state across redirects
3974
			Jetpack::restate();
3975
		}
3976
3977
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3978
			// @todo: Add validation against a known whitelist
3979
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3980
			// User clicked in the iframe to link their accounts
3981
			if ( ! Jetpack::is_user_connected() ) {
3982
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3983
3984
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3985
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3986
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3987
3988
				if ( isset( $_GET['notes_iframe'] ) )
3989
					$connect_url .= '&notes_iframe';
3990
				wp_redirect( $connect_url );
3991
				exit;
3992
			} else {
3993
				if ( ! isset( $_GET['calypso_env'] ) ) {
3994
					Jetpack::state( 'message', 'already_authorized' );
3995
					wp_safe_redirect( Jetpack::admin_url() );
3996
					exit;
3997
				} else {
3998
					$connect_url = $this->build_connect_url( true, false, $from );
3999
					$connect_url .= '&already_authorized=true';
4000
					wp_redirect( $connect_url );
4001
					exit;
4002
				}
4003
			}
4004
		}
4005
4006
4007
		if ( isset( $_GET['action'] ) ) {
4008
			switch ( $_GET['action'] ) {
4009
			case 'authorize':
4010
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4011
					Jetpack::state( 'message', 'already_authorized' );
4012
					wp_safe_redirect( Jetpack::admin_url() );
4013
					exit;
4014
				}
4015
				Jetpack::log( 'authorize' );
4016
				$client_server = new Jetpack_Client_Server;
4017
				$client_server->client_authorize();
4018
				exit;
4019
			case 'register' :
4020
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4021
					$error = 'cheatin';
4022
					break;
4023
				}
4024
				check_admin_referer( 'jetpack-register' );
4025
				Jetpack::log( 'register' );
4026
				Jetpack::maybe_set_version_option();
4027
				$registered = Jetpack::try_registration();
4028
				if ( is_wp_error( $registered ) ) {
4029
					$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...
4030
					Jetpack::state( 'error', $error );
4031
					Jetpack::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...
4032
4033
					/**
4034
					 * Jetpack registration Error.
4035
					 *
4036
					 * @since 7.5.0
4037
					 *
4038
					 * @param string|int $error The error code.
4039
					 * @param \WP_Error $registered The error object.
4040
					 */
4041
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4042
					break;
4043
				}
4044
4045
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4046
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4047
4048
				/**
4049
				 * Jetpack registration Success.
4050
				 *
4051
				 * @since 7.5.0
4052
				 *
4053
				 * @param string $from 'from' GET parameter;
4054
				 */
4055
				do_action( 'jetpack_connection_register_success', $from );
4056
4057
				$url = $this->build_connect_url( true, $redirect, $from );
4058
4059
				if ( ! empty( $_GET['onboarding'] ) ) {
4060
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4061
				}
4062
4063
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4064
					$url = add_query_arg( 'auth_approved', 'true', $url );
4065
				}
4066
4067
				wp_redirect( $url );
4068
				exit;
4069
			case 'activate' :
4070
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4071
					$error = 'cheatin';
4072
					break;
4073
				}
4074
4075
				$module = stripslashes( $_GET['module'] );
4076
				check_admin_referer( "jetpack_activate-$module" );
4077
				Jetpack::log( 'activate', $module );
4078
				if ( ! Jetpack::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression \Jetpack::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...
4079
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4080
				}
4081
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4082
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4083
				exit;
4084
			case 'activate_default_modules' :
4085
				check_admin_referer( 'activate_default_modules' );
4086
				Jetpack::log( 'activate_default_modules' );
4087
				Jetpack::restate();
4088
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4089
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4090
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4091
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4092
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4093
				exit;
4094
			case 'disconnect' :
4095
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4096
					$error = 'cheatin';
4097
					break;
4098
				}
4099
4100
				check_admin_referer( 'jetpack-disconnect' );
4101
				Jetpack::log( 'disconnect' );
4102
				Jetpack::disconnect();
4103
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4104
				exit;
4105
			case 'reconnect' :
4106
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4107
					$error = 'cheatin';
4108
					break;
4109
				}
4110
4111
				check_admin_referer( 'jetpack-reconnect' );
4112
				Jetpack::log( 'reconnect' );
4113
				$this->disconnect();
4114
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4115
				exit;
4116 View Code Duplication
			case 'deactivate' :
4117
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4118
					$error = 'cheatin';
4119
					break;
4120
				}
4121
4122
				$modules = stripslashes( $_GET['module'] );
4123
				check_admin_referer( "jetpack_deactivate-$modules" );
4124
				foreach ( explode( ',', $modules ) as $module ) {
4125
					Jetpack::log( 'deactivate', $module );
4126
					Jetpack::deactivate_module( $module );
4127
					Jetpack::state( 'message', 'module_deactivated' );
4128
				}
4129
				Jetpack::state( 'module', $modules );
4130
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4131
				exit;
4132
			case 'unlink' :
4133
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4134
				check_admin_referer( 'jetpack-unlink' );
4135
				Jetpack::log( 'unlink' );
4136
				Connection_Manager::disconnect_user();
4137
				Jetpack::state( 'message', 'unlinked' );
4138
				if ( 'sub-unlink' == $redirect ) {
4139
					wp_safe_redirect( admin_url() );
4140
				} else {
4141
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4142
				}
4143
				exit;
4144
			case 'onboard' :
4145
				if ( ! current_user_can( 'manage_options' ) ) {
4146
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4147
				} else {
4148
					Jetpack::create_onboarding_token();
4149
					$url = $this->build_connect_url( true );
4150
4151
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4152
						$url = add_query_arg( 'onboarding', $token, $url );
4153
					}
4154
4155
					$calypso_env = $this->get_calypso_env();
4156
					if ( ! empty( $calypso_env ) ) {
4157
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4158
					}
4159
4160
					wp_redirect( $url );
4161
					exit;
4162
				}
4163
				exit;
4164
			default:
4165
				/**
4166
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4167
				 *
4168
				 * @since 2.6.0
4169
				 *
4170
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4171
				 */
4172
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4173
			}
4174
		}
4175
4176
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4177
			self::activate_new_modules( true );
4178
		}
4179
4180
		$message_code = Jetpack::state( 'message' );
4181
		if ( Jetpack::state( 'optin-manage' ) ) {
4182
			$activated_manage = $message_code;
4183
			$message_code = 'jetpack-manage';
4184
		}
4185
4186
		switch ( $message_code ) {
4187
		case 'jetpack-manage':
4188
			$this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), 'https://wordpress.com/sites' ) . '</strong>';
4189
			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...
4190
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4191
			}
4192
			break;
4193
4194
		}
4195
4196
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4197
4198
		if ( ! empty( $deactivated_plugins ) ) {
4199
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4200
			$deactivated_titles  = array();
4201
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4202
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4203
					continue;
4204
				}
4205
4206
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4207
			}
4208
4209
			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...
4210
				if ( $this->message ) {
4211
					$this->message .= "<br /><br />\n";
4212
				}
4213
4214
				$this->message .= wp_sprintf(
4215
					_n(
4216
						'Jetpack contains the most recent version of the old %l plugin.',
4217
						'Jetpack contains the most recent versions of the old %l plugins.',
4218
						count( $deactivated_titles ),
4219
						'jetpack'
4220
					),
4221
					$deactivated_titles
4222
				);
4223
4224
				$this->message .= "<br />\n";
4225
4226
				$this->message .= _n(
4227
					'The old version has been deactivated and can be removed from your site.',
4228
					'The old versions have been deactivated and can be removed from your site.',
4229
					count( $deactivated_titles ),
4230
					'jetpack'
4231
				);
4232
			}
4233
		}
4234
4235
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4236
4237
		if ( $this->message || $this->error || $this->privacy_checks ) {
4238
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4239
		}
4240
4241
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4242
	}
4243
4244
	function admin_notices() {
4245
4246
		if ( $this->error ) {
4247
?>
4248
<div id="message" class="jetpack-message jetpack-err">
4249
	<div class="squeezer">
4250
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4251
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4252
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4253
<?php	endif; ?>
4254
	</div>
4255
</div>
4256
<?php
4257
		}
4258
4259
		if ( $this->message ) {
4260
?>
4261
<div id="message" class="jetpack-message">
4262
	<div class="squeezer">
4263
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4264
	</div>
4265
</div>
4266
<?php
4267
		}
4268
4269
		if ( $this->privacy_checks ) :
4270
			$module_names = $module_slugs = array();
4271
4272
			$privacy_checks = explode( ',', $this->privacy_checks );
4273
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4274
			foreach ( $privacy_checks as $module_slug ) {
4275
				$module = Jetpack::get_module( $module_slug );
4276
				if ( ! $module ) {
4277
					continue;
4278
				}
4279
4280
				$module_slugs[] = $module_slug;
4281
				$module_names[] = "<strong>{$module['name']}</strong>";
4282
			}
4283
4284
			$module_slugs = join( ',', $module_slugs );
4285
?>
4286
<div id="message" class="jetpack-message jetpack-err">
4287
	<div class="squeezer">
4288
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4289
		<p><?php
4290
			echo wp_kses(
4291
				wptexturize(
4292
					wp_sprintf(
4293
						_nx(
4294
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4295
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4296
							count( $privacy_checks ),
4297
							'%l = list of Jetpack module/feature names',
4298
							'jetpack'
4299
						),
4300
						$module_names
4301
					)
4302
				),
4303
				array( 'strong' => true )
4304
			);
4305
4306
			echo "\n<br />\n";
4307
4308
			echo wp_kses(
4309
				sprintf(
4310
					_nx(
4311
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4312
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4313
						count( $privacy_checks ),
4314
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4315
						'jetpack'
4316
					),
4317
					wp_nonce_url(
4318
						Jetpack::admin_url(
4319
							array(
4320
								'page'   => 'jetpack',
4321
								'action' => 'deactivate',
4322
								'module' => urlencode( $module_slugs ),
4323
							)
4324
						),
4325
						"jetpack_deactivate-$module_slugs"
4326
					),
4327
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4328
				),
4329
				array( 'a' => array( 'href' => true, 'title' => true ) )
4330
			);
4331
		?></p>
4332
	</div>
4333
</div>
4334
<?php endif;
4335
	}
4336
4337
	/**
4338
	 * We can't always respond to a signed XML-RPC request with a
4339
	 * helpful error message. In some circumstances, doing so could
4340
	 * leak information.
4341
	 *
4342
	 * Instead, track that the error occurred via a Jetpack_Option,
4343
	 * and send that data back in the heartbeat.
4344
	 * All this does is increment a number, but it's enough to find
4345
	 * trends.
4346
	 *
4347
	 * @param WP_Error $xmlrpc_error The error produced during
4348
	 *                               signature validation.
4349
	 */
4350
	function track_xmlrpc_error( $xmlrpc_error ) {
4351
		$code = is_wp_error( $xmlrpc_error )
4352
			? $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...
4353
			: 'should-not-happen';
4354
4355
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4356
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4357
			// No need to update the option if we already have
4358
			// this code stored.
4359
			return;
4360
		}
4361
		$xmlrpc_errors[ $code ] = true;
4362
4363
		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...
4364
	}
4365
4366
	/**
4367
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4368
	 */
4369
	function stat( $group, $detail ) {
4370
		if ( ! isset( $this->stats[ $group ] ) )
4371
			$this->stats[ $group ] = array();
4372
		$this->stats[ $group ][] = $detail;
4373
	}
4374
4375
	/**
4376
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4377
	 */
4378
	function do_stats( $method = '' ) {
4379
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4380
			foreach ( $this->stats as $group => $stats ) {
4381
				if ( is_array( $stats ) && count( $stats ) ) {
4382
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4383
					if ( 'server_side' === $method ) {
4384
						self::do_server_side_stat( $args );
4385
					} else {
4386
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4387
					}
4388
				}
4389
				unset( $this->stats[ $group ] );
4390
			}
4391
		}
4392
	}
4393
4394
	/**
4395
	 * Runs stats code for a one-off, server-side.
4396
	 *
4397
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4398
	 *
4399
	 * @return bool If it worked.
4400
	 */
4401
	static function do_server_side_stat( $args ) {
4402
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4403
		if ( is_wp_error( $response ) )
4404
			return false;
4405
4406
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4407
			return false;
4408
4409
		return true;
4410
	}
4411
4412
	/**
4413
	 * Builds the stats url.
4414
	 *
4415
	 * @param $args array|string The arguments to append to the URL.
4416
	 *
4417
	 * @return string The URL to be pinged.
4418
	 */
4419
	static function build_stats_url( $args ) {
4420
		$defaults = array(
4421
			'v'    => 'wpcom2',
4422
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4423
		);
4424
		$args     = wp_parse_args( $args, $defaults );
4425
		/**
4426
		 * Filter the URL used as the Stats tracking pixel.
4427
		 *
4428
		 * @since 2.3.2
4429
		 *
4430
		 * @param string $url Base URL used as the Stats tracking pixel.
4431
		 */
4432
		$base_url = apply_filters(
4433
			'jetpack_stats_base_url',
4434
			'https://pixel.wp.com/g.gif'
4435
		);
4436
		$url      = add_query_arg( $args, $base_url );
4437
		return $url;
4438
	}
4439
4440
	/**
4441
	 * Get the role of the current user.
4442
	 *
4443
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4444
	 *
4445
	 * @access public
4446
	 * @static
4447
	 *
4448
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4449
	 */
4450
	public static function translate_current_user_to_role() {
4451
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4452
4453
		$roles = new Roles();
4454
		return $roles->translate_current_user_to_role();
4455
	}
4456
4457
	/**
4458
	 * Get the role of a particular user.
4459
	 *
4460
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4461
	 *
4462
	 * @access public
4463
	 * @static
4464
	 *
4465
	 * @param \WP_User $user User object.
4466
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4467
	 */
4468
	public static function translate_user_to_role( $user ) {
4469
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4470
4471
		$roles = new Roles();
4472
		return $roles->translate_user_to_role( $user );
4473
	}
4474
4475
	/**
4476
	 * Get the minimum capability for a role.
4477
	 *
4478
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4479
	 *
4480
	 * @access public
4481
	 * @static
4482
	 *
4483
	 * @param string $role Role name.
4484
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4485
	 */
4486
	public static function translate_role_to_cap( $role ) {
4487
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4488
4489
		$roles = new Roles();
4490
		return $roles->translate_role_to_cap( $role );
4491
	}
4492
4493
	/**
4494
	 * Sign a user role with the master access token.
4495
	 * If not specified, will default to the current user.
4496
	 *
4497
	 * @deprecated since 7.7
4498
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4499
	 *
4500
	 * @access public
4501
	 * @static
4502
	 *
4503
	 * @param string $role    User role.
4504
	 * @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...
4505
	 * @return string Signed user role.
4506
	 */
4507
	public static function sign_role( $role, $user_id = null ) {
4508
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4509
		return self::connection()->sign_role( $role, $user_id );
4510
	}
4511
4512
	/**
4513
	 * Builds a URL to the Jetpack connection auth page
4514
	 *
4515
	 * @since 3.9.5
4516
	 *
4517
	 * @param bool $raw If true, URL will not be escaped.
4518
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4519
	 *                              If string, will be a custom redirect.
4520
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4521
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4522
	 *
4523
	 * @return string Connect URL
4524
	 */
4525
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4526
		$site_id = Jetpack_Options::get_option( 'id' );
4527
		$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...
4528
4529
		if ( $register || ! $blog_token || ! $site_id ) {
4530
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4531
4532
			if ( ! empty( $redirect ) ) {
4533
				$url = add_query_arg(
4534
					'redirect',
4535
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4536
					$url
4537
				);
4538
			}
4539
4540
			if( is_network_admin() ) {
4541
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4542
			}
4543
		} else {
4544
4545
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4546
			// because otherwise this logic can get us in to a loop.
4547
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4548
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4549
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4550
4551
				$response = Client::wpcom_json_api_request_as_blog(
4552
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4553
					'1.1'
4554
				);
4555
4556
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4557
4558
					// Generating a register URL instead to refresh the existing token
4559
					return $this->build_connect_url( $raw, $redirect, $from, true );
4560
				}
4561
			}
4562
4563
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4525 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...
4564
		}
4565
4566
		if ( $from ) {
4567
			$url = add_query_arg( 'from', $from, $url );
4568
		}
4569
4570
		// Ensure that class to get the affiliate code is loaded
4571
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4572
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4573
		}
4574
		// Get affiliate code and add it to the URL
4575
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4576
4577
		$calypso_env = $this->get_calypso_env();
4578
4579
		if ( ! empty( $calypso_env ) ) {
4580
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4581
		}
4582
4583
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4584
	}
4585
4586
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4587
		if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4588
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4589
		}
4590
4591
		$roles       = new Roles();
4592
		$role        = $roles->translate_current_user_to_role();
4593
		$signed_role = self::connection()->sign_role( $role );
4594
4595
		$user = wp_get_current_user();
4596
4597
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4598
		$redirect = $redirect
4599
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4600
			: $jetpack_admin_page;
4601
4602
		if( isset( $_REQUEST['is_multisite'] ) ) {
4603
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4604
		}
4605
4606
		$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4607
4608
		/**
4609
		 * Filter the type of authorization.
4610
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4611
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4612
		 *
4613
		 * @since 4.3.3
4614
		 *
4615
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4616
		 */
4617
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4618
4619
4620
		$tracks = new Tracking();
4621
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4622
4623
		$args = urlencode_deep(
4624
			array(
4625
				'response_type' => 'code',
4626
				'client_id'     => Jetpack_Options::get_option( 'id' ),
4627
				'redirect_uri'  => add_query_arg(
4628
					array(
4629
						'action'   => 'authorize',
4630
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4631
						'redirect' => urlencode( $redirect ),
4632
					),
4633
					esc_url( admin_url( 'admin.php?page=jetpack' ) )
4634
				),
4635
				'state'         => $user->ID,
4636
				'scope'         => $signed_role,
4637
				'user_email'    => $user->user_email,
4638
				'user_login'    => $user->user_login,
4639
				'is_active'     => Jetpack::is_active(),
4640
				'jp_version'    => JETPACK__VERSION,
4641
				'auth_type'     => $auth_type,
4642
				'secret'        => $secrets['secret_1'],
4643
				'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4644
				'blogname'      => get_option( 'blogname' ),
4645
				'site_url'      => site_url(),
4646
				'home_url'      => home_url(),
4647
				'site_icon'     => get_site_icon_url(),
4648
				'site_lang'     => get_locale(),
4649
				'_ui'           => $tracks_identity['_ui'],
4650
				'_ut'           => $tracks_identity['_ut'],
4651
				'site_created'  => Jetpack::get_assumed_site_creation_date(),
4652
			)
4653
		);
4654
4655
		self::apply_activation_source_to_args( $args );
4656
4657
		$connection = self::connection();
4658
4659
		$api_url = $iframe ? $connection->api_url( 'authorize_iframe' ) : $connection->api_url( 'authorize' );
4660
4661
		return add_query_arg( $args, $api_url );
4662
	}
4663
4664
	/**
4665
	 * Get our assumed site creation date.
4666
	 * Calculated based on the earlier date of either:
4667
	 * - Earliest admin user registration date.
4668
	 * - Earliest date of post of any post type.
4669
	 *
4670
	 * @since 7.2.0
4671
	 *
4672
	 * @return string Assumed site creation date and time.
4673
	 */
4674 View Code Duplication
	public static function get_assumed_site_creation_date() {
4675
		$earliest_registered_users = get_users( array(
4676
			'role'    => 'administrator',
4677
			'orderby' => 'user_registered',
4678
			'order'   => 'ASC',
4679
			'fields'  => array( 'user_registered' ),
4680
			'number'  => 1,
4681
		) );
4682
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4683
4684
		$earliest_posts = get_posts( array(
4685
			'posts_per_page' => 1,
4686
			'post_type'      => 'any',
4687
			'post_status'    => 'any',
4688
			'orderby'        => 'date',
4689
			'order'          => 'ASC',
4690
		) );
4691
4692
		// If there are no posts at all, we'll count only on user registration date.
4693
		if ( $earliest_posts ) {
4694
			$earliest_post_date = $earliest_posts[0]->post_date;
4695
		} else {
4696
			$earliest_post_date = PHP_INT_MAX;
4697
		}
4698
4699
		return min( $earliest_registration_date, $earliest_post_date );
4700
	}
4701
4702 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4703
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4704
4705
		if ( $activation_source_name ) {
4706
			$args['_as'] = urlencode( $activation_source_name );
4707
		}
4708
4709
		if ( $activation_source_keyword ) {
4710
			$args['_ak'] = urlencode( $activation_source_keyword );
4711
		}
4712
	}
4713
4714
	function build_reconnect_url( $raw = false ) {
4715
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4716
		return $raw ? $url : esc_url( $url );
4717
	}
4718
4719
	public static function admin_url( $args = null ) {
4720
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4721
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4722
		return $url;
4723
	}
4724
4725
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4726
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4727
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4728
	}
4729
4730
	function dismiss_jetpack_notice() {
4731
4732
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4733
			return;
4734
		}
4735
4736
		switch( $_GET['jetpack-notice'] ) {
4737
			case 'dismiss':
4738
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4739
4740
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4741
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4742
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4743
				}
4744
				break;
4745
		}
4746
	}
4747
4748
	public static function sort_modules( $a, $b ) {
4749
		if ( $a['sort'] == $b['sort'] )
4750
			return 0;
4751
4752
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4753
	}
4754
4755
	function ajax_recheck_ssl() {
4756
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4757
		$result = Jetpack::permit_ssl( true );
4758
		wp_send_json( array(
4759
			'enabled' => $result,
4760
			'message' => get_transient( 'jetpack_https_test_message' )
4761
		) );
4762
	}
4763
4764
/* Client API */
4765
4766
	/**
4767
	 * Returns the requested Jetpack API URL
4768
	 *
4769
	 * @deprecated since 7.7
4770
	 * @return string
4771
	 */
4772
	public static function api_url( $relative_url ) {
4773
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4774
		$connection = self::connection();
4775
		return $connection->api_url( $relative_url );
4776
	}
4777
4778
	/**
4779
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4780
	 */
4781
	public static function fix_url_for_bad_hosts( $url ) {
4782
		if ( 0 !== strpos( $url, 'https://' ) ) {
4783
			return $url;
4784
		}
4785
4786
		switch ( JETPACK_CLIENT__HTTPS ) {
4787
			case 'ALWAYS' :
4788
				return $url;
4789
			case 'NEVER' :
4790
				return set_url_scheme( $url, 'http' );
4791
			// default : case 'AUTO' :
4792
		}
4793
4794
		// we now return the unmodified SSL URL by default, as a security precaution
4795
		return $url;
4796
	}
4797
4798
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4799
		// Default to a blog token.
4800
		$token_type = 'blog';
4801
4802
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4803
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4804
			if ( ! empty( $_GET['onboarding'] ) ) {
4805
				$jpo = $_GET;
4806
			} else {
4807
				$jpo = json_decode( $request_data, true );
4808
			}
4809
4810
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4811
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4812
4813
			if (
4814
				isset( $jpo_user )
4815
				&& isset( $jpo_token )
4816
				&& is_email( $jpo_user )
4817
				&& ctype_alnum( $jpo_token )
4818
				&& isset( $_GET['rest_route'] )
4819
				&& self::validate_onboarding_token_action(
4820
					$jpo_token,
4821
					$_GET['rest_route']
4822
				)
4823
			) {
4824
				$jp_user = get_user_by( 'email', $jpo_user );
4825
				if ( is_a( $jp_user, 'WP_User' ) ) {
4826
					wp_set_current_user( $jp_user->ID );
4827
					$user_can = is_multisite()
4828
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4829
						: current_user_can( 'manage_options' );
4830
					if ( $user_can ) {
4831
						$token_type = 'user';
4832
						$token->external_user_id = $jp_user->ID;
4833
					}
4834
				}
4835
			}
4836
4837
			$token_data['type']    = $token_type;
4838
			$token_data['user_id'] = $token->external_user_id;
4839
		}
4840
4841
		return $token_data;
4842
	}
4843
4844
	/**
4845
	 * Create a random secret for validating onboarding payload
4846
	 *
4847
	 * @return string Secret token
4848
	 */
4849
	public static function create_onboarding_token() {
4850
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4851
			$token = wp_generate_password( 32, false );
4852
			Jetpack_Options::update_option( 'onboarding', $token );
4853
		}
4854
4855
		return $token;
4856
	}
4857
4858
	/**
4859
	 * Remove the onboarding token
4860
	 *
4861
	 * @return bool True on success, false on failure
4862
	 */
4863
	public static function invalidate_onboarding_token() {
4864
		return Jetpack_Options::delete_option( 'onboarding' );
4865
	}
4866
4867
	/**
4868
	 * Validate an onboarding token for a specific action
4869
	 *
4870
	 * @return boolean True if token/action pair is accepted, false if not
4871
	 */
4872
	public static function validate_onboarding_token_action( $token, $action ) {
4873
		// Compare tokens, bail if tokens do not match
4874
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4875
			return false;
4876
		}
4877
4878
		// List of valid actions we can take
4879
		$valid_actions = array(
4880
			'/jetpack/v4/settings',
4881
		);
4882
4883
		// Whitelist the action
4884
		if ( ! in_array( $action, $valid_actions ) ) {
4885
			return false;
4886
		}
4887
4888
		return true;
4889
	}
4890
4891
	/**
4892
	 * Checks to see if the URL is using SSL to connect with Jetpack
4893
	 *
4894
	 * @since 2.3.3
4895
	 * @return boolean
4896
	 */
4897
	public static function permit_ssl( $force_recheck = false ) {
4898
		// Do some fancy tests to see if ssl is being supported
4899
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4900
			$message = '';
4901
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4902
				$ssl = 0;
4903
			} else {
4904
				switch ( JETPACK_CLIENT__HTTPS ) {
4905
					case 'NEVER':
4906
						$ssl = 0;
4907
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4908
						break;
4909
					case 'ALWAYS':
4910
					case 'AUTO':
4911
					default:
4912
						$ssl = 1;
4913
						break;
4914
				}
4915
4916
				// If it's not 'NEVER', test to see
4917
				if ( $ssl ) {
4918
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4919
						$ssl = 0;
4920
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4921
					} else {
4922
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4923
						if ( is_wp_error( $response ) ) {
4924
							$ssl = 0;
4925
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4926
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4927
							$ssl = 0;
4928
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4929
						}
4930
					}
4931
				}
4932
			}
4933
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4934
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4935
		}
4936
4937
		return (bool) $ssl;
4938
	}
4939
4940
	/*
4941
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4942
	 */
4943
	public function alert_auto_ssl_fail() {
4944
		if ( ! current_user_can( 'manage_options' ) )
4945
			return;
4946
4947
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4948
		?>
4949
4950
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4951
			<div class="jp-banner__content">
4952
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4953
				<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>
4954
				<p>
4955
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4956
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4957
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4958
				</p>
4959
				<p>
4960
					<?php printf( __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
4961
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4962
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4963
				</p>
4964
			</div>
4965
		</div>
4966
		<style>
4967
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4968
		</style>
4969
		<script type="text/javascript">
4970
			jQuery( document ).ready( function( $ ) {
4971
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4972
					var $this = $( this );
4973
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4974
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4975
					e.preventDefault();
4976
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4977
					$.post( ajaxurl, data )
4978
					  .done( function( response ) {
4979
					  	if ( response.enabled ) {
4980
					  		$( '#jetpack-ssl-warning' ).hide();
4981
					  	} else {
4982
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4983
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4984
					  	}
4985
					  }.bind( $this ) );
4986
				} );
4987
			} );
4988
		</script>
4989
4990
		<?php
4991
	}
4992
4993
	/**
4994
	 * Returns the Jetpack XML-RPC API
4995
	 *
4996
	 * @return string
4997
	 */
4998
	public static function xmlrpc_api_url() {
4999
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
5000
		return untrailingslashit( $base ) . '/xmlrpc.php';
5001
	}
5002
5003
	public static function connection() {
5004
		return self::init()->connection_manager;
5005
	}
5006
5007
	/**
5008
	 * Creates two secret tokens and the end of life timestamp for them.
5009
	 *
5010
	 * Note these tokens are unique per call, NOT static per site for connecting.
5011
	 *
5012
	 * @since 2.6
5013
	 * @return array
5014
	 */
5015
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5016
		if ( false === $user_id ) {
5017
			$user_id = get_current_user_id();
5018
		}
5019
5020
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5021
	}
5022
5023
	public static function get_secrets( $action, $user_id ) {
5024
		$secrets = self::connection()->get_secrets( $action, $user_id );
5025
5026
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5027
			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...
5028
		}
5029
5030
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5031
			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...
5032
		}
5033
5034
		return $secrets;
5035
	}
5036
5037
	/**
5038
	 * @deprecated 7.5 Use Connection_Manager instead.
5039
	 *
5040
	 * @param $action
5041
	 * @param $user_id
5042
	 */
5043
	public static function delete_secrets( $action, $user_id ) {
5044
		return self::connection()->delete_secrets( $action, $user_id );
5045
	}
5046
5047
	/**
5048
	 * Builds the timeout limit for queries talking with the wpcom servers.
5049
	 *
5050
	 * Based on local php max_execution_time in php.ini
5051
	 *
5052
	 * @since 2.6
5053
	 * @return int
5054
	 * @deprecated
5055
	 **/
5056
	public function get_remote_query_timeout_limit() {
5057
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5058
		return Jetpack::get_max_execution_time();
5059
	}
5060
5061
	/**
5062
	 * Builds the timeout limit for queries talking with the wpcom servers.
5063
	 *
5064
	 * Based on local php max_execution_time in php.ini
5065
	 *
5066
	 * @since 5.4
5067
	 * @return int
5068
	 **/
5069
	public static function get_max_execution_time() {
5070
		$timeout = (int) ini_get( 'max_execution_time' );
5071
5072
		// Ensure exec time set in php.ini
5073
		if ( ! $timeout ) {
5074
			$timeout = 30;
5075
		}
5076
		return $timeout;
5077
	}
5078
5079
	/**
5080
	 * Sets a minimum request timeout, and returns the current timeout
5081
	 *
5082
	 * @since 5.4
5083
	 **/
5084 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5085
		$timeout = self::get_max_execution_time();
5086
		if ( $timeout < $min_timeout ) {
5087
			$timeout = $min_timeout;
5088
			set_time_limit( $timeout );
5089
		}
5090
		return $timeout;
5091
	}
5092
5093
	/**
5094
	 * Takes the response from the Jetpack register new site endpoint and
5095
	 * verifies it worked properly.
5096
	 *
5097
	 * @since 2.6
5098
	 * @deprecated since 7.7.0
5099
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5100
	 **/
5101
	public function validate_remote_register_response() {
5102
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5103
	}
5104
5105
	/**
5106
	 * @return bool|WP_Error
5107
	 */
5108
	public static function register() {
5109
		$tracking = new Tracking();
5110
		$tracking->record_user_event( 'jpc_register_begin' );
5111
5112
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5113
5114
		$connection = self::connection();
5115
		$registration = $connection->register();
5116
5117
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5118
5119
		if ( ! $registration || is_wp_error( $registration ) ) {
5120
			return $registration;
5121
		}
5122
5123
		return true;
5124
	}
5125
5126
	/**
5127
	 * Filters the registration request body to include tracking properties.
5128
	 *
5129
	 * @param Array $properties
5130
	 * @return Array amended properties.
5131
	 */
5132
	public static function filter_register_request_body( $properties ) {
5133
		$tracking = new Tracking();
5134
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5135
5136
		return array_merge(
5137
			$properties,
5138
			array(
5139
				'_ui' => $tracks_identity['_ui'],
5140
				'_ut' => $tracks_identity['_ut'],
5141
			)
5142
		);
5143
	}
5144
5145
	/**
5146
	 * If the db version is showing something other that what we've got now, bump it to current.
5147
	 *
5148
	 * @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...
5149
	 */
5150
	public static function maybe_set_version_option() {
5151
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5152
		if ( JETPACK__VERSION != $version ) {
5153
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5154
5155
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5156
				/** This action is documented in class.jetpack.php */
5157
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5158
			}
5159
5160
			return true;
5161
		}
5162
		return false;
5163
	}
5164
5165
/* Client Server API */
5166
5167
	/**
5168
	 * Loads the Jetpack XML-RPC client.
5169
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5170
	 *
5171
	 * @deprecated since 7.7.0
5172
	 */
5173
	public static function load_xml_rpc_client() {
5174
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5175
	}
5176
5177
	/**
5178
	 * Resets the saved authentication state in between testing requests.
5179
	 */
5180
	public function reset_saved_auth_state() {
5181
		$this->rest_authentication_status = null;
5182
		$this->connection_manager->reset_saved_auth_state();
5183
	}
5184
5185
	/**
5186
	 * Verifies the signature of the current request.
5187
	 *
5188
	 * @deprecated since 7.7.0
5189
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5190
	 *
5191
	 * @return false|array
5192
	 */
5193
	public function verify_xml_rpc_signature() {
5194
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5195
		return self::connection()->verify_xml_rpc_signature();
5196
	}
5197
5198
	/**
5199
	 * Verifies the signature of the current request.
5200
	 *
5201
	 * This function has side effects and should not be used. Instead,
5202
	 * use the memoized version `->verify_xml_rpc_signature()`.
5203
	 *
5204
	 * @deprecated since 7.7.0
5205
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5206
	 * @internal
5207
	 */
5208
	private function internal_verify_xml_rpc_signature() {
5209
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5210
	}
5211
5212
	/**
5213
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5214
	 *
5215
	 * @deprecated since 7.7.0
5216
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5217
	 *
5218
	 * @param \WP_User|mixed $user     User object if authenticated.
5219
	 * @param string         $username Username.
5220
	 * @param string         $password Password string.
5221
	 * @return \WP_User|mixed Authenticated user or error.
5222
	 */
5223
	public function authenticate_jetpack( $user, $username, $password ) {
5224
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5225
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5226
	}
5227
5228
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5229
	// Uses the existing XMLRPC request signing implementation.
5230
	function wp_rest_authenticate( $user ) {
5231
		if ( ! empty( $user ) ) {
5232
			// Another authentication method is in effect.
5233
			return $user;
5234
		}
5235
5236
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5237
			// Nothing to do for this authentication method.
5238
			return null;
5239
		}
5240
5241
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5242
			// Nothing to do for this authentication method.
5243
			return null;
5244
		}
5245
5246
		// Ensure that we always have the request body available.  At this
5247
		// point, the WP REST API code to determine the request body has not
5248
		// run yet.  That code may try to read from 'php://input' later, but
5249
		// this can only be done once per request in PHP versions prior to 5.6.
5250
		// So we will go ahead and perform this read now if needed, and save
5251
		// the request body where both the Jetpack signature verification code
5252
		// and the WP REST API code can see it.
5253
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5254
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5255
		}
5256
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5257
5258
		// Only support specific request parameters that have been tested and
5259
		// are known to work with signature verification.  A different method
5260
		// can be passed to the WP REST API via the '?_method=' parameter if
5261
		// needed.
5262
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5263
			$this->rest_authentication_status = new WP_Error(
5264
				'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...
5265
				__( 'This request method is not supported.', 'jetpack' ),
5266
				array( 'status' => 400 )
5267
			);
5268
			return null;
5269
		}
5270
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5271
			$this->rest_authentication_status = new WP_Error(
5272
				'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...
5273
				__( 'This request method does not support body parameters.', 'jetpack' ),
5274
				array( 'status' => 400 )
5275
			);
5276
			return null;
5277
		}
5278
5279
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5280
5281
		if (
5282
			$verified &&
5283
			isset( $verified['type'] ) &&
5284
			'user' === $verified['type'] &&
5285
			! empty( $verified['user_id'] )
5286
		) {
5287
			// Authentication successful.
5288
			$this->rest_authentication_status = true;
5289
			return $verified['user_id'];
5290
		}
5291
5292
		// Something else went wrong.  Probably a signature error.
5293
		$this->rest_authentication_status = new WP_Error(
5294
			'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...
5295
			__( 'The request is not signed correctly.', 'jetpack' ),
5296
			array( 'status' => 400 )
5297
		);
5298
		return null;
5299
	}
5300
5301
	/**
5302
	 * Report authentication status to the WP REST API.
5303
	 *
5304
	 * @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...
5305
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5306
	 */
5307
	public function wp_rest_authentication_errors( $value ) {
5308
		if ( $value !== null ) {
5309
			return $value;
5310
		}
5311
		return $this->rest_authentication_status;
5312
	}
5313
5314
	/**
5315
	 * Add our nonce to this request.
5316
	 *
5317
	 * @deprecated since 7.7.0
5318
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5319
	 *
5320
	 * @param int    $timestamp Timestamp of the request.
5321
	 * @param string $nonce     Nonce string.
5322
	 */
5323
	public function add_nonce( $timestamp, $nonce ) {
5324
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5325
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5326
	}
5327
5328
	/**
5329
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5330
	 * Capture it here so we can verify the signature later.
5331
	 *
5332
	 * @deprecated since 7.7.0
5333
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5334
	 *
5335
	 * @param array $methods XMLRPC methods.
5336
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5337
	 */
5338
	public function xmlrpc_methods( $methods ) {
5339
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5340
		return $this->connection_manager->xmlrpc_methods( $methods );
5341
	}
5342
5343
	/**
5344
	 * Register additional public XMLRPC methods.
5345
	 *
5346
	 * @deprecated since 7.7.0
5347
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5348
	 *
5349
	 * @param array $methods Public XMLRPC methods.
5350
	 * @return array Public XMLRPC methods, with the getOptions one.
5351
	 */
5352
	public function public_xmlrpc_methods( $methods ) {
5353
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5354
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5355
	}
5356
5357
	/**
5358
	 * Handles a getOptions XMLRPC method call.
5359
	 *
5360
	 * @deprecated since 7.7.0
5361
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5362
	 *
5363
	 * @param array $args method call arguments.
5364
	 * @return array an amended XMLRPC server options array.
5365
	 */
5366
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5367
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5368
		return $this->connection_manager->jetpack_getOptions( $args );
5369
	}
5370
5371
	/**
5372
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5373
	 *
5374
	 * @deprecated since 7.7.0
5375
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5376
	 *
5377
	 * @param array $options Standard Core options.
5378
	 * @return array Amended options.
5379
	 */
5380
	public function xmlrpc_options( $options ) {
5381
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5382
		return $this->connection_manager->xmlrpc_options( $options );
5383
	}
5384
5385
	/**
5386
	 * Cleans nonces that were saved when calling ::add_nonce.
5387
	 *
5388
	 * @deprecated since 7.7.0
5389
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5390
	 *
5391
	 * @param bool $all whether to clean even non-expired nonces.
5392
	 */
5393
	public static function clean_nonces( $all = false ) {
5394
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5395
		return self::connection()->clean_nonces( $all );
5396
	}
5397
5398
	/**
5399
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5400
	 * SET: state( $key, $value );
5401
	 * GET: $value = state( $key );
5402
	 *
5403
	 * @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...
5404
	 * @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...
5405
	 * @param bool $restate private
5406
	 */
5407
	public static function state( $key = null, $value = null, $restate = false ) {
5408
		static $state = array();
5409
		static $path, $domain;
5410
		if ( ! isset( $path ) ) {
5411
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5412
			$admin_url = Jetpack::admin_url();
5413
			$bits      = wp_parse_url( $admin_url );
5414
5415
			if ( is_array( $bits ) ) {
5416
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5417
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5418
			} else {
5419
				$path = $domain = null;
5420
			}
5421
		}
5422
5423
		// Extract state from cookies and delete cookies
5424
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5425
			$yum = $_COOKIE[ 'jetpackState' ];
5426
			unset( $_COOKIE[ 'jetpackState' ] );
5427
			foreach ( $yum as $k => $v ) {
5428
				if ( strlen( $v ) )
5429
					$state[ $k ] = $v;
5430
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5431
			}
5432
		}
5433
5434
		if ( $restate ) {
5435
			foreach ( $state as $k => $v ) {
5436
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5437
			}
5438
			return;
5439
		}
5440
5441
		// Get a state variable
5442
		if ( isset( $key ) && ! isset( $value ) ) {
5443
			if ( array_key_exists( $key, $state ) )
5444
				return $state[ $key ];
5445
			return null;
5446
		}
5447
5448
		// Set a state variable
5449
		if ( isset ( $key ) && isset( $value ) ) {
5450
			if( is_array( $value ) && isset( $value[0] ) ) {
5451
				$value = $value[0];
5452
			}
5453
			$state[ $key ] = $value;
5454
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5455
		}
5456
	}
5457
5458
	public static function restate() {
5459
		Jetpack::state( null, null, true );
5460
	}
5461
5462
	public static function check_privacy( $file ) {
5463
		static $is_site_publicly_accessible = null;
5464
5465
		if ( is_null( $is_site_publicly_accessible ) ) {
5466
			$is_site_publicly_accessible = false;
5467
5468
			$rpc = new Jetpack_IXR_Client();
5469
5470
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5471
			if ( $success ) {
5472
				$response = $rpc->getResponse();
5473
				if ( $response ) {
5474
					$is_site_publicly_accessible = true;
5475
				}
5476
			}
5477
5478
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5479
		}
5480
5481
		if ( $is_site_publicly_accessible ) {
5482
			return;
5483
		}
5484
5485
		$module_slug = self::get_module_slug( $file );
5486
5487
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5488
		if ( ! $privacy_checks ) {
5489
			$privacy_checks = $module_slug;
5490
		} else {
5491
			$privacy_checks .= ",$module_slug";
5492
		}
5493
5494
		Jetpack::state( 'privacy_checks', $privacy_checks );
5495
	}
5496
5497
	/**
5498
	 * Helper method for multicall XMLRPC.
5499
	 */
5500
	public static function xmlrpc_async_call() {
5501
		global $blog_id;
5502
		static $clients = array();
5503
5504
		$client_blog_id = is_multisite() ? $blog_id : 0;
5505
5506
		if ( ! isset( $clients[$client_blog_id] ) ) {
5507
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5508
			if ( function_exists( 'ignore_user_abort' ) ) {
5509
				ignore_user_abort( true );
5510
			}
5511
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5512
		}
5513
5514
		$args = func_get_args();
5515
5516
		if ( ! empty( $args[0] ) ) {
5517
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5518
		} elseif ( is_multisite() ) {
5519
			foreach ( $clients as $client_blog_id => $client ) {
5520
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5521
					continue;
5522
				}
5523
5524
				$switch_success = switch_to_blog( $client_blog_id, true );
5525
				if ( ! $switch_success ) {
5526
					continue;
5527
				}
5528
5529
				flush();
5530
				$client->query();
5531
5532
				restore_current_blog();
5533
			}
5534
		} else {
5535
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5536
				flush();
5537
				$clients[0]->query();
5538
			}
5539
		}
5540
	}
5541
5542
	public static function staticize_subdomain( $url ) {
5543
5544
		// Extract hostname from URL
5545
		$host = parse_url( $url, PHP_URL_HOST );
5546
5547
		// Explode hostname on '.'
5548
		$exploded_host = explode( '.', $host );
5549
5550
		// Retrieve the name and TLD
5551
		if ( count( $exploded_host ) > 1 ) {
5552
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5553
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5554
			// Rebuild domain excluding subdomains
5555
			$domain = $name . '.' . $tld;
5556
		} else {
5557
			$domain = $host;
5558
		}
5559
		// Array of Automattic domains
5560
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5561
5562
		// Return $url if not an Automattic domain
5563
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5564
			return $url;
5565
		}
5566
5567
		if ( is_ssl() ) {
5568
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5569
		}
5570
5571
		srand( crc32( basename( $url ) ) );
5572
		$static_counter = rand( 0, 2 );
5573
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5574
5575
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5576
	}
5577
5578
/* JSON API Authorization */
5579
5580
	/**
5581
	 * Handles the login action for Authorizing the JSON API
5582
	 */
5583
	function login_form_json_api_authorization() {
5584
		$this->verify_json_api_authorization_request();
5585
5586
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5587
5588
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5589
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5590
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5591
	}
5592
5593
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5594
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5595
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5596
			return $url;
5597
		}
5598
5599
		$parsed_url = parse_url( $url );
5600
		$url = strtok( $url, '?' );
5601
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5602
		if ( ! empty( $parsed_url['query'] ) )
5603
			$url .= "&{$parsed_url['query']}";
5604
5605
		return $url;
5606
	}
5607
5608
	// Make sure the POSTed request is handled by the same action
5609
	function preserve_action_in_login_form_for_json_api_authorization() {
5610
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5611
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5612
	}
5613
5614
	// If someone logs in to approve API access, store the Access Code in usermeta
5615
	function store_json_api_authorization_token( $user_login, $user ) {
5616
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5617
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5618
		$token = wp_generate_password( 32, false );
5619
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5620
	}
5621
5622
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5623
	function allow_wpcom_public_api_domain( $domains ) {
5624
		$domains[] = 'public-api.wordpress.com';
5625
		return $domains;
5626
	}
5627
5628
	static function is_redirect_encoded( $redirect_url ) {
5629
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5630
	}
5631
5632
	// Add all wordpress.com environments to the safe redirect whitelist
5633
	function allow_wpcom_environments( $domains ) {
5634
		$domains[] = 'wordpress.com';
5635
		$domains[] = 'wpcalypso.wordpress.com';
5636
		$domains[] = 'horizon.wordpress.com';
5637
		$domains[] = 'calypso.localhost';
5638
		return $domains;
5639
	}
5640
5641
	// Add the Access Code details to the public-api.wordpress.com redirect
5642
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5643
		return add_query_arg(
5644
			urlencode_deep(
5645
				array(
5646
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5647
					'jetpack-user-id' => (int) $user->ID,
5648
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5649
				)
5650
			),
5651
			$redirect_to
5652
		);
5653
	}
5654
5655
5656
	/**
5657
	 * Verifies the request by checking the signature
5658
	 *
5659
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5660
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5661
	 *
5662
	 * @param null|array $environment
5663
	 */
5664
	function verify_json_api_authorization_request( $environment = null ) {
5665
		$environment = is_null( $environment )
5666
			? $_REQUEST
5667
			: $environment;
5668
5669
		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...
5670
		$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...
5671
		if ( ! $token || empty( $token->secret ) ) {
5672
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5673
		}
5674
5675
		$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' );
5676
5677
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5678
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5679
			/**
5680
			 * Jetpack authorisation request Error.
5681
			 *
5682
			 * @since 7.5.0
5683
			 *
5684
			 */
5685
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5686
			$die_error = sprintf(
5687
				/* translators: %s is a URL */
5688
				__( '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' ),
5689
				'https://jetpack.com/support/double-encoding/'
5690
			);
5691
		}
5692
5693
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5694
5695
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5696
			$signature = $jetpack_signature->sign_request(
5697
				$environment['token'],
5698
				$environment['timestamp'],
5699
				$environment['nonce'],
5700
				'',
5701
				'GET',
5702
				$environment['jetpack_json_api_original_query'],
5703
				null,
5704
				true
5705
			);
5706
		} else {
5707
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5708
		}
5709
5710
		if ( ! $signature ) {
5711
			wp_die( $die_error );
5712
		} else if ( is_wp_error( $signature ) ) {
5713
			wp_die( $die_error );
5714
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5715
			if ( is_ssl() ) {
5716
				// 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
5717
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5718
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5719
					wp_die( $die_error );
5720
				}
5721
			} else {
5722
				wp_die( $die_error );
5723
			}
5724
		}
5725
5726
		$timestamp = (int) $environment['timestamp'];
5727
		$nonce     = stripslashes( (string) $environment['nonce'] );
5728
5729
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
The property connection does not seem to exist. Did you mean connection_manager?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
5730
			// De-nonce the nonce, at least for 5 minutes.
5731
			// 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)
5732
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5733
			if ( $old_nonce_time < time() - 300 ) {
5734
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5735
			}
5736
		}
5737
5738
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5739
		$data_filters = array(
5740
			'state'        => 'opaque',
5741
			'client_id'    => 'int',
5742
			'client_title' => 'string',
5743
			'client_image' => 'url',
5744
		);
5745
5746
		foreach ( $data_filters as $key => $sanitation ) {
5747
			if ( ! isset( $data->$key ) ) {
5748
				wp_die( $die_error );
5749
			}
5750
5751
			switch ( $sanitation ) {
5752
			case 'int' :
5753
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5754
				break;
5755
			case 'opaque' :
5756
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5757
				break;
5758
			case 'string' :
5759
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5760
				break;
5761
			case 'url' :
5762
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5763
				break;
5764
			}
5765
		}
5766
5767
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5768
			wp_die( $die_error );
5769
		}
5770
	}
5771
5772
	function login_message_json_api_authorization( $message ) {
5773
		return '<p class="message">' . sprintf(
5774
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5775
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5776
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5777
	}
5778
5779
	/**
5780
	 * Get $content_width, but with a <s>twist</s> filter.
5781
	 */
5782
	public static function get_content_width() {
5783
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5784
			? $GLOBALS['content_width']
5785
			: false;
5786
		/**
5787
		 * Filter the Content Width value.
5788
		 *
5789
		 * @since 2.2.3
5790
		 *
5791
		 * @param string $content_width Content Width value.
5792
		 */
5793
		return apply_filters( 'jetpack_content_width', $content_width );
5794
	}
5795
5796
	/**
5797
	 * Pings the WordPress.com Mirror Site for the specified options.
5798
	 *
5799
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5800
	 *
5801
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5802
	 */
5803
	public function get_cloud_site_options( $option_names ) {
5804
		$option_names = array_filter( (array) $option_names, 'is_string' );
5805
5806
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5807
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5808
		if ( $xml->isError() ) {
5809
			return array(
5810
				'error_code' => $xml->getErrorCode(),
5811
				'error_msg'  => $xml->getErrorMessage(),
5812
			);
5813
		}
5814
		$cloud_site_options = $xml->getResponse();
5815
5816
		return $cloud_site_options;
5817
	}
5818
5819
	/**
5820
	 * Checks if the site is currently in an identity crisis.
5821
	 *
5822
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5823
	 */
5824
	public static function check_identity_crisis() {
5825
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5826
			return false;
5827
		}
5828
5829
		return Jetpack_Options::get_option( 'sync_error_idc' );
5830
	}
5831
5832
	/**
5833
	 * Checks whether the home and siteurl specifically are whitelisted
5834
	 * Written so that we don't have re-check $key and $value params every time
5835
	 * we want to check if this site is whitelisted, for example in footer.php
5836
	 *
5837
	 * @since  3.8.0
5838
	 * @return bool True = already whitelisted False = not whitelisted
5839
	 */
5840
	public static function is_staging_site() {
5841
		$is_staging = false;
5842
5843
		$known_staging = array(
5844
			'urls' => array(
5845
				'#\.staging\.wpengine\.com$#i', // WP Engine
5846
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5847
				'#\.stage\.site$#i'             // DreamPress
5848
			),
5849
			'constants' => array(
5850
				'IS_WPE_SNAPSHOT',      // WP Engine
5851
				'KINSTA_DEV_ENV',       // Kinsta.com
5852
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5853
				'JETPACK_STAGING_MODE', // Generic
5854
			)
5855
		);
5856
		/**
5857
		 * Filters the flags of known staging sites.
5858
		 *
5859
		 * @since 3.9.0
5860
		 *
5861
		 * @param array $known_staging {
5862
		 *     An array of arrays that each are used to check if the current site is staging.
5863
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5864
		 *     @type array $constants PHP constants of known staging/developement environments.
5865
		 *  }
5866
		 */
5867
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5868
5869
		if ( isset( $known_staging['urls'] ) ) {
5870
			foreach ( $known_staging['urls'] as $url ){
5871
				if ( preg_match( $url, site_url() ) ) {
5872
					$is_staging = true;
5873
					break;
5874
				}
5875
			}
5876
		}
5877
5878
		if ( isset( $known_staging['constants'] ) ) {
5879
			foreach ( $known_staging['constants'] as $constant ) {
5880
				if ( defined( $constant ) && constant( $constant ) ) {
5881
					$is_staging = true;
5882
				}
5883
			}
5884
		}
5885
5886
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5887
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5888
			$is_staging = true;
5889
		}
5890
5891
		/**
5892
		 * Filters is_staging_site check.
5893
		 *
5894
		 * @since 3.9.0
5895
		 *
5896
		 * @param bool $is_staging If the current site is a staging site.
5897
		 */
5898
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5899
	}
5900
5901
	/**
5902
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5903
	 *
5904
	 * @since 4.4.0
5905
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5906
	 *
5907
	 * @return bool
5908
	 */
5909
	public static function validate_sync_error_idc_option() {
5910
		$is_valid = false;
5911
5912
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5913
		if ( false === $idc_allowed ) {
5914
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5915
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5916
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5917
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5918
				$transient_duration = HOUR_IN_SECONDS;
5919
			} else {
5920
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5921
				$idc_allowed = '1';
5922
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5923
			}
5924
5925
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5926
		}
5927
5928
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5929
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5930
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5931
			$local_options = self::get_sync_error_idc_option();
5932
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5933
				$is_valid = true;
5934
			}
5935
		}
5936
5937
		/**
5938
		 * Filters whether the sync_error_idc option is valid.
5939
		 *
5940
		 * @since 4.4.0
5941
		 *
5942
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5943
		 */
5944
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5945
5946
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5947
			// Since the option exists, and did not validate, delete it
5948
			Jetpack_Options::delete_option( 'sync_error_idc' );
5949
		}
5950
5951
		return $is_valid;
5952
	}
5953
5954
	/**
5955
	 * Normalizes a url by doing three things:
5956
	 *  - Strips protocol
5957
	 *  - Strips www
5958
	 *  - Adds a trailing slash
5959
	 *
5960
	 * @since 4.4.0
5961
	 * @param string $url
5962
	 * @return WP_Error|string
5963
	 */
5964
	public static function normalize_url_protocol_agnostic( $url ) {
5965
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5966
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5967
			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...
5968
		}
5969
5970
		// Strip www and protocols
5971
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5972
		return $url;
5973
	}
5974
5975
	/**
5976
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5977
	 *
5978
	 * @since 4.4.0
5979
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5980
	 *
5981
	 * @param array $response
5982
	 * @return array Array of the local urls, wpcom urls, and error code
5983
	 */
5984
	public static function get_sync_error_idc_option( $response = array() ) {
5985
		// Since the local options will hit the database directly, store the values
5986
		// in a transient to allow for autoloading and caching on subsequent views.
5987
		$local_options = get_transient( 'jetpack_idc_local' );
5988
		if ( false === $local_options ) {
5989
			$local_options = array(
5990
				'home'    => Functions::home_url(),
5991
				'siteurl' => Functions::site_url(),
5992
			);
5993
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5994
		}
5995
5996
		$options = array_merge( $local_options, $response );
5997
5998
		$returned_values = array();
5999
		foreach( $options as $key => $option ) {
6000
			if ( 'error_code' === $key ) {
6001
				$returned_values[ $key ] = $option;
6002
				continue;
6003
			}
6004
6005
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6006
				continue;
6007
			}
6008
6009
			$returned_values[ $key ] = $normalized_url;
6010
		}
6011
6012
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6013
6014
		return $returned_values;
6015
	}
6016
6017
	/**
6018
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6019
	 * If set to true, the site will be put into staging mode.
6020
	 *
6021
	 * @since 4.3.2
6022
	 * @return bool
6023
	 */
6024
	public static function sync_idc_optin() {
6025
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6026
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6027
		} else {
6028
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6029
		}
6030
6031
		/**
6032
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6033
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6034
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6035
		 *
6036
		 * @since 4.3.2
6037
		 *
6038
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6039
		 */
6040
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6041
	}
6042
6043
	/**
6044
	 * Maybe Use a .min.css stylesheet, maybe not.
6045
	 *
6046
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6047
	 */
6048
	public static function maybe_min_asset( $url, $path, $plugin ) {
6049
		// Short out on things trying to find actual paths.
6050
		if ( ! $path || empty( $plugin ) ) {
6051
			return $url;
6052
		}
6053
6054
		$path = ltrim( $path, '/' );
6055
6056
		// Strip out the abspath.
6057
		$base = dirname( plugin_basename( $plugin ) );
6058
6059
		// Short out on non-Jetpack assets.
6060
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6061
			return $url;
6062
		}
6063
6064
		// File name parsing.
6065
		$file              = "{$base}/{$path}";
6066
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6067
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6068
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6069
		$extension         = array_shift( $file_name_parts_r );
6070
6071
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6072
			// Already pointing at the minified version.
6073
			if ( 'min' === $file_name_parts_r[0] ) {
6074
				return $url;
6075
			}
6076
6077
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6078
			if ( file_exists( $min_full_path ) ) {
6079
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6080
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6081
				if ( 'css' === $extension ) {
6082
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6083
					self::$min_assets[ $key ] = $path;
6084
				}
6085
			}
6086
		}
6087
6088
		return $url;
6089
	}
6090
6091
	/**
6092
	 * If the asset is minified, let's flag .min as the suffix.
6093
	 *
6094
	 * Attached to `style_loader_src` filter.
6095
	 *
6096
	 * @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...
6097
	 * @param string $handle The registered handle of the script in question.
6098
	 * @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...
6099
	 */
6100
	public static function set_suffix_on_min( $src, $handle ) {
6101
		if ( false === strpos( $src, '.min.css' ) ) {
6102
			return $src;
6103
		}
6104
6105
		if ( ! empty( self::$min_assets ) ) {
6106
			foreach ( self::$min_assets as $file => $path ) {
6107
				if ( false !== strpos( $src, $file ) ) {
6108
					wp_style_add_data( $handle, 'suffix', '.min' );
6109
					return $src;
6110
				}
6111
			}
6112
		}
6113
6114
		return $src;
6115
	}
6116
6117
	/**
6118
	 * Maybe inlines a stylesheet.
6119
	 *
6120
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6121
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6122
	 *
6123
	 * Attached to `style_loader_tag` filter.
6124
	 *
6125
	 * @param string $tag The tag that would link to the external asset.
6126
	 * @param string $handle The registered handle of the script in question.
6127
	 *
6128
	 * @return string
6129
	 */
6130
	public static function maybe_inline_style( $tag, $handle ) {
6131
		global $wp_styles;
6132
		$item = $wp_styles->registered[ $handle ];
6133
6134
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6135
			return $tag;
6136
		}
6137
6138
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6139
			$href = $matches[1];
6140
			// Strip off query string
6141
			if ( $pos = strpos( $href, '?' ) ) {
6142
				$href = substr( $href, 0, $pos );
6143
			}
6144
			// Strip off fragment
6145
			if ( $pos = strpos( $href, '#' ) ) {
6146
				$href = substr( $href, 0, $pos );
6147
			}
6148
		} else {
6149
			return $tag;
6150
		}
6151
6152
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6153
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6154
			return $tag;
6155
		}
6156
6157
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6158
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6159
			// And this isn't the pass that actually deals with the RTL version...
6160
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6161
				// Short out, as the RTL version will deal with it in a moment.
6162
				return $tag;
6163
			}
6164
		}
6165
6166
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6167
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6168
		if ( $css ) {
6169
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6170
			if ( empty( $item->extra['after'] ) ) {
6171
				wp_add_inline_style( $handle, $css );
6172
			} else {
6173
				array_unshift( $item->extra['after'], $css );
6174
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6175
			}
6176
		}
6177
6178
		return $tag;
6179
	}
6180
6181
	/**
6182
	 * Loads a view file from the views
6183
	 *
6184
	 * Data passed in with the $data parameter will be available in the
6185
	 * template file as $data['value']
6186
	 *
6187
	 * @param string $template - Template file to load
6188
	 * @param array $data - Any data to pass along to the template
6189
	 * @return boolean - If template file was found
6190
	 **/
6191
	public function load_view( $template, $data = array() ) {
6192
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6193
6194
		if( file_exists( $views_dir . $template ) ) {
6195
			require_once( $views_dir . $template );
6196
			return true;
6197
		}
6198
6199
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6200
		return false;
6201
	}
6202
6203
	/**
6204
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6205
	 */
6206
	public function deprecated_hooks() {
6207
		global $wp_filter;
6208
6209
		/*
6210
		 * Format:
6211
		 * deprecated_filter_name => replacement_name
6212
		 *
6213
		 * If there is no replacement, use null for replacement_name
6214
		 */
6215
		$deprecated_list = array(
6216
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6217
			'wpl_sharing_2014_1'                                     => null,
6218
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6219
			'jetpack_identity_crisis_options_to_check'               => null,
6220
			'update_option_jetpack_single_user_site'                 => null,
6221
			'audio_player_default_colors'                            => null,
6222
			'add_option_jetpack_featured_images_enabled'             => null,
6223
			'add_option_jetpack_update_details'                      => null,
6224
			'add_option_jetpack_updates'                             => null,
6225
			'add_option_jetpack_network_name'                        => null,
6226
			'add_option_jetpack_network_allow_new_registrations'     => null,
6227
			'add_option_jetpack_network_add_new_users'               => null,
6228
			'add_option_jetpack_network_site_upload_space'           => null,
6229
			'add_option_jetpack_network_upload_file_types'           => null,
6230
			'add_option_jetpack_network_enable_administration_menus' => null,
6231
			'add_option_jetpack_is_multi_site'                       => null,
6232
			'add_option_jetpack_is_main_network'                     => null,
6233
			'add_option_jetpack_main_network_site'                   => null,
6234
			'jetpack_sync_all_registered_options'                    => null,
6235
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6236
			'jetpack_is_post_mailable'                               => null,
6237
			'jetpack_seo_site_host'                                  => null,
6238
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6239
			'jetpack_holiday_snow_option_name'                       => null,
6240
			'jetpack_holiday_chance_of_snow'                         => null,
6241
			'jetpack_holiday_snow_js_url'                            => null,
6242
			'jetpack_is_holiday_snow_season'                         => null,
6243
			'jetpack_holiday_snow_option_updated'                    => null,
6244
			'jetpack_holiday_snowing'                                => null,
6245
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6246
			'jetpack_cache_plans'                                    => null,
6247
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6248
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6249
			'jetpack_enable_site_verification'                       => null,
6250
			'can_display_jetpack_manage_notice'                      => null,
6251
			// Removed in Jetpack 7.3.0
6252
			'atd_load_scripts'                                       => null,
6253
			'atd_http_post_timeout'                                  => null,
6254
			'atd_http_post_error'                                    => null,
6255
			'atd_service_domain'                                     => null,
6256
			'jetpack_widget_authors_exclude'                         => 'jetpack_widget_authors_params',
6257
		);
6258
6259
		// This is a silly loop depth. Better way?
6260
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6261
			if ( has_action( $hook ) ) {
6262
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6263
					foreach( $values AS $hooked ) {
6264
						if ( is_callable( $hooked['function'] ) ) {
6265
							$function_name = 'an anonymous function';
6266
						} else {
6267
							$function_name = $hooked['function'];
6268
						}
6269
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6270
					}
6271
				}
6272
			}
6273
		}
6274
	}
6275
6276
	/**
6277
	 * Converts any url in a stylesheet, to the correct absolute url.
6278
	 *
6279
	 * Considerations:
6280
	 *  - Normal, relative URLs     `feh.png`
6281
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6282
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6283
	 *  - Absolute URLs             `http://domain.com/feh.png`
6284
	 *  - Domain root relative URLs `/feh.png`
6285
	 *
6286
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6287
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6288
	 *
6289
	 * @return mixed|string
6290
	 */
6291
	public static function absolutize_css_urls( $css, $css_file_url ) {
6292
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6293
		$css_dir = dirname( $css_file_url );
6294
		$p       = parse_url( $css_dir );
6295
		$domain  = sprintf(
6296
					'%1$s//%2$s%3$s%4$s',
6297
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6298
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6299
					$p['host'],
6300
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6301
				);
6302
6303
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6304
			$find = $replace = array();
6305
			foreach ( $matches as $match ) {
6306
				$url = trim( $match['path'], "'\" \t" );
6307
6308
				// If this is a data url, we don't want to mess with it.
6309
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6310
					continue;
6311
				}
6312
6313
				// If this is an absolute or protocol-agnostic url,
6314
				// we don't want to mess with it.
6315
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6316
					continue;
6317
				}
6318
6319
				switch ( substr( $url, 0, 1 ) ) {
6320
					case '/':
6321
						$absolute = $domain . $url;
6322
						break;
6323
					default:
6324
						$absolute = $css_dir . '/' . $url;
6325
				}
6326
6327
				$find[]    = $match[0];
6328
				$replace[] = sprintf( 'url("%s")', $absolute );
6329
			}
6330
			$css = str_replace( $find, $replace, $css );
6331
		}
6332
6333
		return $css;
6334
	}
6335
6336
	/**
6337
	 * This methods removes all of the registered css files on the front end
6338
	 * from Jetpack in favor of using a single file. In effect "imploding"
6339
	 * all the files into one file.
6340
	 *
6341
	 * Pros:
6342
	 * - Uses only ONE css asset connection instead of 15
6343
	 * - Saves a minimum of 56k
6344
	 * - Reduces server load
6345
	 * - Reduces time to first painted byte
6346
	 *
6347
	 * Cons:
6348
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6349
	 *		should not cause any issues with themes.
6350
	 * - Plugins/themes dequeuing styles no longer do anything. See
6351
	 *		jetpack_implode_frontend_css filter for a workaround
6352
	 *
6353
	 * For some situations developers may wish to disable css imploding and
6354
	 * instead operate in legacy mode where each file loads seperately and
6355
	 * can be edited individually or dequeued. This can be accomplished with
6356
	 * the following line:
6357
	 *
6358
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6359
	 *
6360
	 * @since 3.2
6361
	 **/
6362
	public function implode_frontend_css( $travis_test = false ) {
6363
		$do_implode = true;
6364
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6365
			$do_implode = false;
6366
		}
6367
6368
		// Do not implode CSS when the page loads via the AMP plugin.
6369
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6370
			$do_implode = false;
6371
		}
6372
6373
		/**
6374
		 * Allow CSS to be concatenated into a single jetpack.css file.
6375
		 *
6376
		 * @since 3.2.0
6377
		 *
6378
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6379
		 */
6380
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6381
6382
		// Do not use the imploded file when default behavior was altered through the filter
6383
		if ( ! $do_implode ) {
6384
			return;
6385
		}
6386
6387
		// We do not want to use the imploded file in dev mode, or if not connected
6388
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6389
			if ( ! $travis_test ) {
6390
				return;
6391
			}
6392
		}
6393
6394
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6395
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6396
			return;
6397
		}
6398
6399
		/*
6400
		 * Now we assume Jetpack is connected and able to serve the single
6401
		 * file.
6402
		 *
6403
		 * In the future there will be a check here to serve the file locally
6404
		 * or potentially from the Jetpack CDN
6405
		 *
6406
		 * For now:
6407
		 * - Enqueue a single imploded css file
6408
		 * - Zero out the style_loader_tag for the bundled ones
6409
		 * - Be happy, drink scotch
6410
		 */
6411
6412
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6413
6414
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6415
6416
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6417
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6418
	}
6419
6420
	function concat_remove_style_loader_tag( $tag, $handle ) {
6421
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6422
			$tag = '';
6423
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6424
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6425
			}
6426
		}
6427
6428
		return $tag;
6429
	}
6430
6431
	/**
6432
	 * Add an async attribute to scripts that can be loaded asynchronously.
6433
	 * https://www.w3schools.com/tags/att_script_async.asp
6434
	 *
6435
	 * @since 7.7.0
6436
	 *
6437
	 * @param string $tag    The <script> tag for the enqueued script.
6438
	 * @param string $handle The script's registered handle.
6439
	 * @param string $src    The script's source URL.
6440
	 */
6441
	public function script_add_async( $tag, $handle, $src ) {
6442
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6443
			return preg_replace( '/^<script /i', '<script async ', $tag );
6444
		}
6445
6446
		return $tag;
6447
	}
6448
6449
	/*
6450
	 * Check the heartbeat data
6451
	 *
6452
	 * Organizes the heartbeat data by severity.  For example, if the site
6453
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6454
	 *
6455
	 * Data will be added to "caution" array, if it either:
6456
	 *  - Out of date Jetpack version
6457
	 *  - Out of date WP version
6458
	 *  - Out of date PHP version
6459
	 *
6460
	 * $return array $filtered_data
6461
	 */
6462
	public static function jetpack_check_heartbeat_data() {
6463
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6464
6465
		$good    = array();
6466
		$caution = array();
6467
		$bad     = array();
6468
6469
		foreach ( $raw_data as $stat => $value ) {
6470
6471
			// Check jetpack version
6472
			if ( 'version' == $stat ) {
6473
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6474
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6475
					continue;
6476
				}
6477
			}
6478
6479
			// Check WP version
6480
			if ( 'wp-version' == $stat ) {
6481
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6482
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6483
					continue;
6484
				}
6485
			}
6486
6487
			// Check PHP version
6488
			if ( 'php-version' == $stat ) {
6489
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6490
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6491
					continue;
6492
				}
6493
			}
6494
6495
			// Check ID crisis
6496
			if ( 'identitycrisis' == $stat ) {
6497
				if ( 'yes' == $value ) {
6498
					$bad[ $stat ] = $value;
6499
					continue;
6500
				}
6501
			}
6502
6503
			// The rest are good :)
6504
			$good[ $stat ] = $value;
6505
		}
6506
6507
		$filtered_data = array(
6508
			'good'    => $good,
6509
			'caution' => $caution,
6510
			'bad'     => $bad
6511
		);
6512
6513
		return $filtered_data;
6514
	}
6515
6516
6517
	/*
6518
	 * This method is used to organize all options that can be reset
6519
	 * without disconnecting Jetpack.
6520
	 *
6521
	 * It is used in class.jetpack-cli.php to reset options
6522
	 *
6523
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6524
	 *
6525
	 * @return array of options to delete.
6526
	 */
6527
	public static function get_jetpack_options_for_reset() {
6528
		return Jetpack_Options::get_options_for_reset();
6529
	}
6530
6531
	/*
6532
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6533
	 * so we can bring them directly to their site in calypso.
6534
	 *
6535
	 * @param string | url
6536
	 * @return string | url without the guff
6537
	 */
6538
	public static function build_raw_urls( $url ) {
6539
		$strip_http = '/.*?:\/\//i';
6540
		$url = preg_replace( $strip_http, '', $url  );
6541
		$url = str_replace( '/', '::', $url );
6542
		return $url;
6543
	}
6544
6545
	/**
6546
	 * Stores and prints out domains to prefetch for page speed optimization.
6547
	 *
6548
	 * @param mixed $new_urls
6549
	 */
6550
	public static function dns_prefetch( $new_urls = null ) {
6551
		static $prefetch_urls = array();
6552
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6553
			echo "\r\n";
6554
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6555
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6556
			}
6557
		} elseif ( ! empty( $new_urls ) ) {
6558
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6559
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6560
			}
6561
			foreach ( (array) $new_urls as $this_new_url ) {
6562
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6563
			}
6564
			$prefetch_urls = array_unique( $prefetch_urls );
6565
		}
6566
	}
6567
6568
	public function wp_dashboard_setup() {
6569
		if ( self::is_active() ) {
6570
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6571
		}
6572
6573
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6574
			$jetpack_logo = new Jetpack_Logo();
6575
			$widget_title = sprintf(
6576
				wp_kses(
6577
					/* translators: Placeholder is a Jetpack logo. */
6578
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6579
					array( 'span' => array() )
6580
				),
6581
				$jetpack_logo->get_jp_emblem( true )
6582
			);
6583
6584
			wp_add_dashboard_widget(
6585
				'jetpack_summary_widget',
6586
				$widget_title,
6587
				array( __CLASS__, 'dashboard_widget' )
6588
			);
6589
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6590
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6591
6592
			// If we're inactive and not in development mode, sort our box to the top.
6593
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6594
				global $wp_meta_boxes;
6595
6596
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6597
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6598
6599
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6600
			}
6601
		}
6602
	}
6603
6604
	/**
6605
	 * @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...
6606
	 * @return mixed
6607
	 */
6608
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6609
		if ( ! is_array( $sorted ) ) {
6610
			return $sorted;
6611
		}
6612
6613
		foreach ( $sorted as $box_context => $ids ) {
6614
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6615
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6616
				continue;
6617
			}
6618
6619
			$ids_array = explode( ',', $ids );
6620
			$key = array_search( 'dashboard_stats', $ids_array );
6621
6622
			if ( false !== $key ) {
6623
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6624
				$ids_array[ $key ] = 'jetpack_summary_widget';
6625
				$sorted[ $box_context ] = implode( ',', $ids_array );
6626
				// We've found it, stop searching, and just return.
6627
				break;
6628
			}
6629
		}
6630
6631
		return $sorted;
6632
	}
6633
6634
	public static function dashboard_widget() {
6635
		/**
6636
		 * Fires when the dashboard is loaded.
6637
		 *
6638
		 * @since 3.4.0
6639
		 */
6640
		do_action( 'jetpack_dashboard_widget' );
6641
	}
6642
6643
	public static function dashboard_widget_footer() {
6644
		?>
6645
		<footer>
6646
6647
		<div class="protect">
6648
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6649
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6650
				<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>
6651
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6652
				<a href="<?php echo esc_url( wp_nonce_url( Jetpack::admin_url( array( 'action' => 'activate', 'module' => 'protect' ) ), 'jetpack_activate-protect' ) ); ?>" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6653
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6654
				</a>
6655
			<?php else : ?>
6656
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6657
			<?php endif; ?>
6658
		</div>
6659
6660
		<div class="akismet">
6661
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6662
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6663
				<p><?php echo esc_html_x( 'Spam comments blocked by Akismet.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
6664
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6665
				<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'activate', 'plugin' => 'akismet/akismet.php' ), admin_url( 'plugins.php' ) ), 'activate-plugin_akismet/akismet.php' ) ); ?>" class="button button-jetpack">
6666
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6667
				</a>
6668
			<?php else : ?>
6669
				<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( 'Akismet can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
6670
			<?php endif; ?>
6671
		</div>
6672
6673
		</footer>
6674
		<?php
6675
	}
6676
6677
	/*
6678
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6679
	 */
6680
	function jetpack_icon_user_connected( $columns ) {
6681
		$columns['user_jetpack'] = '';
6682
		return $columns;
6683
	}
6684
6685
	/*
6686
	 * Show Jetpack icon if the user is linked.
6687
	 */
6688
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6689
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6690
			$jetpack_logo = new Jetpack_Logo();
6691
			$emblem_html = sprintf(
6692
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6693
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6694
				$jetpack_logo->get_jp_emblem()
6695
			);
6696
			return $emblem_html;
6697
		}
6698
6699
		return $val;
6700
	}
6701
6702
	/*
6703
	 * Style the Jetpack user column
6704
	 */
6705
	function jetpack_user_col_style() {
6706
		global $current_screen;
6707
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6708
			<style>
6709
				.fixed .column-user_jetpack {
6710
					width: 21px;
6711
				}
6712
				.jp-emblem-user-admin svg {
6713
					width: 20px;
6714
					height: 20px;
6715
				}
6716
				.jp-emblem-user-admin path {
6717
					fill: #00BE28;
6718
				}
6719
			</style>
6720
		<?php }
6721
	}
6722
6723
	/**
6724
	 * Checks if Akismet is active and working.
6725
	 *
6726
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6727
	 * that implied usage of methods present since more recent version.
6728
	 * See https://github.com/Automattic/jetpack/pull/9585
6729
	 *
6730
	 * @since  5.1.0
6731
	 *
6732
	 * @return bool True = Akismet available. False = Aksimet not available.
6733
	 */
6734
	public static function is_akismet_active() {
6735
		static $status = null;
6736
6737
		if ( ! is_null( $status ) ) {
6738
			return $status;
6739
		}
6740
6741
		// Check if a modern version of Akismet is active.
6742
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6743
			$status = false;
6744
			return $status;
6745
		}
6746
6747
		// Make sure there is a key known to Akismet at all before verifying key.
6748
		$akismet_key = Akismet::get_api_key();
6749
		if ( ! $akismet_key ) {
6750
			$status = false;
6751
			return $status;
6752
		}
6753
6754
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6755
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6756
6757
		// 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.
6758
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6759
		// We cache the result of the Akismet key verification for ten minutes.
6760
		if ( ! $akismet_key_state || $recheck ) {
6761
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6762
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6763
		}
6764
6765
		$status = 'valid' === $akismet_key_state;
6766
6767
		return $status;
6768
	}
6769
6770
	/**
6771
	 * @deprecated
6772
	 *
6773
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6774
	 */
6775
	public static function is_function_in_backtrace() {
6776
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6777
	}
6778
6779
	/**
6780
	 * Given a minified path, and a non-minified path, will return
6781
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6782
	 *
6783
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6784
	 * root Jetpack directory.
6785
	 *
6786
	 * @since 5.6.0
6787
	 *
6788
	 * @param string $min_path
6789
	 * @param string $non_min_path
6790
	 * @return string The URL to the file
6791
	 */
6792
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6793
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6794
	}
6795
6796
	/**
6797
	 * Checks for whether Jetpack Backup & Scan is enabled.
6798
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6799
	 * @return bool|int|mixed
6800
	 */
6801
	public static function is_rewind_enabled() {
6802
		if ( ! Jetpack::is_active() ) {
6803
			return false;
6804
		}
6805
6806
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6807
		if ( false === $rewind_enabled ) {
6808
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6809
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6810
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6811
				&& ! empty( $rewind_data['state'] )
6812
				&& 'active' === $rewind_data['state'] )
6813
				? 1
6814
				: 0;
6815
6816
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6817
		}
6818
		return $rewind_enabled;
6819
	}
6820
6821
	/**
6822
	 * Return Calypso environment value; used for developing Jetpack and pairing
6823
	 * it with different Calypso enrionments, such as localhost.
6824
	 *
6825
	 * @since 7.4.0
6826
	 *
6827
	 * @return string Calypso environment
6828
	 */
6829
	public static function get_calypso_env() {
6830
		if ( isset( $_GET['calypso_env'] ) ) {
6831
			return sanitize_key( $_GET['calypso_env'] );
6832
		}
6833
6834
		if ( getenv( 'CALYPSO_ENV' ) ) {
6835
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6836
		}
6837
6838
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6839
			return sanitize_key( CALYPSO_ENV );
6840
		}
6841
6842
		return '';
6843
	}
6844
6845
	/**
6846
	 * Checks whether or not TOS has been agreed upon.
6847
	 * Will return true if a user has clicked to register, or is already connected.
6848
	 */
6849
	public static function jetpack_tos_agreed() {
6850
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6851
	}
6852
6853
	/**
6854
	 * Handles activating default modules as well general cleanup for the new connection.
6855
	 *
6856
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6857
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6858
	 * @param boolean $send_state_messages          Whether to send state messages.
6859
	 * @return void
6860
	 */
6861
	public static function handle_post_authorization_actions(
6862
		$activate_sso = false,
6863
		$redirect_on_activation_error = false,
6864
		$send_state_messages = true
6865
	) {
6866
		$other_modules = $activate_sso
6867
			? array( 'sso' )
6868
			: array();
6869
6870
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6871
			Jetpack::delete_active_modules();
6872
6873
			Jetpack::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...
6874
		} else {
6875
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6876
		}
6877
6878
		// Since this is a fresh connection, be sure to clear out IDC options
6879
		Jetpack_IDC::clear_all_idc_options();
6880
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6881
6882
		// Start nonce cleaner
6883
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6884
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6885
6886
		if ( $send_state_messages ) {
6887
			Jetpack::state( 'message', 'authorized' );
6888
		}
6889
	}
6890
6891
	/**
6892
	 * Returns a boolean for whether backups UI should be displayed or not.
6893
	 *
6894
	 * @return bool Should backups UI be displayed?
6895
	 */
6896
	public static function show_backups_ui() {
6897
		/**
6898
		 * Whether UI for backups should be displayed.
6899
		 *
6900
		 * @since 6.5.0
6901
		 *
6902
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6903
		 */
6904
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6905
	}
6906
6907
	/*
6908
	 * Deprecated manage functions
6909
	 */
6910
	function prepare_manage_jetpack_notice() {
6911
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6912
	}
6913
	function manage_activate_screen() {
6914
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6915
	}
6916
	function admin_jetpack_manage_notice() {
6917
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6918
	}
6919
	function opt_out_jetpack_manage_url() {
6920
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6921
	}
6922
	function opt_in_jetpack_manage_url() {
6923
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6924
	}
6925
	function opt_in_jetpack_manage_notice() {
6926
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6927
	}
6928
	function can_display_jetpack_manage_notice() {
6929
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6930
	}
6931
6932
	/**
6933
	 * Clean leftoveruser meta.
6934
	 *
6935
	 * Delete Jetpack-related user meta when it is no longer needed.
6936
	 *
6937
	 * @since 7.3.0
6938
	 *
6939
	 * @param int $user_id User ID being updated.
6940
	 */
6941
	public static function user_meta_cleanup( $user_id ) {
6942
		$meta_keys = array(
6943
			// AtD removed from Jetpack 7.3
6944
			'AtD_options',
6945
			'AtD_check_when',
6946
			'AtD_guess_lang',
6947
			'AtD_ignored_phrases',
6948
		);
6949
6950
		foreach ( $meta_keys as $meta_key ) {
6951
			if ( get_user_meta( $user_id, $meta_key ) ) {
6952
				delete_user_meta( $user_id, $meta_key );
6953
			}
6954
		}
6955
	}
6956
6957
	function is_active_and_not_development_mode( $maybe ) {
6958
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6959
			return false;
6960
		}
6961
		return true;
6962
	}
6963
}
6964