Completed
Push — fix/upgrade-redirects ( f98297 )
by
unknown
06:27
created

class.jetpack.php (61 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
		'comment-likes' => array(
159
			'Epoch'                                => 'epoch/plugincore.php',
160
		),
161
		'contact-form'      => array(
162
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
163
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
164
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
165
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
166
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
167
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
168
		),
169
		'minileven'         => array(
170
			'WPtouch'                              => 'wptouch/wptouch.php',
171
		),
172
		'latex'             => array(
173
			'LaTeX for WordPress'                  => 'latex/latex.php',
174
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
175
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
176
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
177
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
178
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
179
		),
180
		'protect'           => array(
181
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
182
			'Captcha'                              => 'captcha/captcha.php',
183
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
184
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
185
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
186
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
187
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
188
			'Security-protection'                  => 'security-protection/security-protection.php',
189
			'Login Security'                       => 'login-security/login-security.php',
190
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
191
			'Wordfence Security'                   => 'wordfence/wordfence.php',
192
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
193
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
194
		),
195
		'random-redirect'   => array(
196
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
197
		),
198
		'related-posts'     => array(
199
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
200
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
201
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
202
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
203
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
204
			'outbrain'                             => 'outbrain/outbrain.php',
205
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
206
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
207
		),
208
		'sharedaddy'        => array(
209
			'AddThis'                              => 'addthis/addthis_social_widget.php',
210
			'Add To Any'                           => 'add-to-any/add-to-any.php',
211
			'ShareThis'                            => 'share-this/sharethis.php',
212
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
213
		),
214
		'seo-tools' => array(
215
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'                    => 'autodescription/autodescription.php',
220
		),
221
		'verification-tools' => array(
222
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
223
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
224
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
225
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
226
			'The SEO Framework'                    => 'autodescription/autodescription.php',
227
		),
228
		'widget-visibility' => array(
229
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
230
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
231
		),
232
		'sitemaps' => array(
233
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
234
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
235
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
236
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
237
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
238
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
239
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
240
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242
			'The SEO Framework'                    => 'autodescription/autodescription.php',
243
			'Sitemap'                              => 'sitemap/sitemap.php',
244
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
245
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
246
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
247
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
248
		),
249
		'lazy-images' => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		                                                         // 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		                                                         // Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		                                                         // Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		                                                         // Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		                                                         // Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		                                                         // NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		                                                         // Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		                                                         // Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		                                                         // WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
	//	'twitter/twitter.php',                       // The official one handles this on its own.
321
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 * @var string
342
	 */
343
	public $error = '';
344
345
	/**
346
	 * Modules that need more privacy description.
347
	 * @var string
348
	 */
349
	public $privacy_checks = '';
350
351
	/**
352
	 * Stats to record once the page loads
353
	 *
354
	 * @var array
355
	 */
356
	public $stats = array();
357
358
	/**
359
	 * Jetpack_Sync object
360
	 */
361
	public $sync;
362
363
	/**
364
	 * Verified data for JSON authorization request
365
	 */
366
	public $json_api_authorization_request = array();
367
368
	/**
369
	 * @var \Automattic\Jetpack\Connection\Manager
370
	 */
371
	protected $connection_manager;
372
373
	/**
374
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
375
	 */
376
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
377
378
	/**
379
	 * Holds the singleton instance of this class
380
	 * @since 2.3.3
381
	 * @var Jetpack
382
	 */
383
	static $instance = false;
384
385
	/**
386
	 * Singleton
387
	 * @static
388
	 */
389
	public static function init() {
390
		if ( ! self::$instance ) {
391
			self::$instance = new Jetpack;
392
393
			self::$instance->plugin_upgrade();
394
		}
395
396
		return self::$instance;
397
	}
398
399
	/**
400
	 * Must never be called statically
401
	 */
402
	function plugin_upgrade() {
403
		if ( Jetpack::is_active() ) {
404
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
405
			if ( JETPACK__VERSION != $version ) {
406
				// Prevent multiple upgrades at once - only a single process should trigger
407
				// an upgrade to avoid stampedes
408
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
409
					return;
410
				}
411
412
				// Set a short lock to prevent multiple instances of the upgrade
413
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
414
415
				// check which active modules actually exist and remove others from active_modules list
416
				$unfiltered_modules = Jetpack::get_active_modules();
417
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
418
				if ( array_diff( $unfiltered_modules, $modules ) ) {
419
					Jetpack::update_active_modules( $modules );
420
				}
421
422
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
423
424
				// Upgrade to 4.3.0
425
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
426
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
427
				}
428
429
				// Make sure Markdown for posts gets turned back on
430
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
431
					update_option( 'wpcom_publish_posts_with_markdown', true );
432
				}
433
434
				if ( did_action( 'wp_loaded' ) ) {
435
					self::upgrade_on_load();
436
				} else {
437
					add_action(
438
						'wp_loaded',
439
						array( __CLASS__, 'upgrade_on_load' )
440
					);
441
				}
442
			}
443
		}
444
	}
445
446
	/**
447
	 * Runs upgrade routines that need to have modules loaded.
448
	 */
449
	static function upgrade_on_load() {
450
451
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
452
		// This can happen in case Jetpack has been just upgraded and is
453
		// being initialized late during the page load. In this case we wait
454
		// until the next proper admin page load with Jetpack active.
455
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
456
			delete_transient( self::$plugin_upgrade_lock_key );
457
458
			return;
459
		}
460
461
		Jetpack::maybe_set_version_option();
462
463
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
464
			Jetpack_Widget_Conditions::migrate_post_type_rules();
465
		}
466
467
		if (
468
			class_exists( 'Jetpack_Sitemap_Manager' )
469
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
470
		) {
471
			do_action( 'jetpack_sitemaps_purge_data' );
472
		}
473
474
		// Delete old stats cache
475
		delete_option( 'jetpack_restapi_stats_cache' );
476
477
		delete_transient( self::$plugin_upgrade_lock_key );
478
	}
479
480
	/**
481
	 * Saves all the currently active modules to options.
482
	 * Also fires Action hooks for each newly activated and deactivated module.
483
	 *
484
	 * @param $modules Array Array of active modules to be saved in options.
485
	 *
486
	 * @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...
487
	 */
488
	static function update_active_modules( $modules ) {
489
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
490
		$active_modules       = Jetpack::get_active_modules();
491
		$new_active_modules   = array_diff( $modules, $current_modules );
492
		$new_inactive_modules = array_diff( $active_modules, $modules );
493
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
494
		$reindexed_modules    = array_values( $new_current_modules );
495
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
496
497
		foreach ( $new_active_modules as $module ) {
498
			/**
499
			 * Fires when a specific module is activated.
500
			 *
501
			 * @since 1.9.0
502
			 *
503
			 * @param string $module Module slug.
504
			 * @param boolean $success whether the module was activated. @since 4.2
505
			 */
506
			do_action( 'jetpack_activate_module', $module, $success );
507
			/**
508
			 * Fires when a module is activated.
509
			 * The dynamic part of the filter, $module, is the module slug.
510
			 *
511
			 * @since 1.9.0
512
			 *
513
			 * @param string $module Module slug.
514
			 */
515
			do_action( "jetpack_activate_module_$module", $module );
516
		}
517
518
		foreach ( $new_inactive_modules as $module ) {
519
			/**
520
			 * Fired after a module has been deactivated.
521
			 *
522
			 * @since 4.2.0
523
			 *
524
			 * @param string $module Module slug.
525
			 * @param boolean $success whether the module was deactivated.
526
			 */
527
			do_action( 'jetpack_deactivate_module', $module, $success );
528
			/**
529
			 * Fires when a module is deactivated.
530
			 * The dynamic part of the filter, $module, is the module slug.
531
			 *
532
			 * @since 1.9.0
533
			 *
534
			 * @param string $module Module slug.
535
			 */
536
			do_action( "jetpack_deactivate_module_$module", $module );
537
		}
538
539
		return $success;
540
	}
541
542
	static function delete_active_modules() {
543
		self::update_active_modules( array() );
544
	}
545
546
	/**
547
	 * Constructor.  Initializes WordPress hooks
548
	 */
549
	private function __construct() {
550
		/*
551
		 * Check for and alert any deprecated hooks
552
		 */
553
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
554
555
		/*
556
		 * Enable enhanced handling of previewing sites in Calypso
557
		 */
558
		if ( Jetpack::is_active() ) {
559
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
560
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
561
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
562
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
563
		}
564
565
		if ( self::jetpack_tos_agreed() ) {
566
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
567
			add_action( 'init', array( $tracking, 'init' ) );
568
		}
569
570
571
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
572
			return function() {
573
				return wp_generate_password( 32, false );
574
			};
575
		} );
576
577
		$this->connection_manager = new Connection_Manager();
578
		$this->connection_manager->init();
579
580
		/*
581
		 * Load things that should only be in Network Admin.
582
		 *
583
		 * For now blow away everything else until a more full
584
		 * understanding of what is needed at the network level is
585
		 * available
586
		 */
587
		if ( is_multisite() ) {
588
			$network = Jetpack_Network::init();
589
			$network->set_connection( $this->connection_manager );
590
		}
591
592
		add_filter(
593
			'jetpack_signature_check_token',
594
			array( __CLASS__, 'verify_onboarding_token' ),
595
			10,
596
			3
597
		);
598
599
		/**
600
		 * Prepare Gutenberg Editor functionality
601
		 */
602
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
603
		Jetpack_Gutenberg::init();
604
		Jetpack_Gutenberg::load_independent_blocks();
605
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
606
607
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
608
609
		// Unlink user before deleting the user from WP.com.
610
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
611
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
612
613
		// Initialize remote file upload request handlers.
614
		$this->add_remote_request_handlers();
615
616
		if ( Jetpack::is_active() ) {
617
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
618
619
			Jetpack_Heartbeat::init();
620
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
621
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
622
				Jetpack_Search_Performance_Logger::init();
623
			}
624
		}
625
626
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
627
628
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
629
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
630
631
		add_action( 'admin_init', array( $this, 'admin_init' ) );
632
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
633
634
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
635
636
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
637
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
638
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
639
640
		// returns HTTPS support status
641
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
642
643
		// JITM AJAX callback function
644
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
645
646
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
647
648
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
649
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
650
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
651
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
652
653
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
654
655
		/**
656
		 * These actions run checks to load additional files.
657
		 * They check for external files or plugins, so they need to run as late as possible.
658
		 */
659
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
660
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
661
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
662
663
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
664
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
665
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
666
667
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
668
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
669
670
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
671
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
672
673
		// A filter to control all just in time messages
674
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
675
676
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
677
678
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
679
		// We should make sure to only do this for front end links.
680
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
681
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
682
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
683
684
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
685
			//so they point moderation links on emails to Calypso
686
			jetpack_require_lib( 'functions.wp-notify' );
687
		}
688
689
		// Hide edit post link if mobile app.
690
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
691
			add_filter( 'edit_post_link', '__return_empty_string' );
692
		}
693
694
		// Update the Jetpack plan from API on heartbeats
695
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
696
697
		/**
698
		 * This is the hack to concatenate all css files into one.
699
		 * For description and reasoning see the implode_frontend_css method
700
		 *
701
		 * Super late priority so we catch all the registered styles
702
		 */
703
		if( !is_admin() ) {
704
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
705
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
706
		}
707
708
709
		/**
710
		 * These are sync actions that we need to keep track of for jitms
711
		 */
712
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
713
714
		// Actually push the stats on shutdown.
715
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
716
			add_action( 'shutdown', array( $this, 'push_stats' ) );
717
		}
718
719
		/*
720
		 * Load some scripts asynchronously.
721
		 */
722
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
723
	}
724
725
	/**
726
	 * Sets up the XMLRPC request handlers.
727
	 *
728
	 * @deprecated since 7.7.0
729
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
730
	 *
731
	 * @param Array                 $request_params Incoming request parameters.
732
	 * @param Boolean               $is_active      Whether the connection is currently active.
733
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
734
	 * @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...
735
	 */
736
	public function setup_xmlrpc_handlers(
737
		$request_params,
738
		$is_active,
739
		$is_signed,
740
		Jetpack_XMLRPC_Server $xmlrpc_server = null
741
	) {
742
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
743
		return $this->connection_manager->setup_xmlrpc_handlers(
744
			$request_params,
745
			$is_active,
746
			$is_signed,
747
			$xmlrpc_server
748
		);
749
	}
750
751
	/**
752
	 * Initialize REST API registration connector.
753
	 *
754
	 * @deprecated since 7.7.0
755
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
756
	 */
757
	public function initialize_rest_api_registration_connector() {
758
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
759
		$this->connection_manager->initialize_rest_api_registration_connector();
760
	}
761
762
	/**
763
	 * This is ported over from the manage module, which has been deprecated and baked in here.
764
	 *
765
	 * @param $domains
766
	 */
767
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
768
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
769
	}
770
771
	/**
772
	 * Return $domains, with 'wordpress.com' appended.
773
	 * This is ported over from the manage module, which has been deprecated and baked in here.
774
	 *
775
	 * @param $domains
776
	 * @return array
777
	 */
778
	function allow_wpcom_domain( $domains ) {
779
		if ( empty( $domains ) ) {
780
			$domains = array();
781
		}
782
		$domains[] = 'wordpress.com';
783
		return array_unique( $domains );
784
	}
785
786
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
787
		$post = get_post( $post_id );
788
789
		if ( empty( $post ) ) {
790
			return $default_url;
791
		}
792
793
		$post_type = $post->post_type;
794
795
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
796
		// https://en.support.wordpress.com/custom-post-types/
797
		$allowed_post_types = array(
798
			'post' => 'post',
799
			'page' => 'page',
800
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
801
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
802
		);
803
804
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
805
			return $default_url;
806
		}
807
808
		$path_prefix = $allowed_post_types[ $post_type ];
809
810
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
811
812
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
813
	}
814
815
	function point_edit_comment_links_to_calypso( $url ) {
816
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
817
		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...
818
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
819
			Jetpack::build_raw_urls( get_home_url() ),
820
			$query_args['amp;c']
821
		) );
822
	}
823
824
	function jetpack_track_last_sync_callback( $params ) {
825
		/**
826
		 * Filter to turn off jitm caching
827
		 *
828
		 * @since 5.4.0
829
		 *
830
		 * @param bool false Whether to cache just in time messages
831
		 */
832
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
833
			return $params;
834
		}
835
836
		if ( is_array( $params ) && isset( $params[0] ) ) {
837
			$option = $params[0];
838
			if ( 'active_plugins' === $option ) {
839
				// use the cache if we can, but not terribly important if it gets evicted
840
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
841
			}
842
		}
843
844
		return $params;
845
	}
846
847
	function jetpack_connection_banner_callback() {
848
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
849
850
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
851
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
852
			wp_send_json_success();
853
		}
854
855
		wp_die();
856
	}
857
858
	/**
859
	 * Removes all XML-RPC methods that are not `jetpack.*`.
860
	 * Only used in our alternate XML-RPC endpoint, where we want to
861
	 * ensure that Core and other plugins' methods are not exposed.
862
	 *
863
	 * @deprecated since 7.7.0
864
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
865
	 *
866
	 * @param array $methods A list of registered WordPress XMLRPC methods.
867
	 * @return array Filtered $methods
868
	 */
869
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
870
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
871
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
872
	}
873
874
	/**
875
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
876
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
877
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
878
	 * which is accessible via a different URI. Most of the below is copied directly
879
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
880
	 *
881
	 * @deprecated since 7.7.0
882
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
883
	 */
884
	public function alternate_xmlrpc() {
885
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
886
		$this->connection_manager->alternate_xmlrpc();
887
	}
888
889
	/**
890
	 * The callback for the JITM ajax requests.
891
	 */
892
	function jetpack_jitm_ajax_callback() {
893
		// Check for nonce
894
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
895
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
896
		}
897
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
898
			$module_slug = $_REQUEST['jitmModule'];
899
			Jetpack::log( 'activate', $module_slug );
900
			Jetpack::activate_module( $module_slug, false, false );
901
			Jetpack::state( 'message', 'no_message' );
902
903
			//A Jetpack module is being activated through a JITM, track it
904
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
905
			$this->do_stats( 'server_side' );
906
907
			wp_send_json_success();
908
		}
909
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
910
			// get the hide_jitm options array
911
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
912
			$module_slug = $_REQUEST['jitmModule'];
913
914
			if( ! $jetpack_hide_jitm ) {
915
				$jetpack_hide_jitm = array(
916
					$module_slug => 'hide'
917
				);
918
			} else {
919
				$jetpack_hide_jitm[$module_slug] = 'hide';
920
			}
921
922
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
923
924
			//jitm is being dismissed forever, track it
925
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
926
			$this->do_stats( 'server_side' );
927
928
			wp_send_json_success();
929
		}
930 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
931
			$module_slug = $_REQUEST['jitmModule'];
932
933
			// User went to WordPress.com, track this
934
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
935
			$this->do_stats( 'server_side' );
936
937
			wp_send_json_success();
938
		}
939 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
940
			$track = $_REQUEST['jitmModule'];
941
942
			// User is viewing JITM, track it.
943
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
944
			$this->do_stats( 'server_side' );
945
946
			wp_send_json_success();
947
		}
948
	}
949
950
	/**
951
	 * If there are any stats that need to be pushed, but haven't been, push them now.
952
	 */
953
	function push_stats() {
954
		if ( ! empty( $this->stats ) ) {
955
			$this->do_stats( 'server_side' );
956
		}
957
	}
958
959
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
960
		switch( $cap ) {
961
			case 'jetpack_connect' :
962
			case 'jetpack_reconnect' :
963
				if ( Jetpack::is_development_mode() ) {
964
					$caps = array( 'do_not_allow' );
965
					break;
966
				}
967
				/**
968
				 * Pass through. If it's not development mode, these should match disconnect.
969
				 * Let users disconnect if it's development mode, just in case things glitch.
970
				 */
971
			case 'jetpack_disconnect' :
972
				/**
973
				 * In multisite, can individual site admins manage their own connection?
974
				 *
975
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
976
				 */
977
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
978
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
979
						/**
980
						 * We need to update the option name -- it's terribly unclear which
981
						 * direction the override goes.
982
						 *
983
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
984
						 */
985
						$caps = array( 'do_not_allow' );
986
						break;
987
					}
988
				}
989
990
				$caps = array( 'manage_options' );
991
				break;
992
			case 'jetpack_manage_modules' :
993
			case 'jetpack_activate_modules' :
994
			case 'jetpack_deactivate_modules' :
995
				$caps = array( 'manage_options' );
996
				break;
997
			case 'jetpack_configure_modules' :
998
				$caps = array( 'manage_options' );
999
				break;
1000
			case 'jetpack_manage_autoupdates' :
1001
				$caps = array(
1002
					'manage_options',
1003
					'update_plugins',
1004
				);
1005
				break;
1006
			case 'jetpack_network_admin_page':
1007
			case 'jetpack_network_settings_page':
1008
				$caps = array( 'manage_network_plugins' );
1009
				break;
1010
			case 'jetpack_network_sites_page':
1011
				$caps = array( 'manage_sites' );
1012
				break;
1013
			case 'jetpack_admin_page' :
1014
				if ( Jetpack::is_development_mode() ) {
1015
					$caps = array( 'manage_options' );
1016
					break;
1017
				} else {
1018
					$caps = array( 'read' );
1019
				}
1020
				break;
1021
			case 'jetpack_connect_user' :
1022
				if ( Jetpack::is_development_mode() ) {
1023
					$caps = array( 'do_not_allow' );
1024
					break;
1025
				}
1026
				$caps = array( 'read' );
1027
				break;
1028
		}
1029
		return $caps;
1030
	}
1031
1032
	/**
1033
	 * Require a Jetpack authentication.
1034
	 *
1035
	 * @deprecated since 7.7.0
1036
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1037
	 */
1038
	public function require_jetpack_authentication() {
1039
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1040
		$this->connection_manager->require_jetpack_authentication();
1041
	}
1042
1043
	/**
1044
	 * Load language files
1045
	 * @action plugins_loaded
1046
	 */
1047
	public static function plugin_textdomain() {
1048
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1049
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1050
	}
1051
1052
	/**
1053
	 * Register assets for use in various modules and the Jetpack admin page.
1054
	 *
1055
	 * @uses wp_script_is, wp_register_script, plugins_url
1056
	 * @action wp_loaded
1057
	 * @return null
1058
	 */
1059
	public function register_assets() {
1060
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1061
			wp_register_script(
1062
				'spin',
1063
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1064
				false,
1065
				'1.3'
1066
			);
1067
		}
1068
1069 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1070
			wp_register_script(
1071
				'jquery.spin',
1072
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1073
				array( 'jquery', 'spin' ),
1074
				'1.3'
1075
			);
1076
		}
1077
1078 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1079
			wp_register_script(
1080
				'jetpack-gallery-settings',
1081
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1082
				array( 'media-views' ),
1083
				'20121225'
1084
			);
1085
		}
1086
1087 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1088
			wp_register_script(
1089
				'jetpack-twitter-timeline',
1090
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1091
				array( 'jquery' ),
1092
				'4.0.0',
1093
				true
1094
			);
1095
		}
1096
1097
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1098
			wp_register_script(
1099
				'jetpack-facebook-embed',
1100
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1101
				array( 'jquery' ),
1102
				null,
1103
				true
1104
			);
1105
1106
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1107
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1108
			if ( ! is_numeric( $fb_app_id ) ) {
1109
				$fb_app_id = '';
1110
			}
1111
			wp_localize_script(
1112
				'jetpack-facebook-embed',
1113
				'jpfbembed',
1114
				array(
1115
					'appid' => $fb_app_id,
1116
					'locale' => $this->get_locale(),
1117
				)
1118
			);
1119
		}
1120
1121
		/**
1122
		 * As jetpack_register_genericons is by default fired off a hook,
1123
		 * the hook may have already fired by this point.
1124
		 * So, let's just trigger it manually.
1125
		 */
1126
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1127
		jetpack_register_genericons();
1128
1129
		/**
1130
		 * Register the social logos
1131
		 */
1132
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1133
		jetpack_register_social_logos();
1134
1135 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1136
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1137
	}
1138
1139
	/**
1140
	 * Guess locale from language code.
1141
	 *
1142
	 * @param string $lang Language code.
1143
	 * @return string|bool
1144
	 */
1145 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1146
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1147
			return 'en_US';
1148
		}
1149
1150
		if ( ! class_exists( 'GP_Locales' ) ) {
1151
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1152
				return false;
1153
			}
1154
1155
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1156
		}
1157
1158
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1159
			// WP.com: get_locale() returns 'it'
1160
			$locale = GP_Locales::by_slug( $lang );
1161
		} else {
1162
			// Jetpack: get_locale() returns 'it_IT';
1163
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1164
		}
1165
1166
		if ( ! $locale ) {
1167
			return false;
1168
		}
1169
1170
		if ( empty( $locale->facebook_locale ) ) {
1171
			if ( empty( $locale->wp_locale ) ) {
1172
				return false;
1173
			} else {
1174
				// Facebook SDK is smart enough to fall back to en_US if a
1175
				// locale isn't supported. Since supported Facebook locales
1176
				// can fall out of sync, we'll attempt to use the known
1177
				// wp_locale value and rely on said fallback.
1178
				return $locale->wp_locale;
1179
			}
1180
		}
1181
1182
		return $locale->facebook_locale;
1183
	}
1184
1185
	/**
1186
	 * Get the locale.
1187
	 *
1188
	 * @return string|bool
1189
	 */
1190
	function get_locale() {
1191
		$locale = $this->guess_locale_from_lang( get_locale() );
1192
1193
		if ( ! $locale ) {
1194
			$locale = 'en_US';
1195
		}
1196
1197
		return $locale;
1198
	}
1199
1200
	/**
1201
	 * Device Pixels support
1202
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1203
	 */
1204
	function devicepx() {
1205
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1206
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1207
		}
1208
	}
1209
1210
	/**
1211
	 * Return the network_site_url so that .com knows what network this site is a part of.
1212
	 * @param  bool $option
1213
	 * @return string
1214
	 */
1215
	public function jetpack_main_network_site_option( $option ) {
1216
		return network_site_url();
1217
	}
1218
	/**
1219
	 * Network Name.
1220
	 */
1221
	static function network_name( $option = null ) {
1222
		global $current_site;
1223
		return $current_site->site_name;
1224
	}
1225
	/**
1226
	 * Does the network allow new user and site registrations.
1227
	 * @return string
1228
	 */
1229
	static function network_allow_new_registrations( $option = null ) {
1230
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1231
	}
1232
	/**
1233
	 * Does the network allow admins to add new users.
1234
	 * @return boolian
1235
	 */
1236
	static function network_add_new_users( $option = null ) {
1237
		return (bool) get_site_option( 'add_new_users' );
1238
	}
1239
	/**
1240
	 * File upload psace left per site in MB.
1241
	 *  -1 means NO LIMIT.
1242
	 * @return number
1243
	 */
1244
	static function network_site_upload_space( $option = null ) {
1245
		// value in MB
1246
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1247
	}
1248
1249
	/**
1250
	 * Network allowed file types.
1251
	 * @return string
1252
	 */
1253
	static function network_upload_file_types( $option = null ) {
1254
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1255
	}
1256
1257
	/**
1258
	 * Maximum file upload size set by the network.
1259
	 * @return number
1260
	 */
1261
	static function network_max_upload_file_size( $option = null ) {
1262
		// value in KB
1263
		return get_site_option( 'fileupload_maxk', 300 );
1264
	}
1265
1266
	/**
1267
	 * Lets us know if a site allows admins to manage the network.
1268
	 * @return array
1269
	 */
1270
	static function network_enable_administration_menus( $option = null ) {
1271
		return get_site_option( 'menu_items' );
1272
	}
1273
1274
	/**
1275
	 * If a user has been promoted to or demoted from admin, we need to clear the
1276
	 * jetpack_other_linked_admins transient.
1277
	 *
1278
	 * @since 4.3.2
1279
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1280
	 *
1281
	 * @param int    $user_id   The user ID whose role changed.
1282
	 * @param string $role      The new role.
1283
	 * @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...
1284
	 */
1285
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1286
		if ( 'administrator' == $role
1287
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1288
			|| is_null( $old_roles )
1289
		) {
1290
			delete_transient( 'jetpack_other_linked_admins' );
1291
		}
1292
	}
1293
1294
	/**
1295
	 * Checks to see if there are any other users available to become primary
1296
	 * Users must both:
1297
	 * - Be linked to wpcom
1298
	 * - Be an admin
1299
	 *
1300
	 * @return mixed False if no other users are linked, Int if there are.
1301
	 */
1302
	static function get_other_linked_admins() {
1303
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1304
1305
		if ( false === $other_linked_users ) {
1306
			$admins = get_users( array( 'role' => 'administrator' ) );
1307
			if ( count( $admins ) > 1 ) {
1308
				$available = array();
1309
				foreach ( $admins as $admin ) {
1310
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1311
						$available[] = $admin->ID;
1312
					}
1313
				}
1314
1315
				$count_connected_admins = count( $available );
1316
				if ( count( $available ) > 1 ) {
1317
					$other_linked_users = $count_connected_admins;
1318
				} else {
1319
					$other_linked_users = 0;
1320
				}
1321
			} else {
1322
				$other_linked_users = 0;
1323
			}
1324
1325
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1326
		}
1327
1328
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1329
	}
1330
1331
	/**
1332
	 * Return whether we are dealing with a multi network setup or not.
1333
	 * The reason we are type casting this is because we want to avoid the situation where
1334
	 * the result is false since when is_main_network_option return false it cases
1335
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1336
	 * database which could be set to anything as opposed to what this function returns.
1337
	 * @param  bool  $option
1338
	 *
1339
	 * @return boolean
1340
	 */
1341
	public function is_main_network_option( $option ) {
1342
		// return '1' or ''
1343
		return (string) (bool) Jetpack::is_multi_network();
1344
	}
1345
1346
	/**
1347
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1348
	 *
1349
	 * @param  string  $option
1350
	 * @return boolean
1351
	 */
1352
	public function is_multisite( $option ) {
1353
		return (string) (bool) is_multisite();
1354
	}
1355
1356
	/**
1357
	 * Implemented since there is no core is multi network function
1358
	 * Right now there is no way to tell if we which network is the dominant network on the system
1359
	 *
1360
	 * @since  3.3
1361
	 * @return boolean
1362
	 */
1363 View Code Duplication
	public static function is_multi_network() {
1364
		global  $wpdb;
1365
1366
		// if we don't have a multi site setup no need to do any more
1367
		if ( ! is_multisite() ) {
1368
			return false;
1369
		}
1370
1371
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1372
		if ( $num_sites > 1 ) {
1373
			return true;
1374
		} else {
1375
			return false;
1376
		}
1377
	}
1378
1379
	/**
1380
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1381
	 * @return null
1382
	 */
1383
	function update_jetpack_main_network_site_option() {
1384
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1385
	}
1386
	/**
1387
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1388
	 *
1389
	 */
1390
	function update_jetpack_network_settings() {
1391
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1392
		// Only sync this info for the main network site.
1393
	}
1394
1395
	/**
1396
	 * Get back if the current site is single user site.
1397
	 *
1398
	 * @return bool
1399
	 */
1400 View Code Duplication
	public static function is_single_user_site() {
1401
		global $wpdb;
1402
1403
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1404
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1405
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1406
		}
1407
		return 1 === (int) $some_users;
1408
	}
1409
1410
	/**
1411
	 * Returns true if the site has file write access false otherwise.
1412
	 * @return string ( '1' | '0' )
1413
	 **/
1414
	public static function file_system_write_access() {
1415
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1416
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1417
		}
1418
1419
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1420
1421
		$filesystem_method = get_filesystem_method();
1422
		if ( $filesystem_method === 'direct' ) {
1423
			return 1;
1424
		}
1425
1426
		ob_start();
1427
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1428
		ob_end_clean();
1429
		if ( $filesystem_credentials_are_stored ) {
1430
			return 1;
1431
		}
1432
		return 0;
1433
	}
1434
1435
	/**
1436
	 * Finds out if a site is using a version control system.
1437
	 * @return string ( '1' | '0' )
1438
	 **/
1439
	public static function is_version_controlled() {
1440
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1441
		return (string) (int) Functions::is_version_controlled();
1442
	}
1443
1444
	/**
1445
	 * Determines whether the current theme supports featured images or not.
1446
	 * @return string ( '1' | '0' )
1447
	 */
1448
	public static function featured_images_enabled() {
1449
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1450
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1451
	}
1452
1453
	/**
1454
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1455
	 *
1456
	 * @deprecated 4.7 use get_avatar_url instead.
1457
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1458
	 * @param int $size Size of the avatar image
1459
	 * @param string $default URL to a default image to use if no avatar is available
1460
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1461
	 *
1462
	 * @return array
1463
	 */
1464
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1465
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1466
		return get_avatar_url( $id_or_email, array(
1467
			'size' => $size,
1468
			'default' => $default,
1469
			'force_default' => $force_display,
1470
		) );
1471
	}
1472
1473
	/**
1474
	 * jetpack_updates is saved in the following schema:
1475
	 *
1476
	 * array (
1477
	 *      'plugins'                       => (int) Number of plugin updates available.
1478
	 *      'themes'                        => (int) Number of theme updates available.
1479
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1480
	 *      'translations'                  => (int) Number of translation updates available.
1481
	 *      'total'                         => (int) Total of all available updates.
1482
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1483
	 * )
1484
	 * @return array
1485
	 */
1486
	public static function get_updates() {
1487
		$update_data = wp_get_update_data();
1488
1489
		// Stores the individual update counts as well as the total count.
1490
		if ( isset( $update_data['counts'] ) ) {
1491
			$updates = $update_data['counts'];
1492
		}
1493
1494
		// If we need to update WordPress core, let's find the latest version number.
1495 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1496
			$cur = get_preferred_from_update_core();
1497
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1498
				$updates['wp_update_version'] = $cur->current;
1499
			}
1500
		}
1501
		return isset( $updates ) ? $updates : array();
1502
	}
1503
1504
	public static function get_update_details() {
1505
		$update_details = array(
1506
			'update_core' => get_site_transient( 'update_core' ),
1507
			'update_plugins' => get_site_transient( 'update_plugins' ),
1508
			'update_themes' => get_site_transient( 'update_themes' ),
1509
		);
1510
		return $update_details;
1511
	}
1512
1513
	public static function refresh_update_data() {
1514
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1515
1516
	}
1517
1518
	public static function refresh_theme_data() {
1519
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1520
	}
1521
1522
	/**
1523
	 * Is Jetpack active?
1524
	 */
1525
	public static function is_active() {
1526
		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...
1527
	}
1528
1529
	/**
1530
	 * Make an API call to WordPress.com for plan status
1531
	 *
1532
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1533
	 *
1534
	 * @return bool True if plan is updated, false if no update
1535
	 */
1536
	public static function refresh_active_plan_from_wpcom() {
1537
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1538
		return Jetpack_Plan::refresh_from_wpcom();
1539
	}
1540
1541
	/**
1542
	 * Get the plan that this Jetpack site is currently using
1543
	 *
1544
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1545
	 * @return array Active Jetpack plan details.
1546
	 */
1547
	public static function get_active_plan() {
1548
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1549
		return Jetpack_Plan::get();
1550
	}
1551
1552
	/**
1553
	 * Determine whether the active plan supports a particular feature
1554
	 *
1555
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1556
	 * @return bool True if plan supports feature, false if not.
1557
	 */
1558
	public static function active_plan_supports( $feature ) {
1559
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1560
		return Jetpack_Plan::supports( $feature );
1561
	}
1562
1563
	/**
1564
	 * Is Jetpack in development (offline) mode?
1565
	 */
1566 View Code Duplication
	public static function is_development_mode() {
1567
		$development_mode = false;
1568
1569
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1570
			$development_mode = JETPACK_DEV_DEBUG;
1571
		} elseif ( $site_url = site_url() ) {
1572
			$development_mode = false === strpos( $site_url, '.' );
1573
		}
1574
1575
		/**
1576
		 * Filters Jetpack's development mode.
1577
		 *
1578
		 * @see https://jetpack.com/support/development-mode/
1579
		 *
1580
		 * @since 2.2.1
1581
		 *
1582
		 * @param bool $development_mode Is Jetpack's development mode active.
1583
		 */
1584
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1585
		return $development_mode;
1586
	}
1587
1588
	/**
1589
	 * Whether the site is currently onboarding or not.
1590
	 * A site is considered as being onboarded if it currently has an onboarding token.
1591
	 *
1592
	 * @since 5.8
1593
	 *
1594
	 * @access public
1595
	 * @static
1596
	 *
1597
	 * @return bool True if the site is currently onboarding, false otherwise
1598
	 */
1599
	public static function is_onboarding() {
1600
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1601
	}
1602
1603
	/**
1604
	 * Determines reason for Jetpack development mode.
1605
	 */
1606
	public static function development_mode_trigger_text() {
1607
		if ( ! Jetpack::is_development_mode() ) {
1608
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1609
		}
1610
1611
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1612
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1613
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1614
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1615
		} else {
1616
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1617
		}
1618
1619
		return $notice;
1620
1621
	}
1622
	/**
1623
	* Get Jetpack development mode notice text and notice class.
1624
	*
1625
	* Mirrors the checks made in Jetpack::is_development_mode
1626
	*
1627
	*/
1628
	public static function show_development_mode_notice() {
1629 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1630
			$notice = sprintf(
1631
			/* translators: %s is a URL */
1632
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1633
				'https://jetpack.com/support/development-mode/'
1634
			);
1635
1636
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1637
1638
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1639
		}
1640
1641
		// Throw up a notice if using a development version and as for feedback.
1642
		if ( Jetpack::is_development_version() ) {
1643
			/* translators: %s is a URL */
1644
			$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/' );
1645
1646
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1647
		}
1648
		// Throw up a notice if using staging mode
1649
		if ( Jetpack::is_staging_site() ) {
1650
			/* translators: %s is a URL */
1651
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1652
1653
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1654
		}
1655
	}
1656
1657
	/**
1658
	 * Whether Jetpack's version maps to a public release, or a development version.
1659
	 */
1660
	public static function is_development_version() {
1661
		/**
1662
		 * Allows filtering whether this is a development version of Jetpack.
1663
		 *
1664
		 * This filter is especially useful for tests.
1665
		 *
1666
		 * @since 4.3.0
1667
		 *
1668
		 * @param bool $development_version Is this a develoment version of Jetpack?
1669
		 */
1670
		return (bool) apply_filters(
1671
			'jetpack_development_version',
1672
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1673
		);
1674
	}
1675
1676
	/**
1677
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1678
	 */
1679
	public static function is_user_connected( $user_id = false ) {
1680
		return self::connection()->is_user_connected( $user_id );
1681
	}
1682
1683
	/**
1684
	 * Get the wpcom user data of the current|specified connected user.
1685
	 */
1686 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1687
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1688
		if ( ! $user_id ) {
1689
			$user_id = get_current_user_id();
1690
		}
1691
1692
		$transient_key = "jetpack_connected_user_data_$user_id";
1693
1694
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1695
			return $cached_user_data;
1696
		}
1697
1698
		$xml = new Jetpack_IXR_Client( array(
1699
			'user_id' => $user_id,
1700
		) );
1701
		$xml->query( 'wpcom.getUser' );
1702
		if ( ! $xml->isError() ) {
1703
			$user_data = $xml->getResponse();
1704
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1705
			return $user_data;
1706
		}
1707
1708
		return false;
1709
	}
1710
1711
	/**
1712
	 * Get the wpcom email of the current|specified connected user.
1713
	 */
1714 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1715
		if ( ! $user_id ) {
1716
			$user_id = get_current_user_id();
1717
		}
1718
1719
		$xml = new Jetpack_IXR_Client( array(
1720
			'user_id' => $user_id,
1721
		) );
1722
		$xml->query( 'wpcom.getUserEmail' );
1723
		if ( ! $xml->isError() ) {
1724
			return $xml->getResponse();
1725
		}
1726
		return false;
1727
	}
1728
1729
	/**
1730
	 * Get the wpcom email of the master user.
1731
	 */
1732
	public static function get_master_user_email() {
1733
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1734
		if ( $master_user_id ) {
1735
			return self::get_connected_user_email( $master_user_id );
1736
		}
1737
		return '';
1738
	}
1739
1740
	/**
1741
	 * Whether the current user is the connection owner.
1742
	 *
1743
	 * @deprecated since 7.7
1744
	 *
1745
	 * @return bool Whether the current user is the connection owner.
1746
	 */
1747
	public function current_user_is_connection_owner() {
1748
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1749
		return self::connection()->is_connection_owner();
1750
	}
1751
1752
	/**
1753
	 * Gets current user IP address.
1754
	 *
1755
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1756
	 *
1757
	 * @return string                  Current user IP address.
1758
	 */
1759
	public static function current_user_ip( $check_all_headers = false ) {
1760
		if ( $check_all_headers ) {
1761
			foreach ( array(
1762
				'HTTP_CF_CONNECTING_IP',
1763
				'HTTP_CLIENT_IP',
1764
				'HTTP_X_FORWARDED_FOR',
1765
				'HTTP_X_FORWARDED',
1766
				'HTTP_X_CLUSTER_CLIENT_IP',
1767
				'HTTP_FORWARDED_FOR',
1768
				'HTTP_FORWARDED',
1769
				'HTTP_VIA',
1770
			) as $key ) {
1771
				if ( ! empty( $_SERVER[ $key ] ) ) {
1772
					return $_SERVER[ $key ];
1773
				}
1774
			}
1775
		}
1776
1777
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1778
	}
1779
1780
	/**
1781
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1782
	 */
1783
	function extra_oembed_providers() {
1784
		// Cloudup: https://dev.cloudup.com/#oembed
1785
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1786
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1787
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1788
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1789
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1790
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1791
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1792
	}
1793
1794
	/**
1795
	 * Synchronize connected user role changes
1796
	 */
1797
	function user_role_change( $user_id ) {
1798
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1799
		Users::user_role_change( $user_id );
1800
	}
1801
1802
	/**
1803
	 * Loads the currently active modules.
1804
	 */
1805
	public static function load_modules() {
1806
		if (
1807
			! self::is_active()
1808
			&& ! self::is_development_mode()
1809
			&& ! self::is_onboarding()
1810
			&& (
1811
				! is_multisite()
1812
				|| ! get_site_option( 'jetpack_protect_active' )
1813
			)
1814
		) {
1815
			return;
1816
		}
1817
1818
		$version = Jetpack_Options::get_option( 'version' );
1819 View Code Duplication
		if ( ! $version ) {
1820
			$version = $old_version = JETPACK__VERSION . ':' . time();
1821
			/** This action is documented in class.jetpack.php */
1822
			do_action( 'updating_jetpack_version', $version, false );
1823
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1824
		}
1825
		list( $version ) = explode( ':', $version );
1826
1827
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1828
1829
		$modules_data = array();
1830
1831
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1832
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1833
			$updated_modules = array();
1834
			foreach ( $modules as $module ) {
1835
				$modules_data[ $module ] = Jetpack::get_module( $module );
1836
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1837
					continue;
1838
				}
1839
1840
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1841
					continue;
1842
				}
1843
1844
				$updated_modules[] = $module;
1845
			}
1846
1847
			$modules = array_diff( $modules, $updated_modules );
1848
		}
1849
1850
		$is_development_mode = Jetpack::is_development_mode();
1851
1852
		foreach ( $modules as $index => $module ) {
1853
			// If we're in dev mode, disable modules requiring a connection
1854
			if ( $is_development_mode ) {
1855
				// Prime the pump if we need to
1856
				if ( empty( $modules_data[ $module ] ) ) {
1857
					$modules_data[ $module ] = Jetpack::get_module( $module );
1858
				}
1859
				// If the module requires a connection, but we're in local mode, don't include it.
1860
				if ( $modules_data[ $module ]['requires_connection'] ) {
1861
					continue;
1862
				}
1863
			}
1864
1865
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1866
				continue;
1867
			}
1868
1869
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1870
				unset( $modules[ $index ] );
1871
				self::update_active_modules( array_values( $modules ) );
1872
				continue;
1873
			}
1874
1875
			/**
1876
			 * Fires when a specific module is loaded.
1877
			 * The dynamic part of the hook, $module, is the module slug.
1878
			 *
1879
			 * @since 1.1.0
1880
			 */
1881
			do_action( 'jetpack_module_loaded_' . $module );
1882
		}
1883
1884
		/**
1885
		 * Fires when all the modules are loaded.
1886
		 *
1887
		 * @since 1.1.0
1888
		 */
1889
		do_action( 'jetpack_modules_loaded' );
1890
1891
		// 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.
1892
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1893
	}
1894
1895
	/**
1896
	 * Check if Jetpack's REST API compat file should be included
1897
	 * @action plugins_loaded
1898
	 * @return null
1899
	 */
1900
	public function check_rest_api_compat() {
1901
		/**
1902
		 * Filters the list of REST API compat files to be included.
1903
		 *
1904
		 * @since 2.2.5
1905
		 *
1906
		 * @param array $args Array of REST API compat files to include.
1907
		 */
1908
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1909
1910
		if ( function_exists( 'bbpress' ) )
1911
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1912
1913
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1914
			require_once $_jetpack_rest_api_compat_include;
1915
	}
1916
1917
	/**
1918
	 * Gets all plugins currently active in values, regardless of whether they're
1919
	 * traditionally activated or network activated.
1920
	 *
1921
	 * @todo Store the result in core's object cache maybe?
1922
	 */
1923
	public static function get_active_plugins() {
1924
		$active_plugins = (array) get_option( 'active_plugins', array() );
1925
1926
		if ( is_multisite() ) {
1927
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1928
			// whereas active_plugins stores them in the values.
1929
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1930
			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...
1931
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1932
			}
1933
		}
1934
1935
		sort( $active_plugins );
1936
1937
		return array_unique( $active_plugins );
1938
	}
1939
1940
	/**
1941
	 * Gets and parses additional plugin data to send with the heartbeat data
1942
	 *
1943
	 * @since 3.8.1
1944
	 *
1945
	 * @return array Array of plugin data
1946
	 */
1947
	public static function get_parsed_plugin_data() {
1948
		if ( ! function_exists( 'get_plugins' ) ) {
1949
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1950
		}
1951
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1952
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1953
		$active_plugins = Jetpack::get_active_plugins();
1954
1955
		$plugins = array();
1956
		foreach ( $all_plugins as $path => $plugin_data ) {
1957
			$plugins[ $path ] = array(
1958
					'is_active' => in_array( $path, $active_plugins ),
1959
					'file'      => $path,
1960
					'name'      => $plugin_data['Name'],
1961
					'version'   => $plugin_data['Version'],
1962
					'author'    => $plugin_data['Author'],
1963
			);
1964
		}
1965
1966
		return $plugins;
1967
	}
1968
1969
	/**
1970
	 * Gets and parses theme data to send with the heartbeat data
1971
	 *
1972
	 * @since 3.8.1
1973
	 *
1974
	 * @return array Array of theme data
1975
	 */
1976
	public static function get_parsed_theme_data() {
1977
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1978
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1979
1980
		$themes = array();
1981
		foreach ( $all_themes as $slug => $theme_data ) {
1982
			$theme_headers = array();
1983
			foreach ( $header_keys as $header_key ) {
1984
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1985
			}
1986
1987
			$themes[ $slug ] = array(
1988
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1989
					'slug' => $slug,
1990
					'theme_root' => $theme_data->get_theme_root_uri(),
1991
					'parent' => $theme_data->parent(),
1992
					'headers' => $theme_headers
1993
			);
1994
		}
1995
1996
		return $themes;
1997
	}
1998
1999
	/**
2000
	 * Checks whether a specific plugin is active.
2001
	 *
2002
	 * We don't want to store these in a static variable, in case
2003
	 * there are switch_to_blog() calls involved.
2004
	 */
2005
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2006
		return in_array( $plugin, self::get_active_plugins() );
2007
	}
2008
2009
	/**
2010
	 * Check if Jetpack's Open Graph tags should be used.
2011
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2012
	 *
2013
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2014
	 * @action plugins_loaded
2015
	 * @return null
2016
	 */
2017
	public function check_open_graph() {
2018
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2019
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2020
		}
2021
2022
		$active_plugins = self::get_active_plugins();
2023
2024
		if ( ! empty( $active_plugins ) ) {
2025
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2026
				if ( in_array( $plugin, $active_plugins ) ) {
2027
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2028
					break;
2029
				}
2030
			}
2031
		}
2032
2033
		/**
2034
		 * Allow the addition of Open Graph Meta Tags to all pages.
2035
		 *
2036
		 * @since 2.0.3
2037
		 *
2038
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2039
		 */
2040
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2041
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2042
		}
2043
	}
2044
2045
	/**
2046
	 * Check if Jetpack's Twitter tags should be used.
2047
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2048
	 *
2049
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2050
	 * @action plugins_loaded
2051
	 * @return null
2052
	 */
2053
	public function check_twitter_tags() {
2054
2055
		$active_plugins = self::get_active_plugins();
2056
2057
		if ( ! empty( $active_plugins ) ) {
2058
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2059
				if ( in_array( $plugin, $active_plugins ) ) {
2060
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2061
					break;
2062
				}
2063
			}
2064
		}
2065
2066
		/**
2067
		 * Allow Twitter Card Meta tags to be disabled.
2068
		 *
2069
		 * @since 2.6.0
2070
		 *
2071
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2072
		 */
2073
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2074
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2075
		}
2076
	}
2077
2078
	/**
2079
	 * Allows plugins to submit security reports.
2080
 	 *
2081
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2082
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2083
	 * @param array   $args         See definitions above
2084
	 */
2085
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2086
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2087
	}
2088
2089
/* Jetpack Options API */
2090
2091
	public static function get_option_names( $type = 'compact' ) {
2092
		return Jetpack_Options::get_option_names( $type );
2093
	}
2094
2095
	/**
2096
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2097
 	 *
2098
	 * @param string $name    Option name
2099
	 * @param mixed  $default (optional)
2100
	 */
2101
	public static function get_option( $name, $default = false ) {
2102
		return Jetpack_Options::get_option( $name, $default );
2103
	}
2104
2105
	/**
2106
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2107
 	 *
2108
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2109
	 * @param string $name  Option name
2110
	 * @param mixed  $value Option value
2111
	 */
2112
	public static function update_option( $name, $value ) {
2113
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2114
		return Jetpack_Options::update_option( $name, $value );
2115
	}
2116
2117
	/**
2118
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2119
 	 *
2120
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2121
	 * @param array $array array( option name => option value, ... )
2122
	 */
2123
	public static function update_options( $array ) {
2124
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2125
		return Jetpack_Options::update_options( $array );
2126
	}
2127
2128
	/**
2129
	 * Deletes the given option.  May be passed multiple option names as an array.
2130
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2131
	 *
2132
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2133
	 * @param string|array $names
2134
	 */
2135
	public static function delete_option( $names ) {
2136
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2137
		return Jetpack_Options::delete_option( $names );
2138
	}
2139
2140
	/**
2141
	 * Enters a user token into the user_tokens option
2142
	 *
2143
	 * @param int $user_id
2144
	 * @param string $token
2145
	 * return bool
2146
	 */
2147
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2148
		// not designed for concurrent updates
2149
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2150
		if ( ! is_array( $user_tokens ) )
2151
			$user_tokens = array();
2152
		$user_tokens[$user_id] = $token;
2153
		if ( $is_master_user ) {
2154
			$master_user = $user_id;
2155
			$options     = compact( 'user_tokens', 'master_user' );
2156
		} else {
2157
			$options = compact( 'user_tokens' );
2158
		}
2159
		return Jetpack_Options::update_options( $options );
2160
	}
2161
2162
	/**
2163
	 * Returns an array of all PHP files in the specified absolute path.
2164
	 * Equivalent to glob( "$absolute_path/*.php" ).
2165
	 *
2166
	 * @param string $absolute_path The absolute path of the directory to search.
2167
	 * @return array Array of absolute paths to the PHP files.
2168
	 */
2169
	public static function glob_php( $absolute_path ) {
2170
		if ( function_exists( 'glob' ) ) {
2171
			return glob( "$absolute_path/*.php" );
2172
		}
2173
2174
		$absolute_path = untrailingslashit( $absolute_path );
2175
		$files = array();
2176
		if ( ! $dir = @opendir( $absolute_path ) ) {
2177
			return $files;
2178
		}
2179
2180
		while ( false !== $file = readdir( $dir ) ) {
2181
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2182
				continue;
2183
			}
2184
2185
			$file = "$absolute_path/$file";
2186
2187
			if ( ! is_file( $file ) ) {
2188
				continue;
2189
			}
2190
2191
			$files[] = $file;
2192
		}
2193
2194
		closedir( $dir );
2195
2196
		return $files;
2197
	}
2198
2199
	public static function activate_new_modules( $redirect = false ) {
2200
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2201
			return;
2202
		}
2203
2204
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2205 View Code Duplication
		if ( ! $jetpack_old_version ) {
2206
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2207
			/** This action is documented in class.jetpack.php */
2208
			do_action( 'updating_jetpack_version', $version, false );
2209
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2210
		}
2211
2212
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2213
2214
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2215
			return;
2216
		}
2217
2218
		$active_modules     = Jetpack::get_active_modules();
2219
		$reactivate_modules = array();
2220
		foreach ( $active_modules as $active_module ) {
2221
			$module = Jetpack::get_module( $active_module );
2222
			if ( ! isset( $module['changed'] ) ) {
2223
				continue;
2224
			}
2225
2226
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2227
				continue;
2228
			}
2229
2230
			$reactivate_modules[] = $active_module;
2231
			Jetpack::deactivate_module( $active_module );
2232
		}
2233
2234
		$new_version = JETPACK__VERSION . ':' . time();
2235
		/** This action is documented in class.jetpack.php */
2236
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2237
		Jetpack_Options::update_options(
2238
			array(
2239
				'version'     => $new_version,
2240
				'old_version' => $jetpack_old_version,
2241
			)
2242
		);
2243
2244
		Jetpack::state( 'message', 'modules_activated' );
2245
		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...
2246
2247
		if ( $redirect ) {
2248
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2249
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2250
				$page = $_GET['page'];
2251
			}
2252
2253
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2254
			exit;
2255
		}
2256
	}
2257
2258
	/**
2259
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2260
	 * Make sure to tuck away module "library" files in a sub-directory.
2261
	 */
2262
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2263
		static $modules = null;
2264
2265
		if ( ! isset( $modules ) ) {
2266
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2267
			// Use the cache if we're on the front-end and it's available...
2268
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2269
				$modules = $available_modules_option[ JETPACK__VERSION ];
2270
			} else {
2271
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2272
2273
				$modules = array();
2274
2275
				foreach ( $files as $file ) {
2276
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2277
						continue;
2278
					}
2279
2280
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2281
				}
2282
2283
				Jetpack_Options::update_option( 'available_modules', array(
2284
					JETPACK__VERSION => $modules,
2285
				) );
2286
			}
2287
		}
2288
2289
		/**
2290
		 * Filters the array of modules available to be activated.
2291
		 *
2292
		 * @since 2.4.0
2293
		 *
2294
		 * @param array $modules Array of available modules.
2295
		 * @param string $min_version Minimum version number required to use modules.
2296
		 * @param string $max_version Maximum version number required to use modules.
2297
		 */
2298
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2299
2300
		if ( ! $min_version && ! $max_version ) {
2301
			return array_keys( $mods );
2302
		}
2303
2304
		$r = array();
2305
		foreach ( $mods as $slug => $introduced ) {
2306
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2307
				continue;
2308
			}
2309
2310
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2311
				continue;
2312
			}
2313
2314
			$r[] = $slug;
2315
		}
2316
2317
		return $r;
2318
	}
2319
2320
	/**
2321
	 * Default modules loaded on activation.
2322
	 */
2323
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2324
		$return = array();
2325
2326
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2327
			$module_data = Jetpack::get_module( $module );
2328
2329
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2330
				case 'yes' :
2331
					$return[] = $module;
2332
					break;
2333
				case 'public' :
2334
					if ( Jetpack_Options::get_option( 'public' ) ) {
2335
						$return[] = $module;
2336
					}
2337
					break;
2338
				case 'no' :
2339
				default :
2340
					break;
2341
			}
2342
		}
2343
		/**
2344
		 * Filters the array of default modules.
2345
		 *
2346
		 * @since 2.5.0
2347
		 *
2348
		 * @param array $return Array of default modules.
2349
		 * @param string $min_version Minimum version number required to use modules.
2350
		 * @param string $max_version Maximum version number required to use modules.
2351
		 */
2352
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2353
	}
2354
2355
	/**
2356
	 * Checks activated modules during auto-activation to determine
2357
	 * if any of those modules are being deprecated.  If so, close
2358
	 * them out, and add any replacement modules.
2359
	 *
2360
	 * Runs at priority 99 by default.
2361
	 *
2362
	 * This is run late, so that it can still activate a module if
2363
	 * the new module is a replacement for another that the user
2364
	 * currently has active, even if something at the normal priority
2365
	 * would kibosh everything.
2366
	 *
2367
	 * @since 2.6
2368
	 * @uses jetpack_get_default_modules filter
2369
	 * @param array $modules
2370
	 * @return array
2371
	 */
2372
	function handle_deprecated_modules( $modules ) {
2373
		$deprecated_modules = array(
2374
			'debug'            => null,  // Closed out and moved to the debugger library.
2375
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2376
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2377
		);
2378
2379
		// Don't activate SSO if they never completed activating WPCC.
2380
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2381
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2382
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2383
				$deprecated_modules['wpcc'] = null;
2384
			}
2385
		}
2386
2387
		foreach ( $deprecated_modules as $module => $replacement ) {
2388
			if ( Jetpack::is_module_active( $module ) ) {
2389
				self::deactivate_module( $module );
2390
				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...
2391
					$modules[] = $replacement;
2392
				}
2393
			}
2394
		}
2395
2396
		return array_unique( $modules );
2397
	}
2398
2399
	/**
2400
	 * Checks activated plugins during auto-activation to determine
2401
	 * if any of those plugins are in the list with a corresponding module
2402
	 * that is not compatible with the plugin. The module will not be allowed
2403
	 * to auto-activate.
2404
	 *
2405
	 * @since 2.6
2406
	 * @uses jetpack_get_default_modules filter
2407
	 * @param array $modules
2408
	 * @return array
2409
	 */
2410
	function filter_default_modules( $modules ) {
2411
2412
		$active_plugins = self::get_active_plugins();
2413
2414
		if ( ! empty( $active_plugins ) ) {
2415
2416
			// For each module we'd like to auto-activate...
2417
			foreach ( $modules as $key => $module ) {
2418
				// If there are potential conflicts for it...
2419
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2420
					// For each potential conflict...
2421
					foreach ( $this->conflicting_plugins[ $module ] 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 = true
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
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2804
		$modules = array_merge( $other_modules, $modules );
2805
2806
		// Look for standalone plugins and disable if active.
2807
2808
		$to_deactivate = array();
2809
		foreach ( $modules as $module ) {
2810
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2811
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2812
			}
2813
		}
2814
2815
		$deactivated = array();
2816
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2817
			list( $probable_file, $probable_title ) = $deactivate_me;
2818
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2819
				$deactivated[] = $module;
2820
			}
2821
		}
2822
2823
		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...
2824
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2825
2826
			if ( $redirect ) {
2827
				$url = add_query_arg(
2828
					array(
2829
						'action'   => 'activate_default_modules',
2830
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2831
					),
2832
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2833
				);
2834
				wp_safe_redirect( $url );
2835
				exit;
2836
			}
2837
		}
2838
2839
		/**
2840
		 * Fires before default modules are activated.
2841
		 *
2842
		 * @since 1.9.0
2843
		 *
2844
		 * @param string $min_version Minimum version number required to use modules.
2845
		 * @param string $max_version Maximum version number required to use modules.
2846
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2847
		 */
2848
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2849
2850
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2851
		if ( $send_state_messages ) {
2852
			Jetpack::restate();
2853
			Jetpack::catch_errors( true );
2854
		}
2855
2856
		$active = Jetpack::get_active_modules();
2857
2858
		foreach ( $modules as $module ) {
2859
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2860
				$active[] = $module;
2861
				self::update_active_modules( $active );
2862
				continue;
2863
			}
2864
2865
			if ( $send_state_messages && in_array( $module, $active ) ) {
2866
				$module_info = Jetpack::get_module( $module );
2867 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2868
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2869
					if ( $active_state = Jetpack::state( $state ) ) {
2870
						$active_state = explode( ',', $active_state );
2871
					} else {
2872
						$active_state = array();
2873
					}
2874
					$active_state[] = $module;
2875
					Jetpack::state( $state, implode( ',', $active_state ) );
2876
				}
2877
				continue;
2878
			}
2879
2880
			$file = Jetpack::get_module_path( $module );
2881
			if ( ! file_exists( $file ) ) {
2882
				continue;
2883
			}
2884
2885
			// we'll override this later if the plugin can be included without fatal error
2886
			if ( $redirect ) {
2887
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2888
			}
2889
2890
			if ( $send_state_messages ) {
2891
				Jetpack::state( 'error', 'module_activation_failed' );
2892
				Jetpack::state( 'module', $module );
2893
			}
2894
2895
			ob_start();
2896
			require_once $file;
2897
2898
			$active[] = $module;
2899
2900 View Code Duplication
			if ( $send_state_messages ) {
2901
2902
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2903
				if ( $active_state = Jetpack::state( $state ) ) {
2904
					$active_state = explode( ',', $active_state );
2905
				} else {
2906
					$active_state = array();
2907
				}
2908
				$active_state[] = $module;
2909
				Jetpack::state( $state, implode( ',', $active_state ) );
2910
			}
2911
2912
			Jetpack::update_active_modules( $active );
2913
2914
			ob_end_clean();
2915
		}
2916
2917
		if ( $send_state_messages ) {
2918
			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...
2919
			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...
2920
		}
2921
2922
		Jetpack::catch_errors( false );
2923
		/**
2924
		 * Fires when default modules are activated.
2925
		 *
2926
		 * @since 1.9.0
2927
		 *
2928
		 * @param string $min_version Minimum version number required to use modules.
2929
		 * @param string $max_version Maximum version number required to use modules.
2930
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2931
		 */
2932
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2933
	}
2934
2935
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2936
		/**
2937
		 * Fires before a module is activated.
2938
		 *
2939
		 * @since 2.6.0
2940
		 *
2941
		 * @param string $module Module slug.
2942
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2943
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2944
		 */
2945
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2946
2947
		$jetpack = Jetpack::init();
2948
2949
		if ( ! strlen( $module ) )
2950
			return false;
2951
2952
		if ( ! Jetpack::is_module( $module ) )
2953
			return false;
2954
2955
		// If it's already active, then don't do it again
2956
		$active = Jetpack::get_active_modules();
2957
		foreach ( $active as $act ) {
2958
			if ( $act == $module )
2959
				return true;
2960
		}
2961
2962
		$module_data = Jetpack::get_module( $module );
2963
2964
		if ( ! Jetpack::is_active() ) {
2965
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2966
				return false;
2967
2968
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2969
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2970
				return false;
2971
		}
2972
2973
		// Check and see if the old plugin is active
2974
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2975
			// Deactivate the old plugin
2976
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2977
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2978
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2979
				Jetpack::state( 'deactivated_plugins', $module );
2980
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2981
				exit;
2982
			}
2983
		}
2984
2985
		// Protect won't work with mis-configured IPs
2986
		if ( 'protect' === $module ) {
2987
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2988
			if ( ! jetpack_protect_get_ip() ) {
2989
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2990
				return false;
2991
			}
2992
		}
2993
2994
		if ( ! Jetpack_Plan::supports( $module ) ) {
2995
			return false;
2996
		}
2997
2998
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2999
		Jetpack::state( 'module', $module );
3000
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3001
3002
		Jetpack::catch_errors( true );
3003
		ob_start();
3004
		require Jetpack::get_module_path( $module );
3005
		/** This action is documented in class.jetpack.php */
3006
		do_action( 'jetpack_activate_module', $module );
3007
		$active[] = $module;
3008
		Jetpack::update_active_modules( $active );
3009
3010
		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...
3011
		ob_end_clean();
3012
		Jetpack::catch_errors( false );
3013
3014
		if ( $redirect ) {
3015
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3016
		}
3017
		if ( $exit ) {
3018
			exit;
3019
		}
3020
		return true;
3021
	}
3022
3023
	function activate_module_actions( $module ) {
3024
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3025
	}
3026
3027
	public static function deactivate_module( $module ) {
3028
		/**
3029
		 * Fires when a module is deactivated.
3030
		 *
3031
		 * @since 1.9.0
3032
		 *
3033
		 * @param string $module Module slug.
3034
		 */
3035
		do_action( 'jetpack_pre_deactivate_module', $module );
3036
3037
		$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...
3038
3039
		$active = Jetpack::get_active_modules();
3040
		$new    = array_filter( array_diff( $active, (array) $module ) );
3041
3042
		return self::update_active_modules( $new );
3043
	}
3044
3045
	public static function enable_module_configurable( $module ) {
3046
		$module = Jetpack::get_module_slug( $module );
3047
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3048
	}
3049
3050
	/**
3051
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3052
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3053
	 *
3054
	 * @param string $module Module slug
3055
	 * @return string $url module configuration URL
3056
	 */
3057
	public static function module_configuration_url( $module ) {
3058
		$module = Jetpack::get_module_slug( $module );
3059
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3060
		/**
3061
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3062
		 *
3063
		 * @since 6.9.0
3064
		 *
3065
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3066
		 */
3067
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3068
3069
		return $url;
3070
	}
3071
3072
/* Installation */
3073
	public static function bail_on_activation( $message, $deactivate = true ) {
3074
?>
3075
<!doctype html>
3076
<html>
3077
<head>
3078
<meta charset="<?php bloginfo( 'charset' ); ?>">
3079
<style>
3080
* {
3081
	text-align: center;
3082
	margin: 0;
3083
	padding: 0;
3084
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3085
}
3086
p {
3087
	margin-top: 1em;
3088
	font-size: 18px;
3089
}
3090
</style>
3091
<body>
3092
<p><?php echo esc_html( $message ); ?></p>
3093
</body>
3094
</html>
3095
<?php
3096
		if ( $deactivate ) {
3097
			$plugins = get_option( 'active_plugins' );
3098
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3099
			$update  = false;
3100
			foreach ( $plugins as $i => $plugin ) {
3101
				if ( $plugin === $jetpack ) {
3102
					$plugins[$i] = false;
3103
					$update = true;
3104
				}
3105
			}
3106
3107
			if ( $update ) {
3108
				update_option( 'active_plugins', array_filter( $plugins ) );
3109
			}
3110
		}
3111
		exit;
3112
	}
3113
3114
	/**
3115
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3116
	 * @static
3117
	 */
3118
	public static function plugin_activation( $network_wide ) {
3119
		Jetpack_Options::update_option( 'activated', 1 );
3120
3121
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3122
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3123
		}
3124
3125
		if ( $network_wide )
3126
			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...
3127
3128
		// For firing one-off events (notices) immediately after activation
3129
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3130
3131
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3132
3133
		Jetpack::plugin_initialize();
3134
	}
3135
3136
	public static function get_activation_source( $referer_url ) {
3137
3138
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3139
			return array( 'wp-cli', null );
3140
		}
3141
3142
		$referer = parse_url( $referer_url );
3143
3144
		$source_type = 'unknown';
3145
		$source_query = null;
3146
3147
		if ( ! is_array( $referer ) ) {
3148
			return array( $source_type, $source_query );
3149
		}
3150
3151
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3152
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3153
3154
		if ( isset( $referer['query'] ) ) {
3155
			parse_str( $referer['query'], $query_parts );
3156
		} else {
3157
			$query_parts = array();
3158
		}
3159
3160
		if ( $plugins_path === $referer['path'] ) {
3161
			$source_type = 'list';
3162
		} elseif ( $plugins_install_path === $referer['path'] ) {
3163
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3164
			switch( $tab ) {
3165
				case 'popular':
3166
					$source_type = 'popular';
3167
					break;
3168
				case 'recommended':
3169
					$source_type = 'recommended';
3170
					break;
3171
				case 'favorites':
3172
					$source_type = 'favorites';
3173
					break;
3174
				case 'search':
3175
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3176
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3177
					break;
3178
				default:
3179
					$source_type = 'featured';
3180
			}
3181
		}
3182
3183
		return array( $source_type, $source_query );
3184
	}
3185
3186
	/**
3187
	 * Runs before bumping version numbers up to a new version
3188
	 * @param  string $version    Version:timestamp
3189
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3190
	 * @return null              [description]
3191
	 */
3192
	public static function do_version_bump( $version, $old_version ) {
3193
		if ( ! $old_version ) { // For new sites
3194
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3195
		}
3196
	}
3197
3198
	/**
3199
	 * Sets the internal version number and activation state.
3200
	 * @static
3201
	 */
3202
	public static function plugin_initialize() {
3203
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3204
			Jetpack_Options::update_option( 'activated', 2 );
3205
		}
3206
3207 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3208
			$version = $old_version = JETPACK__VERSION . ':' . time();
3209
			/** This action is documented in class.jetpack.php */
3210
			do_action( 'updating_jetpack_version', $version, false );
3211
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3212
		}
3213
3214
		Jetpack::load_modules();
3215
3216
		Jetpack_Options::delete_option( 'do_activate' );
3217
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3218
	}
3219
3220
	/**
3221
	 * Removes all connection options
3222
	 * @static
3223
	 */
3224
	public static function plugin_deactivation( ) {
3225
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3226
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3227
			Jetpack_Network::init()->deactivate();
3228
		} else {
3229
			Jetpack::disconnect( false );
3230
			//Jetpack_Heartbeat::init()->deactivate();
3231
		}
3232
	}
3233
3234
	/**
3235
	 * Disconnects from the Jetpack servers.
3236
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3237
	 * @static
3238
	 */
3239
	public static function disconnect( $update_activated_state = true ) {
3240
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3241
		$connection = self::connection();
3242
		$connection->clean_nonces( true );
3243
3244
		// If the site is in an IDC because sync is not allowed,
3245
		// let's make sure to not disconnect the production site.
3246
		if ( ! self::validate_sync_error_idc_option() ) {
3247
			$tracking = new Tracking();
3248
			$tracking->record_user_event( 'disconnect_site', array() );
3249
3250
			$xml = new Jetpack_IXR_Client();
3251
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3252
		}
3253
3254
		Jetpack_Options::delete_option(
3255
			array(
3256
				'blog_token',
3257
				'user_token',
3258
				'user_tokens',
3259
				'master_user',
3260
				'time_diff',
3261
				'fallback_no_verify_ssl_certs',
3262
			)
3263
		);
3264
3265
		Jetpack_IDC::clear_all_idc_options();
3266
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3267
3268
		if ( $update_activated_state ) {
3269
			Jetpack_Options::update_option( 'activated', 4 );
3270
		}
3271
3272
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3273
			// Check then record unique disconnection if site has never been disconnected previously
3274
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3275
				$jetpack_unique_connection['disconnected'] = 1;
3276
			} else {
3277
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3278
					//track unique disconnect
3279
					$jetpack = Jetpack::init();
3280
3281
					$jetpack->stat( 'connections', 'unique-disconnect' );
3282
					$jetpack->do_stats( 'server_side' );
3283
				}
3284
				// increment number of times disconnected
3285
				$jetpack_unique_connection['disconnected'] += 1;
3286
			}
3287
3288
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3289
		}
3290
3291
		// Delete cached connected user data
3292
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3293
		delete_transient( $transient_key );
3294
3295
		// Delete all the sync related data. Since it could be taking up space.
3296
		Sender::get_instance()->uninstall();
3297
3298
		// Disable the Heartbeat cron
3299
		Jetpack_Heartbeat::init()->deactivate();
3300
	}
3301
3302
	/**
3303
	 * Unlinks the current user from the linked WordPress.com user.
3304
	 *
3305
	 * @deprecated since 7.7
3306
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3307
	 *
3308
	 * @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...
3309
	 * @return Boolean Whether the disconnection of the user was successful.
3310
	 */
3311
	public static function unlink_user( $user_id = null ) {
3312
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3313
		return Connection_Manager::disconnect_user( $user_id );
3314
	}
3315
3316
	/**
3317
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3318
	 */
3319
	public static function try_registration() {
3320
		// The user has agreed to the TOS at some point by now.
3321
		Jetpack_Options::update_option( 'tos_agreed', true );
3322
3323
		// Let's get some testing in beta versions and such.
3324
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3325
			// Before attempting to connect, let's make sure that the domains are viable.
3326
			$domains_to_check = array_unique( array(
3327
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3328
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3329
			) );
3330
			foreach ( $domains_to_check as $domain ) {
3331
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3330 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...
3332
				if ( is_wp_error( $result ) ) {
3333
					return $result;
3334
				}
3335
			}
3336
		}
3337
3338
		$result = Jetpack::register();
3339
3340
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3341
		if ( ! $result || is_wp_error( $result ) ) {
3342
			return $result;
3343
		} else {
3344
			return true;
3345
		}
3346
	}
3347
3348
	/**
3349
	 * Tracking an internal event log. Try not to put too much chaff in here.
3350
	 *
3351
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3352
	 */
3353
	public static function log( $code, $data = null ) {
3354
		// only grab the latest 200 entries
3355
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3356
3357
		// Append our event to the log
3358
		$log_entry = array(
3359
			'time'    => time(),
3360
			'user_id' => get_current_user_id(),
3361
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3362
			'code'    => $code,
3363
		);
3364
		// Don't bother storing it unless we've got some.
3365
		if ( ! is_null( $data ) ) {
3366
			$log_entry['data'] = $data;
3367
		}
3368
		$log[] = $log_entry;
3369
3370
		// Try add_option first, to make sure it's not autoloaded.
3371
		// @todo: Add an add_option method to Jetpack_Options
3372
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3373
			Jetpack_Options::update_option( 'log', $log );
3374
		}
3375
3376
		/**
3377
		 * Fires when Jetpack logs an internal event.
3378
		 *
3379
		 * @since 3.0.0
3380
		 *
3381
		 * @param array $log_entry {
3382
		 *	Array of details about the log entry.
3383
		 *
3384
		 *	@param string time Time of the event.
3385
		 *	@param int user_id ID of the user who trigerred the event.
3386
		 *	@param int blog_id Jetpack Blog ID.
3387
		 *	@param string code Unique name for the event.
3388
		 *	@param string data Data about the event.
3389
		 * }
3390
		 */
3391
		do_action( 'jetpack_log_entry', $log_entry );
3392
	}
3393
3394
	/**
3395
	 * Get the internal event log.
3396
	 *
3397
	 * @param $event (string) - only return the specific log events
3398
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3399
	 *
3400
	 * @return array of log events || WP_Error for invalid params
3401
	 */
3402
	public static function get_log( $event = false, $num = false ) {
3403
		if ( $event && ! is_string( $event ) ) {
3404
			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...
3405
		}
3406
3407
		if ( $num && ! is_numeric( $num ) ) {
3408
			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...
3409
		}
3410
3411
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3412
3413
		// If nothing set - act as it did before, otherwise let's start customizing the output
3414
		if ( ! $num && ! $event ) {
3415
			return $entire_log;
3416
		} else {
3417
			$entire_log = array_reverse( $entire_log );
3418
		}
3419
3420
		$custom_log_output = array();
3421
3422
		if ( $event ) {
3423
			foreach ( $entire_log as $log_event ) {
3424
				if ( $event == $log_event[ 'code' ] ) {
3425
					$custom_log_output[] = $log_event;
3426
				}
3427
			}
3428
		} else {
3429
			$custom_log_output = $entire_log;
3430
		}
3431
3432
		if ( $num ) {
3433
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3434
		}
3435
3436
		return $custom_log_output;
3437
	}
3438
3439
	/**
3440
	 * Log modification of important settings.
3441
	 */
3442
	public static function log_settings_change( $option, $old_value, $value ) {
3443
		switch( $option ) {
3444
			case 'jetpack_sync_non_public_post_stati':
3445
				self::log( $option, $value );
3446
				break;
3447
		}
3448
	}
3449
3450
	/**
3451
	 * Return stat data for WPCOM sync
3452
	 */
3453
	public static function get_stat_data( $encode = true, $extended = true ) {
3454
		$data = Jetpack_Heartbeat::generate_stats_array();
3455
3456
		if ( $extended ) {
3457
			$additional_data = self::get_additional_stat_data();
3458
			$data = array_merge( $data, $additional_data );
3459
		}
3460
3461
		if ( $encode ) {
3462
			return json_encode( $data );
3463
		}
3464
3465
		return $data;
3466
	}
3467
3468
	/**
3469
	 * Get additional stat data to sync to WPCOM
3470
	 */
3471
	public static function get_additional_stat_data( $prefix = '' ) {
3472
		$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...
3473
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3474
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3475
		$return["{$prefix}site-count"]     = 0;
3476
3477
		if ( function_exists( 'get_blog_count' ) ) {
3478
			$return["{$prefix}site-count"] = get_blog_count();
3479
		}
3480
		return $return;
3481
	}
3482
3483
	private static function get_site_user_count() {
3484
		global $wpdb;
3485
3486
		if ( function_exists( 'wp_is_large_network' ) ) {
3487
			if ( wp_is_large_network( 'users' ) ) {
3488
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3489
			}
3490
		}
3491
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3492
			// It wasn't there, so regenerate the data and save the transient
3493
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3494
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3495
		}
3496
		return $user_count;
3497
	}
3498
3499
	/* Admin Pages */
3500
3501
	function admin_init() {
3502
		// If the plugin is not connected, display a connect message.
3503
		if (
3504
			// the plugin was auto-activated and needs its candy
3505
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3506
		||
3507
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3508
			! Jetpack_Options::get_option( 'activated' )
3509
		) {
3510
			Jetpack::plugin_initialize();
3511
		}
3512
3513
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3514
			Jetpack_Connection_Banner::init();
3515
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3516
			// Upgrade: 1.1 -> 1.1.1
3517
			// Check and see if host can verify the Jetpack servers' SSL certificate
3518
			$args = array();
3519
			$connection = self::connection();
3520
			Client::_wp_remote_request(
3521
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3522
				$args,
3523
				true
3524
			);
3525
		}
3526
3527
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3528
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3529
		}
3530
3531
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3532
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3533
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3534
3535
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3536
			// Artificially throw errors in certain whitelisted cases during plugin activation
3537
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3538
		}
3539
3540
		// Add custom column in wp-admin/users.php to show whether user is linked.
3541
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3542
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3543
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3544
	}
3545
3546
	function admin_body_class( $admin_body_class = '' ) {
3547
		$classes = explode( ' ', trim( $admin_body_class ) );
3548
3549
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3550
3551
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3552
		return " $admin_body_class ";
3553
	}
3554
3555
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3556
		return $admin_body_class . ' jetpack-pagestyles ';
3557
	}
3558
3559
	/**
3560
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3561
	 * This function artificially throws errors for such cases (whitelisted).
3562
	 *
3563
	 * @param string $plugin The activated plugin.
3564
	 */
3565
	function throw_error_on_activate_plugin( $plugin ) {
3566
		$active_modules = Jetpack::get_active_modules();
3567
3568
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3569
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3570
			$throw = false;
3571
3572
			// Try and make sure it really was the stats plugin
3573
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3574
				if ( 'stats.php' == basename( $plugin ) ) {
3575
					$throw = true;
3576
				}
3577
			} else {
3578
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3579
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3580
					$throw = true;
3581
				}
3582
			}
3583
3584
			if ( $throw ) {
3585
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3586
			}
3587
		}
3588
	}
3589
3590
	function intercept_plugin_error_scrape_init() {
3591
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3592
	}
3593
3594
	function intercept_plugin_error_scrape( $action, $result ) {
3595
		if ( ! $result ) {
3596
			return;
3597
		}
3598
3599
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3600
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3601
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3602
			}
3603
		}
3604
	}
3605
3606
	/**
3607
	 * Register the remote file upload request handlers, if needed.
3608
	 *
3609
	 * @access public
3610
	 */
3611
	public function add_remote_request_handlers() {
3612
		// Remote file uploads are allowed only via AJAX requests.
3613
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3614
			return;
3615
		}
3616
3617
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3618
		$remote_request_actions = array(
3619
			'jetpack_upload_file',
3620
			'jetpack_update_file',
3621
		);
3622
3623
		// phpcs:ignore WordPress.Security.NonceVerification
3624
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3625
			return;
3626
		}
3627
3628
		// Require Jetpack authentication for the remote file upload AJAX requests.
3629
		$this->connection_manager->require_jetpack_authentication();
3630
3631
		// Register the remote file upload AJAX handlers.
3632
		foreach ( $remote_request_actions as $action ) {
3633
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3634
		}
3635
	}
3636
3637
	/**
3638
	 * Handler for Jetpack remote file uploads.
3639
	 *
3640
	 * @access public
3641
	 */
3642
	public function remote_request_handlers() {
3643
		$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...
3644
3645
		switch ( current_filter() ) {
3646
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3647
			$response = $this->upload_handler();
3648
			break;
3649
3650
		case 'wp_ajax_nopriv_jetpack_update_file' :
3651
			$response = $this->upload_handler( true );
3652
			break;
3653
		default :
3654
			$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...
3655
			break;
3656
		}
3657
3658
		if ( ! $response ) {
3659
			$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...
3660
		}
3661
3662
		if ( is_wp_error( $response ) ) {
3663
			$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...
3664
			$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...
3665
			$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...
3666
3667
			if ( ! is_int( $status_code ) ) {
3668
				$status_code = 400;
3669
			}
3670
3671
			status_header( $status_code );
3672
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3673
		}
3674
3675
		status_header( 200 );
3676
		if ( true === $response ) {
3677
			exit;
3678
		}
3679
3680
		die( json_encode( (object) $response ) );
3681
	}
3682
3683
	/**
3684
	 * Uploads a file gotten from the global $_FILES.
3685
	 * If `$update_media_item` is true and `post_id` is defined
3686
	 * the attachment file of the media item (gotten through of the post_id)
3687
	 * will be updated instead of add a new one.
3688
	 *
3689
	 * @param  boolean $update_media_item - update media attachment
3690
	 * @return array - An array describing the uploadind files process
3691
	 */
3692
	function upload_handler( $update_media_item = false ) {
3693
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3694
			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...
3695
		}
3696
3697
		$user = wp_authenticate( '', '' );
3698
		if ( ! $user || is_wp_error( $user ) ) {
3699
			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...
3700
		}
3701
3702
		wp_set_current_user( $user->ID );
3703
3704
		if ( ! current_user_can( 'upload_files' ) ) {
3705
			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...
3706
		}
3707
3708
		if ( empty( $_FILES ) ) {
3709
			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...
3710
		}
3711
3712
		foreach ( array_keys( $_FILES ) as $files_key ) {
3713
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3714
				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...
3715
			}
3716
		}
3717
3718
		$media_keys = array_keys( $_FILES['media'] );
3719
3720
		$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...
3721
		if ( ! $token || is_wp_error( $token ) ) {
3722
			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...
3723
		}
3724
3725
		$uploaded_files = array();
3726
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3727
		unset( $GLOBALS['post'] );
3728
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3729
			$file = array();
3730
			foreach ( $media_keys as $media_key ) {
3731
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3732
			}
3733
3734
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3735
3736
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3737
			if ( $hmac_provided !== $hmac_file ) {
3738
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3739
				continue;
3740
			}
3741
3742
			$_FILES['.jetpack.upload.'] = $file;
3743
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3744
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3745
				$post_id = 0;
3746
			}
3747
3748
			if ( $update_media_item ) {
3749
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3750
					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...
3751
				}
3752
3753
				$media_array = $_FILES['media'];
3754
3755
				$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...
3756
				$file_array['type'] = $media_array['type'][0];
3757
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3758
				$file_array['error'] = $media_array['error'][0];
3759
				$file_array['size'] = $media_array['size'][0];
3760
3761
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3762
3763
				if ( is_wp_error( $edited_media_item ) ) {
3764
					return $edited_media_item;
3765
				}
3766
3767
				$response = (object) array(
3768
					'id'   => (string) $post_id,
3769
					'file' => (string) $edited_media_item->post_title,
3770
					'url'  => (string) wp_get_attachment_url( $post_id ),
3771
					'type' => (string) $edited_media_item->post_mime_type,
3772
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3773
				);
3774
3775
				return (array) array( $response );
3776
			}
3777
3778
			$attachment_id = media_handle_upload(
3779
				'.jetpack.upload.',
3780
				$post_id,
3781
				array(),
3782
				array(
3783
					'action' => 'jetpack_upload_file',
3784
				)
3785
			);
3786
3787
			if ( ! $attachment_id ) {
3788
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3789
			} elseif ( is_wp_error( $attachment_id ) ) {
3790
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3791
			} else {
3792
				$attachment = get_post( $attachment_id );
3793
				$uploaded_files[$index] = (object) array(
3794
					'id'   => (string) $attachment_id,
3795
					'file' => $attachment->post_title,
3796
					'url'  => wp_get_attachment_url( $attachment_id ),
3797
					'type' => $attachment->post_mime_type,
3798
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3799
				);
3800
				// Zip files uploads are not supported unless they are done for installation purposed
3801
				// lets delete them in case something goes wrong in this whole process
3802
				if ( 'application/zip' === $attachment->post_mime_type ) {
3803
					// Schedule a cleanup for 2 hours from now in case of failed install.
3804
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3805
				}
3806
			}
3807
		}
3808
		if ( ! is_null( $global_post ) ) {
3809
			$GLOBALS['post'] = $global_post;
3810
		}
3811
3812
		return $uploaded_files;
3813
	}
3814
3815
	/**
3816
	 * Add help to the Jetpack page
3817
	 *
3818
	 * @since Jetpack (1.2.3)
3819
	 * @return false if not the Jetpack page
3820
	 */
3821
	function admin_help() {
3822
		$current_screen = get_current_screen();
3823
3824
		// Overview
3825
		$current_screen->add_help_tab(
3826
			array(
3827
				'id'		=> 'home',
3828
				'title'		=> __( 'Home', 'jetpack' ),
3829
				'content'	=>
3830
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3831
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3832
					'<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>',
3833
			)
3834
		);
3835
3836
		// Screen Content
3837
		if ( current_user_can( 'manage_options' ) ) {
3838
			$current_screen->add_help_tab(
3839
				array(
3840
					'id'		=> 'settings',
3841
					'title'		=> __( 'Settings', 'jetpack' ),
3842
					'content'	=>
3843
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3844
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3845
						'<ol>' .
3846
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3847
							'<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>' .
3848
						'</ol>' .
3849
						'<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>'
3850
				)
3851
			);
3852
		}
3853
3854
		// Help Sidebar
3855
		$current_screen->set_help_sidebar(
3856
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3857
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3858
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3859
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3860
		);
3861
	}
3862
3863
	function admin_menu_css() {
3864
		wp_enqueue_style( 'jetpack-icons' );
3865
	}
3866
3867
	function admin_menu_order() {
3868
		return true;
3869
	}
3870
3871 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3872
		$jp_menu_order = array();
3873
3874
		foreach ( $menu_order as $index => $item ) {
3875
			if ( $item != 'jetpack' ) {
3876
				$jp_menu_order[] = $item;
3877
			}
3878
3879
			if ( $index == 0 ) {
3880
				$jp_menu_order[] = 'jetpack';
3881
			}
3882
		}
3883
3884
		return $jp_menu_order;
3885
	}
3886
3887
	function admin_banner_styles() {
3888
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3889
3890
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3891
			wp_register_style(
3892
				'jetpack-dops-style',
3893
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3894
				array(),
3895
				JETPACK__VERSION
3896
			);
3897
		}
3898
3899
		wp_enqueue_style(
3900
			'jetpack',
3901
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3902
			array( 'jetpack-dops-style' ),
3903
			 JETPACK__VERSION . '-20121016'
3904
		);
3905
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3906
		wp_style_add_data( 'jetpack', 'suffix', $min );
3907
	}
3908
3909
	function plugin_action_links( $actions ) {
3910
3911
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3912
3913
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3914
			return array_merge(
3915
				$jetpack_home,
3916
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3917
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3918
				$actions
3919
				);
3920
			}
3921
3922
		return array_merge( $jetpack_home, $actions );
3923
	}
3924
3925
	/*
3926
	 * Registration flow:
3927
	 * 1 - ::admin_page_load() action=register
3928
	 * 2 - ::try_registration()
3929
	 * 3 - ::register()
3930
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3931
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3932
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3933
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3934
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3935
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3936
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3937
	 *       jetpack_id, jetpack_secret, jetpack_public
3938
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3939
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3940
	 * 5 - user logs in with WP.com account
3941
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3942
	 *		- Jetpack_Client_Server::authorize()
3943
	 *		- Jetpack_Client_Server::get_token()
3944
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3945
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3946
	 *			- which responds with access_token, token_type, scope
3947
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3948
	 *		- Jetpack::activate_default_modules()
3949
	 *     		- Deactivates deprecated plugins
3950
	 *     		- Activates all default modules
3951
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3952
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3953
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3954
	 *     Done!
3955
	 */
3956
3957
	/**
3958
	 * Handles the page load events for the Jetpack admin page
3959
	 */
3960
	function admin_page_load() {
3961
		$error = false;
3962
3963
		// Make sure we have the right body class to hook stylings for subpages off of.
3964
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3965
3966
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3967
			// Should only be used in intermediate redirects to preserve state across redirects
3968
			Jetpack::restate();
3969
		}
3970
3971
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3972
			// @todo: Add validation against a known whitelist
3973
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3974
			// User clicked in the iframe to link their accounts
3975
			if ( ! Jetpack::is_user_connected() ) {
3976
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3977
3978
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3979
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3980
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3981
3982
				if ( isset( $_GET['notes_iframe'] ) )
3983
					$connect_url .= '&notes_iframe';
3984
				wp_redirect( $connect_url );
3985
				exit;
3986
			} else {
3987
				if ( ! isset( $_GET['calypso_env'] ) ) {
3988
					Jetpack::state( 'message', 'already_authorized' );
3989
					wp_safe_redirect( Jetpack::admin_url() );
3990
					exit;
3991
				} else {
3992
					$connect_url = $this->build_connect_url( true, false, $from );
3993
					$connect_url .= '&already_authorized=true';
3994
					wp_redirect( $connect_url );
3995
					exit;
3996
				}
3997
			}
3998
		}
3999
4000
4001
		if ( isset( $_GET['action'] ) ) {
4002
			switch ( $_GET['action'] ) {
4003
			case 'authorize':
4004
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4005
					Jetpack::state( 'message', 'already_authorized' );
4006
					wp_safe_redirect( Jetpack::admin_url() );
4007
					exit;
4008
				}
4009
				Jetpack::log( 'authorize' );
4010
				$client_server = new Jetpack_Client_Server;
4011
				$client_server->client_authorize();
4012
				exit;
4013
			case 'register' :
4014
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4015
					$error = 'cheatin';
4016
					break;
4017
				}
4018
				check_admin_referer( 'jetpack-register' );
4019
				Jetpack::log( 'register' );
4020
				Jetpack::maybe_set_version_option();
4021
				$registered = Jetpack::try_registration();
4022
				if ( is_wp_error( $registered ) ) {
4023
					$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...
4024
					Jetpack::state( 'error', $error );
4025
					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...
4026
4027
					/**
4028
					 * Jetpack registration Error.
4029
					 *
4030
					 * @since 7.5.0
4031
					 *
4032
					 * @param string|int $error The error code.
4033
					 * @param \WP_Error $registered The error object.
4034
					 */
4035
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4036
					break;
4037
				}
4038
4039
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4040
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4041
4042
				/**
4043
				 * Jetpack registration Success.
4044
				 *
4045
				 * @since 7.5.0
4046
				 *
4047
				 * @param string $from 'from' GET parameter;
4048
				 */
4049
				do_action( 'jetpack_connection_register_success', $from );
4050
4051
				$url = $this->build_connect_url( true, $redirect, $from );
4052
4053
				if ( ! empty( $_GET['onboarding'] ) ) {
4054
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4055
				}
4056
4057
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4058
					$url = add_query_arg( 'auth_approved', 'true', $url );
4059
				}
4060
4061
				wp_redirect( $url );
4062
				exit;
4063
			case 'activate' :
4064
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4065
					$error = 'cheatin';
4066
					break;
4067
				}
4068
4069
				$module = stripslashes( $_GET['module'] );
4070
				check_admin_referer( "jetpack_activate-$module" );
4071
				Jetpack::log( 'activate', $module );
4072
				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...
4073
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4074
				}
4075
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4076
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4077
				exit;
4078
			case 'activate_default_modules' :
4079
				check_admin_referer( 'activate_default_modules' );
4080
				Jetpack::log( 'activate_default_modules' );
4081
				Jetpack::restate();
4082
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4083
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4084
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4085
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4086
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4087
				exit;
4088
			case 'disconnect' :
4089
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4090
					$error = 'cheatin';
4091
					break;
4092
				}
4093
4094
				check_admin_referer( 'jetpack-disconnect' );
4095
				Jetpack::log( 'disconnect' );
4096
				Jetpack::disconnect();
4097
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4098
				exit;
4099
			case 'reconnect' :
4100
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4101
					$error = 'cheatin';
4102
					break;
4103
				}
4104
4105
				check_admin_referer( 'jetpack-reconnect' );
4106
				Jetpack::log( 'reconnect' );
4107
				$this->disconnect();
4108
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4109
				exit;
4110 View Code Duplication
			case 'deactivate' :
4111
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4112
					$error = 'cheatin';
4113
					break;
4114
				}
4115
4116
				$modules = stripslashes( $_GET['module'] );
4117
				check_admin_referer( "jetpack_deactivate-$modules" );
4118
				foreach ( explode( ',', $modules ) as $module ) {
4119
					Jetpack::log( 'deactivate', $module );
4120
					Jetpack::deactivate_module( $module );
4121
					Jetpack::state( 'message', 'module_deactivated' );
4122
				}
4123
				Jetpack::state( 'module', $modules );
4124
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4125
				exit;
4126
			case 'unlink' :
4127
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4128
				check_admin_referer( 'jetpack-unlink' );
4129
				Jetpack::log( 'unlink' );
4130
				Connection_Manager::disconnect_user();
4131
				Jetpack::state( 'message', 'unlinked' );
4132
				if ( 'sub-unlink' == $redirect ) {
4133
					wp_safe_redirect( admin_url() );
4134
				} else {
4135
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4136
				}
4137
				exit;
4138
			case 'onboard' :
4139
				if ( ! current_user_can( 'manage_options' ) ) {
4140
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4141
				} else {
4142
					Jetpack::create_onboarding_token();
4143
					$url = $this->build_connect_url( true );
4144
4145
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4146
						$url = add_query_arg( 'onboarding', $token, $url );
4147
					}
4148
4149
					$calypso_env = $this->get_calypso_env();
4150
					if ( ! empty( $calypso_env ) ) {
4151
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4152
					}
4153
4154
					wp_redirect( $url );
4155
					exit;
4156
				}
4157
				exit;
4158
			default:
4159
				/**
4160
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4161
				 *
4162
				 * @since 2.6.0
4163
				 *
4164
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4165
				 */
4166
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4167
			}
4168
		}
4169
4170
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4171
			self::activate_new_modules( true );
4172
		}
4173
4174
		$message_code = Jetpack::state( 'message' );
4175
		if ( Jetpack::state( 'optin-manage' ) ) {
4176
			$activated_manage = $message_code;
4177
			$message_code = 'jetpack-manage';
4178
		}
4179
4180
		switch ( $message_code ) {
4181
		case 'jetpack-manage':
4182
			$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>';
4183
			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...
4184
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4185
			}
4186
			break;
4187
4188
		}
4189
4190
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4191
4192
		if ( ! empty( $deactivated_plugins ) ) {
4193
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4194
			$deactivated_titles  = array();
4195
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4196
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4197
					continue;
4198
				}
4199
4200
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4201
			}
4202
4203
			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...
4204
				if ( $this->message ) {
4205
					$this->message .= "<br /><br />\n";
4206
				}
4207
4208
				$this->message .= wp_sprintf(
4209
					_n(
4210
						'Jetpack contains the most recent version of the old %l plugin.',
4211
						'Jetpack contains the most recent versions of the old %l plugins.',
4212
						count( $deactivated_titles ),
4213
						'jetpack'
4214
					),
4215
					$deactivated_titles
4216
				);
4217
4218
				$this->message .= "<br />\n";
4219
4220
				$this->message .= _n(
4221
					'The old version has been deactivated and can be removed from your site.',
4222
					'The old versions have been deactivated and can be removed from your site.',
4223
					count( $deactivated_titles ),
4224
					'jetpack'
4225
				);
4226
			}
4227
		}
4228
4229
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4230
4231
		if ( $this->message || $this->error || $this->privacy_checks ) {
4232
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4233
		}
4234
4235
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4236
	}
4237
4238
	function admin_notices() {
4239
4240
		if ( $this->error ) {
4241
?>
4242
<div id="message" class="jetpack-message jetpack-err">
4243
	<div class="squeezer">
4244
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4245
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4246
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4247
<?php	endif; ?>
4248
	</div>
4249
</div>
4250
<?php
4251
		}
4252
4253
		if ( $this->message ) {
4254
?>
4255
<div id="message" class="jetpack-message">
4256
	<div class="squeezer">
4257
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4258
	</div>
4259
</div>
4260
<?php
4261
		}
4262
4263
		if ( $this->privacy_checks ) :
4264
			$module_names = $module_slugs = array();
4265
4266
			$privacy_checks = explode( ',', $this->privacy_checks );
4267
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4268
			foreach ( $privacy_checks as $module_slug ) {
4269
				$module = Jetpack::get_module( $module_slug );
4270
				if ( ! $module ) {
4271
					continue;
4272
				}
4273
4274
				$module_slugs[] = $module_slug;
4275
				$module_names[] = "<strong>{$module['name']}</strong>";
4276
			}
4277
4278
			$module_slugs = join( ',', $module_slugs );
4279
?>
4280
<div id="message" class="jetpack-message jetpack-err">
4281
	<div class="squeezer">
4282
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4283
		<p><?php
4284
			echo wp_kses(
4285
				wptexturize(
4286
					wp_sprintf(
4287
						_nx(
4288
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4289
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4290
							count( $privacy_checks ),
4291
							'%l = list of Jetpack module/feature names',
4292
							'jetpack'
4293
						),
4294
						$module_names
4295
					)
4296
				),
4297
				array( 'strong' => true )
4298
			);
4299
4300
			echo "\n<br />\n";
4301
4302
			echo wp_kses(
4303
				sprintf(
4304
					_nx(
4305
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4306
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4307
						count( $privacy_checks ),
4308
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4309
						'jetpack'
4310
					),
4311
					wp_nonce_url(
4312
						Jetpack::admin_url(
4313
							array(
4314
								'page'   => 'jetpack',
4315
								'action' => 'deactivate',
4316
								'module' => urlencode( $module_slugs ),
4317
							)
4318
						),
4319
						"jetpack_deactivate-$module_slugs"
4320
					),
4321
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4322
				),
4323
				array( 'a' => array( 'href' => true, 'title' => true ) )
4324
			);
4325
		?></p>
4326
	</div>
4327
</div>
4328
<?php endif;
4329
	}
4330
4331
	/**
4332
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4333
	 */
4334
	function stat( $group, $detail ) {
4335
		if ( ! isset( $this->stats[ $group ] ) )
4336
			$this->stats[ $group ] = array();
4337
		$this->stats[ $group ][] = $detail;
4338
	}
4339
4340
	/**
4341
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4342
	 */
4343
	function do_stats( $method = '' ) {
4344
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4345
			foreach ( $this->stats as $group => $stats ) {
4346
				if ( is_array( $stats ) && count( $stats ) ) {
4347
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4348
					if ( 'server_side' === $method ) {
4349
						self::do_server_side_stat( $args );
4350
					} else {
4351
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4352
					}
4353
				}
4354
				unset( $this->stats[ $group ] );
4355
			}
4356
		}
4357
	}
4358
4359
	/**
4360
	 * Runs stats code for a one-off, server-side.
4361
	 *
4362
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4363
	 *
4364
	 * @return bool If it worked.
4365
	 */
4366
	static function do_server_side_stat( $args ) {
4367
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4368
		if ( is_wp_error( $response ) )
4369
			return false;
4370
4371
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4372
			return false;
4373
4374
		return true;
4375
	}
4376
4377
	/**
4378
	 * Builds the stats url.
4379
	 *
4380
	 * @param $args array|string The arguments to append to the URL.
4381
	 *
4382
	 * @return string The URL to be pinged.
4383
	 */
4384
	static function build_stats_url( $args ) {
4385
		$defaults = array(
4386
			'v'    => 'wpcom2',
4387
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4388
		);
4389
		$args     = wp_parse_args( $args, $defaults );
4390
		/**
4391
		 * Filter the URL used as the Stats tracking pixel.
4392
		 *
4393
		 * @since 2.3.2
4394
		 *
4395
		 * @param string $url Base URL used as the Stats tracking pixel.
4396
		 */
4397
		$base_url = apply_filters(
4398
			'jetpack_stats_base_url',
4399
			'https://pixel.wp.com/g.gif'
4400
		);
4401
		$url      = add_query_arg( $args, $base_url );
4402
		return $url;
4403
	}
4404
4405
	/**
4406
	 * Get the role of the current user.
4407
	 *
4408
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4409
	 *
4410
	 * @access public
4411
	 * @static
4412
	 *
4413
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4414
	 */
4415
	public static function translate_current_user_to_role() {
4416
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4417
4418
		$roles = new Roles();
4419
		return $roles->translate_current_user_to_role();
4420
	}
4421
4422
	/**
4423
	 * Get the role of a particular user.
4424
	 *
4425
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4426
	 *
4427
	 * @access public
4428
	 * @static
4429
	 *
4430
	 * @param \WP_User $user User object.
4431
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4432
	 */
4433
	public static function translate_user_to_role( $user ) {
4434
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4435
4436
		$roles = new Roles();
4437
		return $roles->translate_user_to_role( $user );
4438
	}
4439
4440
	/**
4441
	 * Get the minimum capability for a role.
4442
	 *
4443
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4444
	 *
4445
	 * @access public
4446
	 * @static
4447
	 *
4448
	 * @param string $role Role name.
4449
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4450
	 */
4451
	public static function translate_role_to_cap( $role ) {
4452
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4453
4454
		$roles = new Roles();
4455
		return $roles->translate_role_to_cap( $role );
4456
	}
4457
4458
	/**
4459
	 * Sign a user role with the master access token.
4460
	 * If not specified, will default to the current user.
4461
	 *
4462
	 * @deprecated since 7.7
4463
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4464
	 *
4465
	 * @access public
4466
	 * @static
4467
	 *
4468
	 * @param string $role    User role.
4469
	 * @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...
4470
	 * @return string Signed user role.
4471
	 */
4472
	public static function sign_role( $role, $user_id = null ) {
4473
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4474
		return self::connection()->sign_role( $role, $user_id );
4475
	}
4476
4477
	/**
4478
	 * Builds a URL to the Jetpack connection auth page
4479
	 *
4480
	 * @since 3.9.5
4481
	 *
4482
	 * @param bool $raw If true, URL will not be escaped.
4483
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4484
	 *                              If string, will be a custom redirect.
4485
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4486
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4487
	 *
4488
	 * @return string Connect URL
4489
	 */
4490
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4491
		$site_id = Jetpack_Options::get_option( 'id' );
4492
		$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...
4493
4494
		if ( $register || ! $blog_token || ! $site_id ) {
4495
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4496
4497
			if ( ! empty( $redirect ) ) {
4498
				$url = add_query_arg(
4499
					'redirect',
4500
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4501
					$url
4502
				);
4503
			}
4504
4505
			if( is_network_admin() ) {
4506
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4507
			}
4508
		} else {
4509
4510
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4511
			// because otherwise this logic can get us in to a loop.
4512
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4513
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4514
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4515
4516
				$response = Client::wpcom_json_api_request_as_blog(
4517
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4518
					'1.1'
4519
				);
4520
4521
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4522
4523
					// Generating a register URL instead to refresh the existing token
4524
					return $this->build_connect_url( $raw, $redirect, $from, true );
4525
				}
4526
			}
4527
4528
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4490 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...
4529
		}
4530
4531
		if ( $from ) {
4532
			$url = add_query_arg( 'from', $from, $url );
4533
		}
4534
4535
		// Ensure that class to get the affiliate code is loaded
4536
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4537
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4538
		}
4539
		// Get affiliate code and add it to the URL
4540
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4541
4542
		$calypso_env = $this->get_calypso_env();
4543
4544
		if ( ! empty( $calypso_env ) ) {
4545
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4546
		}
4547
4548
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4549
	}
4550
4551
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4552
		if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4553
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4554
		}
4555
4556
		$roles       = new Roles();
4557
		$role        = $roles->translate_current_user_to_role();
4558
		$signed_role = self::connection()->sign_role( $role );
4559
4560
		$user = wp_get_current_user();
4561
4562
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4563
		$redirect = $redirect
4564
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4565
			: $jetpack_admin_page;
4566
4567
		if( isset( $_REQUEST['is_multisite'] ) ) {
4568
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4569
		}
4570
4571
		$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4572
4573
		/**
4574
		 * Filter the type of authorization.
4575
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4576
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4577
		 *
4578
		 * @since 4.3.3
4579
		 *
4580
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4581
		 */
4582
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4583
4584
4585
		$tracks = new Tracking();
4586
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4587
4588
		$args = urlencode_deep(
4589
			array(
4590
				'response_type' => 'code',
4591
				'client_id'     => Jetpack_Options::get_option( 'id' ),
4592
				'redirect_uri'  => add_query_arg(
4593
					array(
4594
						'action'   => 'authorize',
4595
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4596
						'redirect' => urlencode( $redirect ),
4597
					),
4598
					esc_url( admin_url( 'admin.php?page=jetpack' ) )
4599
				),
4600
				'state'         => $user->ID,
4601
				'scope'         => $signed_role,
4602
				'user_email'    => $user->user_email,
4603
				'user_login'    => $user->user_login,
4604
				'is_active'     => Jetpack::is_active(),
4605
				'jp_version'    => JETPACK__VERSION,
4606
				'auth_type'     => $auth_type,
4607
				'secret'        => $secrets['secret_1'],
4608
				'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4609
				'blogname'      => get_option( 'blogname' ),
4610
				'site_url'      => site_url(),
4611
				'home_url'      => home_url(),
4612
				'site_icon'     => get_site_icon_url(),
4613
				'site_lang'     => get_locale(),
4614
				'_ui'           => $tracks_identity['_ui'],
4615
				'_ut'           => $tracks_identity['_ut'],
4616
				'site_created'  => Jetpack::get_assumed_site_creation_date(),
4617
			)
4618
		);
4619
4620
		self::apply_activation_source_to_args( $args );
4621
4622
		$connection = self::connection();
4623
4624
		$api_url = $iframe ? $connection->api_url( 'authorize_iframe' ) : $connection->api_url( 'authorize' );
4625
4626
		return add_query_arg( $args, $api_url );
4627
	}
4628
4629
	/**
4630
	 * Get our assumed site creation date.
4631
	 * Calculated based on the earlier date of either:
4632
	 * - Earliest admin user registration date.
4633
	 * - Earliest date of post of any post type.
4634
	 *
4635
	 * @since 7.2.0
4636
	 *
4637
	 * @return string Assumed site creation date and time.
4638
	 */
4639 View Code Duplication
	public static function get_assumed_site_creation_date() {
4640
		$earliest_registered_users = get_users( array(
4641
			'role'    => 'administrator',
4642
			'orderby' => 'user_registered',
4643
			'order'   => 'ASC',
4644
			'fields'  => array( 'user_registered' ),
4645
			'number'  => 1,
4646
		) );
4647
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4648
4649
		$earliest_posts = get_posts( array(
4650
			'posts_per_page' => 1,
4651
			'post_type'      => 'any',
4652
			'post_status'    => 'any',
4653
			'orderby'        => 'date',
4654
			'order'          => 'ASC',
4655
		) );
4656
4657
		// If there are no posts at all, we'll count only on user registration date.
4658
		if ( $earliest_posts ) {
4659
			$earliest_post_date = $earliest_posts[0]->post_date;
4660
		} else {
4661
			$earliest_post_date = PHP_INT_MAX;
4662
		}
4663
4664
		return min( $earliest_registration_date, $earliest_post_date );
4665
	}
4666
4667 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4668
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4669
4670
		if ( $activation_source_name ) {
4671
			$args['_as'] = urlencode( $activation_source_name );
4672
		}
4673
4674
		if ( $activation_source_keyword ) {
4675
			$args['_ak'] = urlencode( $activation_source_keyword );
4676
		}
4677
	}
4678
4679
	function build_reconnect_url( $raw = false ) {
4680
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4681
		return $raw ? $url : esc_url( $url );
4682
	}
4683
4684
	public static function admin_url( $args = null ) {
4685
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4686
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4687
		return $url;
4688
	}
4689
4690
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4691
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4692
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4693
	}
4694
4695
	function dismiss_jetpack_notice() {
4696
4697
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4698
			return;
4699
		}
4700
4701
		switch( $_GET['jetpack-notice'] ) {
4702
			case 'dismiss':
4703
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4704
4705
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4706
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4707
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4708
				}
4709
				break;
4710
		}
4711
	}
4712
4713
	public static function sort_modules( $a, $b ) {
4714
		if ( $a['sort'] == $b['sort'] )
4715
			return 0;
4716
4717
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4718
	}
4719
4720
	function ajax_recheck_ssl() {
4721
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4722
		$result = Jetpack::permit_ssl( true );
4723
		wp_send_json( array(
4724
			'enabled' => $result,
4725
			'message' => get_transient( 'jetpack_https_test_message' )
4726
		) );
4727
	}
4728
4729
/* Client API */
4730
4731
	/**
4732
	 * Returns the requested Jetpack API URL
4733
	 *
4734
	 * @deprecated since 7.7
4735
	 * @return string
4736
	 */
4737
	public static function api_url( $relative_url ) {
4738
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4739
		$connection = self::connection();
4740
		return $connection->api_url( $relative_url );
4741
	}
4742
4743
	/**
4744
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4745
	 */
4746
	public static function fix_url_for_bad_hosts( $url ) {
4747
		if ( 0 !== strpos( $url, 'https://' ) ) {
4748
			return $url;
4749
		}
4750
4751
		switch ( JETPACK_CLIENT__HTTPS ) {
4752
			case 'ALWAYS' :
4753
				return $url;
4754
			case 'NEVER' :
4755
				return set_url_scheme( $url, 'http' );
4756
			// default : case 'AUTO' :
4757
		}
4758
4759
		// we now return the unmodified SSL URL by default, as a security precaution
4760
		return $url;
4761
	}
4762
4763
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4764
		// Default to a blog token.
4765
		$token_type = 'blog';
4766
4767
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4768
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4769
			if ( ! empty( $_GET['onboarding'] ) ) {
4770
				$jpo = $_GET;
4771
			} else {
4772
				$jpo = json_decode( $request_data, true );
4773
			}
4774
4775
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4776
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4777
4778
			if (
4779
				isset( $jpo_user )
4780
				&& isset( $jpo_token )
4781
				&& is_email( $jpo_user )
4782
				&& ctype_alnum( $jpo_token )
4783
				&& isset( $_GET['rest_route'] )
4784
				&& self::validate_onboarding_token_action(
4785
					$jpo_token,
4786
					$_GET['rest_route']
4787
				)
4788
			) {
4789
				$jp_user = get_user_by( 'email', $jpo_user );
4790
				if ( is_a( $jp_user, 'WP_User' ) ) {
4791
					wp_set_current_user( $jp_user->ID );
4792
					$user_can = is_multisite()
4793
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4794
						: current_user_can( 'manage_options' );
4795
					if ( $user_can ) {
4796
						$token_type = 'user';
4797
						$token->external_user_id = $jp_user->ID;
4798
					}
4799
				}
4800
			}
4801
4802
			$token_data['type']    = $token_type;
4803
			$token_data['user_id'] = $token->external_user_id;
4804
		}
4805
4806
		return $token_data;
4807
	}
4808
4809
	/**
4810
	 * Create a random secret for validating onboarding payload
4811
	 *
4812
	 * @return string Secret token
4813
	 */
4814
	public static function create_onboarding_token() {
4815
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4816
			$token = wp_generate_password( 32, false );
4817
			Jetpack_Options::update_option( 'onboarding', $token );
4818
		}
4819
4820
		return $token;
4821
	}
4822
4823
	/**
4824
	 * Remove the onboarding token
4825
	 *
4826
	 * @return bool True on success, false on failure
4827
	 */
4828
	public static function invalidate_onboarding_token() {
4829
		return Jetpack_Options::delete_option( 'onboarding' );
4830
	}
4831
4832
	/**
4833
	 * Validate an onboarding token for a specific action
4834
	 *
4835
	 * @return boolean True if token/action pair is accepted, false if not
4836
	 */
4837
	public static function validate_onboarding_token_action( $token, $action ) {
4838
		// Compare tokens, bail if tokens do not match
4839
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4840
			return false;
4841
		}
4842
4843
		// List of valid actions we can take
4844
		$valid_actions = array(
4845
			'/jetpack/v4/settings',
4846
		);
4847
4848
		// Whitelist the action
4849
		if ( ! in_array( $action, $valid_actions ) ) {
4850
			return false;
4851
		}
4852
4853
		return true;
4854
	}
4855
4856
	/**
4857
	 * Checks to see if the URL is using SSL to connect with Jetpack
4858
	 *
4859
	 * @since 2.3.3
4860
	 * @return boolean
4861
	 */
4862
	public static function permit_ssl( $force_recheck = false ) {
4863
		// Do some fancy tests to see if ssl is being supported
4864
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4865
			$message = '';
4866
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4867
				$ssl = 0;
4868
			} else {
4869
				switch ( JETPACK_CLIENT__HTTPS ) {
4870
					case 'NEVER':
4871
						$ssl = 0;
4872
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4873
						break;
4874
					case 'ALWAYS':
4875
					case 'AUTO':
4876
					default:
4877
						$ssl = 1;
4878
						break;
4879
				}
4880
4881
				// If it's not 'NEVER', test to see
4882
				if ( $ssl ) {
4883
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4884
						$ssl = 0;
4885
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4886
					} else {
4887
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4888
						if ( is_wp_error( $response ) ) {
4889
							$ssl = 0;
4890
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4891
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4892
							$ssl = 0;
4893
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4894
						}
4895
					}
4896
				}
4897
			}
4898
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4899
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4900
		}
4901
4902
		return (bool) $ssl;
4903
	}
4904
4905
	/*
4906
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4907
	 */
4908
	public function alert_auto_ssl_fail() {
4909
		if ( ! current_user_can( 'manage_options' ) )
4910
			return;
4911
4912
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4913
		?>
4914
4915
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4916
			<div class="jp-banner__content">
4917
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4918
				<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>
4919
				<p>
4920
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4921
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4922
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4923
				</p>
4924
				<p>
4925
					<?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' ),
4926
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4927
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4928
				</p>
4929
			</div>
4930
		</div>
4931
		<style>
4932
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4933
		</style>
4934
		<script type="text/javascript">
4935
			jQuery( document ).ready( function( $ ) {
4936
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4937
					var $this = $( this );
4938
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4939
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4940
					e.preventDefault();
4941
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4942
					$.post( ajaxurl, data )
4943
					  .done( function( response ) {
4944
					  	if ( response.enabled ) {
4945
					  		$( '#jetpack-ssl-warning' ).hide();
4946
					  	} else {
4947
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4948
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4949
					  	}
4950
					  }.bind( $this ) );
4951
				} );
4952
			} );
4953
		</script>
4954
4955
		<?php
4956
	}
4957
4958
	/**
4959
	 * Returns the Jetpack XML-RPC API
4960
	 *
4961
	 * @return string
4962
	 */
4963
	public static function xmlrpc_api_url() {
4964
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4965
		return untrailingslashit( $base ) . '/xmlrpc.php';
4966
	}
4967
4968
	public static function connection() {
4969
		return self::init()->connection_manager;
4970
	}
4971
4972
	/**
4973
	 * Creates two secret tokens and the end of life timestamp for them.
4974
	 *
4975
	 * Note these tokens are unique per call, NOT static per site for connecting.
4976
	 *
4977
	 * @since 2.6
4978
	 * @return array
4979
	 */
4980
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4981
		if ( false === $user_id ) {
4982
			$user_id = get_current_user_id();
4983
		}
4984
4985
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4986
	}
4987
4988
	public static function get_secrets( $action, $user_id ) {
4989
		$secrets = self::connection()->get_secrets( $action, $user_id );
4990
4991
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4992
			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...
4993
		}
4994
4995
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4996
			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...
4997
		}
4998
4999
		return $secrets;
5000
	}
5001
5002
	/**
5003
	 * @deprecated 7.5 Use Connection_Manager instead.
5004
	 *
5005
	 * @param $action
5006
	 * @param $user_id
5007
	 */
5008
	public static function delete_secrets( $action, $user_id ) {
5009
		return self::connection()->delete_secrets( $action, $user_id );
5010
	}
5011
5012
	/**
5013
	 * Builds the timeout limit for queries talking with the wpcom servers.
5014
	 *
5015
	 * Based on local php max_execution_time in php.ini
5016
	 *
5017
	 * @since 2.6
5018
	 * @return int
5019
	 * @deprecated
5020
	 **/
5021
	public function get_remote_query_timeout_limit() {
5022
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5023
		return Jetpack::get_max_execution_time();
5024
	}
5025
5026
	/**
5027
	 * Builds the timeout limit for queries talking with the wpcom servers.
5028
	 *
5029
	 * Based on local php max_execution_time in php.ini
5030
	 *
5031
	 * @since 5.4
5032
	 * @return int
5033
	 **/
5034
	public static function get_max_execution_time() {
5035
		$timeout = (int) ini_get( 'max_execution_time' );
5036
5037
		// Ensure exec time set in php.ini
5038
		if ( ! $timeout ) {
5039
			$timeout = 30;
5040
		}
5041
		return $timeout;
5042
	}
5043
5044
	/**
5045
	 * Sets a minimum request timeout, and returns the current timeout
5046
	 *
5047
	 * @since 5.4
5048
	 **/
5049 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5050
		$timeout = self::get_max_execution_time();
5051
		if ( $timeout < $min_timeout ) {
5052
			$timeout = $min_timeout;
5053
			set_time_limit( $timeout );
5054
		}
5055
		return $timeout;
5056
	}
5057
5058
	/**
5059
	 * Takes the response from the Jetpack register new site endpoint and
5060
	 * verifies it worked properly.
5061
	 *
5062
	 * @since 2.6
5063
	 * @deprecated since 7.7.0
5064
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5065
	 **/
5066
	public function validate_remote_register_response() {
5067
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5068
	}
5069
5070
	/**
5071
	 * @return bool|WP_Error
5072
	 */
5073
	public static function register() {
5074
		$tracking = new Tracking();
5075
		$tracking->record_user_event( 'jpc_register_begin' );
5076
5077
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5078
5079
		$connection = self::connection();
5080
		$registration = $connection->register();
5081
5082
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5083
5084
		if ( ! $registration || is_wp_error( $registration ) ) {
5085
			return $registration;
5086
		}
5087
5088
		return true;
5089
	}
5090
5091
	/**
5092
	 * Filters the registration request body to include tracking properties.
5093
	 *
5094
	 * @param Array $properties
5095
	 * @return Array amended properties.
5096
	 */
5097
	public static function filter_register_request_body( $properties ) {
5098
		$tracking = new Tracking();
5099
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5100
5101
		return array_merge(
5102
			$properties,
5103
			array(
5104
				'_ui' => $tracks_identity['_ui'],
5105
				'_ut' => $tracks_identity['_ut'],
5106
			)
5107
		);
5108
	}
5109
5110
	/**
5111
	 * If the db version is showing something other that what we've got now, bump it to current.
5112
	 *
5113
	 * @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...
5114
	 */
5115
	public static function maybe_set_version_option() {
5116
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5117
		if ( JETPACK__VERSION != $version ) {
5118
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5119
5120
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5121
				/** This action is documented in class.jetpack.php */
5122
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5123
			}
5124
5125
			return true;
5126
		}
5127
		return false;
5128
	}
5129
5130
/* Client Server API */
5131
5132
	/**
5133
	 * Loads the Jetpack XML-RPC client.
5134
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5135
	 *
5136
	 * @deprecated since 7.7.0
5137
	 */
5138
	public static function load_xml_rpc_client() {
5139
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5140
	}
5141
5142
	/**
5143
	 * Resets the saved authentication state in between testing requests.
5144
	 */
5145
	public function reset_saved_auth_state() {
5146
		$this->rest_authentication_status = null;
5147
		$this->connection_manager->reset_saved_auth_state();
5148
	}
5149
5150
	/**
5151
	 * Verifies the signature of the current request.
5152
	 *
5153
	 * @deprecated since 7.7.0
5154
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5155
	 *
5156
	 * @return false|array
5157
	 */
5158
	public function verify_xml_rpc_signature() {
5159
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5160
		return self::connection()->verify_xml_rpc_signature();
5161
	}
5162
5163
	/**
5164
	 * Verifies the signature of the current request.
5165
	 *
5166
	 * This function has side effects and should not be used. Instead,
5167
	 * use the memoized version `->verify_xml_rpc_signature()`.
5168
	 *
5169
	 * @deprecated since 7.7.0
5170
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5171
	 * @internal
5172
	 */
5173
	private function internal_verify_xml_rpc_signature() {
5174
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5175
	}
5176
5177
	/**
5178
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5179
	 *
5180
	 * @deprecated since 7.7.0
5181
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5182
	 *
5183
	 * @param \WP_User|mixed $user     User object if authenticated.
5184
	 * @param string         $username Username.
5185
	 * @param string         $password Password string.
5186
	 * @return \WP_User|mixed Authenticated user or error.
5187
	 */
5188
	public function authenticate_jetpack( $user, $username, $password ) {
5189
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5190
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5191
	}
5192
5193
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5194
	// Uses the existing XMLRPC request signing implementation.
5195
	function wp_rest_authenticate( $user ) {
5196
		if ( ! empty( $user ) ) {
5197
			// Another authentication method is in effect.
5198
			return $user;
5199
		}
5200
5201
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5202
			// Nothing to do for this authentication method.
5203
			return null;
5204
		}
5205
5206
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5207
			// Nothing to do for this authentication method.
5208
			return null;
5209
		}
5210
5211
		// Ensure that we always have the request body available.  At this
5212
		// point, the WP REST API code to determine the request body has not
5213
		// run yet.  That code may try to read from 'php://input' later, but
5214
		// this can only be done once per request in PHP versions prior to 5.6.
5215
		// So we will go ahead and perform this read now if needed, and save
5216
		// the request body where both the Jetpack signature verification code
5217
		// and the WP REST API code can see it.
5218
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5219
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5220
		}
5221
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5222
5223
		// Only support specific request parameters that have been tested and
5224
		// are known to work with signature verification.  A different method
5225
		// can be passed to the WP REST API via the '?_method=' parameter if
5226
		// needed.
5227
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5228
			$this->rest_authentication_status = new WP_Error(
5229
				'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...
5230
				__( 'This request method is not supported.', 'jetpack' ),
5231
				array( 'status' => 400 )
5232
			);
5233
			return null;
5234
		}
5235
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5236
			$this->rest_authentication_status = new WP_Error(
5237
				'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...
5238
				__( 'This request method does not support body parameters.', 'jetpack' ),
5239
				array( 'status' => 400 )
5240
			);
5241
			return null;
5242
		}
5243
5244
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5245
5246
		if (
5247
			$verified &&
5248
			isset( $verified['type'] ) &&
5249
			'user' === $verified['type'] &&
5250
			! empty( $verified['user_id'] )
5251
		) {
5252
			// Authentication successful.
5253
			$this->rest_authentication_status = true;
5254
			return $verified['user_id'];
5255
		}
5256
5257
		// Something else went wrong.  Probably a signature error.
5258
		$this->rest_authentication_status = new WP_Error(
5259
			'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...
5260
			__( 'The request is not signed correctly.', 'jetpack' ),
5261
			array( 'status' => 400 )
5262
		);
5263
		return null;
5264
	}
5265
5266
	/**
5267
	 * Report authentication status to the WP REST API.
5268
	 *
5269
	 * @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...
5270
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5271
	 */
5272
	public function wp_rest_authentication_errors( $value ) {
5273
		if ( $value !== null ) {
5274
			return $value;
5275
		}
5276
		return $this->rest_authentication_status;
5277
	}
5278
5279
	/**
5280
	 * Add our nonce to this request.
5281
	 *
5282
	 * @deprecated since 7.7.0
5283
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5284
	 *
5285
	 * @param int    $timestamp Timestamp of the request.
5286
	 * @param string $nonce     Nonce string.
5287
	 */
5288
	public function add_nonce( $timestamp, $nonce ) {
5289
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5290
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5291
	}
5292
5293
	/**
5294
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5295
	 * Capture it here so we can verify the signature later.
5296
	 *
5297
	 * @deprecated since 7.7.0
5298
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5299
	 *
5300
	 * @param array $methods XMLRPC methods.
5301
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5302
	 */
5303
	public function xmlrpc_methods( $methods ) {
5304
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5305
		return $this->connection_manager->xmlrpc_methods( $methods );
5306
	}
5307
5308
	/**
5309
	 * Register additional public XMLRPC methods.
5310
	 *
5311
	 * @deprecated since 7.7.0
5312
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5313
	 *
5314
	 * @param array $methods Public XMLRPC methods.
5315
	 * @return array Public XMLRPC methods, with the getOptions one.
5316
	 */
5317
	public function public_xmlrpc_methods( $methods ) {
5318
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5319
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5320
	}
5321
5322
	/**
5323
	 * Handles a getOptions XMLRPC method call.
5324
	 *
5325
	 * @deprecated since 7.7.0
5326
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5327
	 *
5328
	 * @param array $args method call arguments.
5329
	 * @return array an amended XMLRPC server options array.
5330
	 */
5331
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5332
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5333
		return $this->connection_manager->jetpack_getOptions( $args );
5334
	}
5335
5336
	/**
5337
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5338
	 *
5339
	 * @deprecated since 7.7.0
5340
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5341
	 *
5342
	 * @param array $options Standard Core options.
5343
	 * @return array Amended options.
5344
	 */
5345
	public function xmlrpc_options( $options ) {
5346
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5347
		return $this->connection_manager->xmlrpc_options( $options );
5348
	}
5349
5350
	/**
5351
	 * Cleans nonces that were saved when calling ::add_nonce.
5352
	 *
5353
	 * @deprecated since 7.7.0
5354
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5355
	 *
5356
	 * @param bool $all whether to clean even non-expired nonces.
5357
	 */
5358
	public static function clean_nonces( $all = false ) {
5359
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5360
		return self::connection()->clean_nonces( $all );
5361
	}
5362
5363
	/**
5364
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5365
	 * SET: state( $key, $value );
5366
	 * GET: $value = state( $key );
5367
	 *
5368
	 * @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...
5369
	 * @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...
5370
	 * @param bool $restate private
5371
	 */
5372
	public static function state( $key = null, $value = null, $restate = false ) {
5373
		static $state = array();
5374
		static $path, $domain;
5375
		if ( ! isset( $path ) ) {
5376
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5377
			$admin_url = Jetpack::admin_url();
5378
			$bits      = wp_parse_url( $admin_url );
5379
5380
			if ( is_array( $bits ) ) {
5381
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5382
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5383
			} else {
5384
				$path = $domain = null;
5385
			}
5386
		}
5387
5388
		// Extract state from cookies and delete cookies
5389
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5390
			$yum = $_COOKIE[ 'jetpackState' ];
5391
			unset( $_COOKIE[ 'jetpackState' ] );
5392
			foreach ( $yum as $k => $v ) {
5393
				if ( strlen( $v ) )
5394
					$state[ $k ] = $v;
5395
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5396
			}
5397
		}
5398
5399
		if ( $restate ) {
5400
			foreach ( $state as $k => $v ) {
5401
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5402
			}
5403
			return;
5404
		}
5405
5406
		// Get a state variable
5407
		if ( isset( $key ) && ! isset( $value ) ) {
5408
			if ( array_key_exists( $key, $state ) )
5409
				return $state[ $key ];
5410
			return null;
5411
		}
5412
5413
		// Set a state variable
5414
		if ( isset ( $key ) && isset( $value ) ) {
5415
			if( is_array( $value ) && isset( $value[0] ) ) {
5416
				$value = $value[0];
5417
			}
5418
			$state[ $key ] = $value;
5419
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5420
		}
5421
	}
5422
5423
	public static function restate() {
5424
		Jetpack::state( null, null, true );
5425
	}
5426
5427
	public static function check_privacy( $file ) {
5428
		static $is_site_publicly_accessible = null;
5429
5430
		if ( is_null( $is_site_publicly_accessible ) ) {
5431
			$is_site_publicly_accessible = false;
5432
5433
			$rpc = new Jetpack_IXR_Client();
5434
5435
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5436
			if ( $success ) {
5437
				$response = $rpc->getResponse();
5438
				if ( $response ) {
5439
					$is_site_publicly_accessible = true;
5440
				}
5441
			}
5442
5443
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5444
		}
5445
5446
		if ( $is_site_publicly_accessible ) {
5447
			return;
5448
		}
5449
5450
		$module_slug = self::get_module_slug( $file );
5451
5452
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5453
		if ( ! $privacy_checks ) {
5454
			$privacy_checks = $module_slug;
5455
		} else {
5456
			$privacy_checks .= ",$module_slug";
5457
		}
5458
5459
		Jetpack::state( 'privacy_checks', $privacy_checks );
5460
	}
5461
5462
	/**
5463
	 * Helper method for multicall XMLRPC.
5464
	 */
5465
	public static function xmlrpc_async_call() {
5466
		global $blog_id;
5467
		static $clients = array();
5468
5469
		$client_blog_id = is_multisite() ? $blog_id : 0;
5470
5471
		if ( ! isset( $clients[$client_blog_id] ) ) {
5472
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5473
			if ( function_exists( 'ignore_user_abort' ) ) {
5474
				ignore_user_abort( true );
5475
			}
5476
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5477
		}
5478
5479
		$args = func_get_args();
5480
5481
		if ( ! empty( $args[0] ) ) {
5482
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5483
		} elseif ( is_multisite() ) {
5484
			foreach ( $clients as $client_blog_id => $client ) {
5485
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5486
					continue;
5487
				}
5488
5489
				$switch_success = switch_to_blog( $client_blog_id, true );
5490
				if ( ! $switch_success ) {
5491
					continue;
5492
				}
5493
5494
				flush();
5495
				$client->query();
5496
5497
				restore_current_blog();
5498
			}
5499
		} else {
5500
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5501
				flush();
5502
				$clients[0]->query();
5503
			}
5504
		}
5505
	}
5506
5507
	public static function staticize_subdomain( $url ) {
5508
5509
		// Extract hostname from URL
5510
		$host = parse_url( $url, PHP_URL_HOST );
5511
5512
		// Explode hostname on '.'
5513
		$exploded_host = explode( '.', $host );
5514
5515
		// Retrieve the name and TLD
5516
		if ( count( $exploded_host ) > 1 ) {
5517
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5518
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5519
			// Rebuild domain excluding subdomains
5520
			$domain = $name . '.' . $tld;
5521
		} else {
5522
			$domain = $host;
5523
		}
5524
		// Array of Automattic domains
5525
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5526
5527
		// Return $url if not an Automattic domain
5528
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5529
			return $url;
5530
		}
5531
5532
		if ( is_ssl() ) {
5533
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5534
		}
5535
5536
		srand( crc32( basename( $url ) ) );
5537
		$static_counter = rand( 0, 2 );
5538
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5539
5540
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5541
	}
5542
5543
/* JSON API Authorization */
5544
5545
	/**
5546
	 * Handles the login action for Authorizing the JSON API
5547
	 */
5548
	function login_form_json_api_authorization() {
5549
		$this->verify_json_api_authorization_request();
5550
5551
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5552
5553
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5554
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5555
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5556
	}
5557
5558
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5559
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5560
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5561
			return $url;
5562
		}
5563
5564
		$parsed_url = parse_url( $url );
5565
		$url = strtok( $url, '?' );
5566
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5567
		if ( ! empty( $parsed_url['query'] ) )
5568
			$url .= "&{$parsed_url['query']}";
5569
5570
		return $url;
5571
	}
5572
5573
	// Make sure the POSTed request is handled by the same action
5574
	function preserve_action_in_login_form_for_json_api_authorization() {
5575
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5576
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5577
	}
5578
5579
	// If someone logs in to approve API access, store the Access Code in usermeta
5580
	function store_json_api_authorization_token( $user_login, $user ) {
5581
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5582
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5583
		$token = wp_generate_password( 32, false );
5584
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5585
	}
5586
5587
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5588
	function allow_wpcom_public_api_domain( $domains ) {
5589
		$domains[] = 'public-api.wordpress.com';
5590
		return $domains;
5591
	}
5592
5593
	static function is_redirect_encoded( $redirect_url ) {
5594
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5595
	}
5596
5597
	// Add all wordpress.com environments to the safe redirect whitelist
5598
	function allow_wpcom_environments( $domains ) {
5599
		$domains[] = 'wordpress.com';
5600
		$domains[] = 'wpcalypso.wordpress.com';
5601
		$domains[] = 'horizon.wordpress.com';
5602
		$domains[] = 'calypso.localhost';
5603
		return $domains;
5604
	}
5605
5606
	// Add the Access Code details to the public-api.wordpress.com redirect
5607
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5608
		return add_query_arg(
5609
			urlencode_deep(
5610
				array(
5611
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5612
					'jetpack-user-id' => (int) $user->ID,
5613
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5614
				)
5615
			),
5616
			$redirect_to
5617
		);
5618
	}
5619
5620
5621
	/**
5622
	 * Verifies the request by checking the signature
5623
	 *
5624
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5625
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5626
	 *
5627
	 * @param null|array $environment
5628
	 */
5629
	function verify_json_api_authorization_request( $environment = null ) {
5630
		$environment = is_null( $environment )
5631
			? $_REQUEST
5632
			: $environment;
5633
5634
		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...
5635
		$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...
5636
		if ( ! $token || empty( $token->secret ) ) {
5637
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5638
		}
5639
5640
		$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' );
5641
5642
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5643
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5644
			/**
5645
			 * Jetpack authorisation request Error.
5646
			 *
5647
			 * @since 7.5.0
5648
			 *
5649
			 */
5650
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5651
			$die_error = sprintf(
5652
				/* translators: %s is a URL */
5653
				__( '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' ),
5654
				'https://jetpack.com/support/double-encoding/'
5655
			);
5656
		}
5657
5658
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5659
5660
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5661
			$signature = $jetpack_signature->sign_request(
5662
				$environment['token'],
5663
				$environment['timestamp'],
5664
				$environment['nonce'],
5665
				'',
5666
				'GET',
5667
				$environment['jetpack_json_api_original_query'],
5668
				null,
5669
				true
5670
			);
5671
		} else {
5672
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5673
		}
5674
5675
		if ( ! $signature ) {
5676
			wp_die( $die_error );
5677
		} else if ( is_wp_error( $signature ) ) {
5678
			wp_die( $die_error );
5679
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5680
			if ( is_ssl() ) {
5681
				// 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
5682
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5683
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5684
					wp_die( $die_error );
5685
				}
5686
			} else {
5687
				wp_die( $die_error );
5688
			}
5689
		}
5690
5691
		$timestamp = (int) $environment['timestamp'];
5692
		$nonce     = stripslashes( (string) $environment['nonce'] );
5693
5694
		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...
5695
			// De-nonce the nonce, at least for 5 minutes.
5696
			// 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)
5697
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5698
			if ( $old_nonce_time < time() - 300 ) {
5699
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5700
			}
5701
		}
5702
5703
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5704
		$data_filters = array(
5705
			'state'        => 'opaque',
5706
			'client_id'    => 'int',
5707
			'client_title' => 'string',
5708
			'client_image' => 'url',
5709
		);
5710
5711
		foreach ( $data_filters as $key => $sanitation ) {
5712
			if ( ! isset( $data->$key ) ) {
5713
				wp_die( $die_error );
5714
			}
5715
5716
			switch ( $sanitation ) {
5717
			case 'int' :
5718
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5719
				break;
5720
			case 'opaque' :
5721
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5722
				break;
5723
			case 'string' :
5724
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5725
				break;
5726
			case 'url' :
5727
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5728
				break;
5729
			}
5730
		}
5731
5732
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5733
			wp_die( $die_error );
5734
		}
5735
	}
5736
5737
	function login_message_json_api_authorization( $message ) {
5738
		return '<p class="message">' . sprintf(
5739
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5740
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5741
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5742
	}
5743
5744
	/**
5745
	 * Get $content_width, but with a <s>twist</s> filter.
5746
	 */
5747
	public static function get_content_width() {
5748
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5749
			? $GLOBALS['content_width']
5750
			: false;
5751
		/**
5752
		 * Filter the Content Width value.
5753
		 *
5754
		 * @since 2.2.3
5755
		 *
5756
		 * @param string $content_width Content Width value.
5757
		 */
5758
		return apply_filters( 'jetpack_content_width', $content_width );
5759
	}
5760
5761
	/**
5762
	 * Pings the WordPress.com Mirror Site for the specified options.
5763
	 *
5764
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5765
	 *
5766
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5767
	 */
5768
	public function get_cloud_site_options( $option_names ) {
5769
		$option_names = array_filter( (array) $option_names, 'is_string' );
5770
5771
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5772
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5773
		if ( $xml->isError() ) {
5774
			return array(
5775
				'error_code' => $xml->getErrorCode(),
5776
				'error_msg'  => $xml->getErrorMessage(),
5777
			);
5778
		}
5779
		$cloud_site_options = $xml->getResponse();
5780
5781
		return $cloud_site_options;
5782
	}
5783
5784
	/**
5785
	 * Checks if the site is currently in an identity crisis.
5786
	 *
5787
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5788
	 */
5789
	public static function check_identity_crisis() {
5790
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5791
			return false;
5792
		}
5793
5794
		return Jetpack_Options::get_option( 'sync_error_idc' );
5795
	}
5796
5797
	/**
5798
	 * Checks whether the home and siteurl specifically are whitelisted
5799
	 * Written so that we don't have re-check $key and $value params every time
5800
	 * we want to check if this site is whitelisted, for example in footer.php
5801
	 *
5802
	 * @since  3.8.0
5803
	 * @return bool True = already whitelisted False = not whitelisted
5804
	 */
5805
	public static function is_staging_site() {
5806
		$is_staging = false;
5807
5808
		$known_staging = array(
5809
			'urls' => array(
5810
				'#\.staging\.wpengine\.com$#i', // WP Engine
5811
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5812
				'#\.stage\.site$#i'             // DreamPress
5813
			),
5814
			'constants' => array(
5815
				'IS_WPE_SNAPSHOT',      // WP Engine
5816
				'KINSTA_DEV_ENV',       // Kinsta.com
5817
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5818
				'JETPACK_STAGING_MODE', // Generic
5819
			)
5820
		);
5821
		/**
5822
		 * Filters the flags of known staging sites.
5823
		 *
5824
		 * @since 3.9.0
5825
		 *
5826
		 * @param array $known_staging {
5827
		 *     An array of arrays that each are used to check if the current site is staging.
5828
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5829
		 *     @type array $constants PHP constants of known staging/developement environments.
5830
		 *  }
5831
		 */
5832
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5833
5834
		if ( isset( $known_staging['urls'] ) ) {
5835
			foreach ( $known_staging['urls'] as $url ){
5836
				if ( preg_match( $url, site_url() ) ) {
5837
					$is_staging = true;
5838
					break;
5839
				}
5840
			}
5841
		}
5842
5843
		if ( isset( $known_staging['constants'] ) ) {
5844
			foreach ( $known_staging['constants'] as $constant ) {
5845
				if ( defined( $constant ) && constant( $constant ) ) {
5846
					$is_staging = true;
5847
				}
5848
			}
5849
		}
5850
5851
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5852
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5853
			$is_staging = true;
5854
		}
5855
5856
		/**
5857
		 * Filters is_staging_site check.
5858
		 *
5859
		 * @since 3.9.0
5860
		 *
5861
		 * @param bool $is_staging If the current site is a staging site.
5862
		 */
5863
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5864
	}
5865
5866
	/**
5867
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5868
	 *
5869
	 * @since 4.4.0
5870
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5871
	 *
5872
	 * @return bool
5873
	 */
5874
	public static function validate_sync_error_idc_option() {
5875
		$is_valid = false;
5876
5877
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5878
		if ( false === $idc_allowed ) {
5879
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5880
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5881
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5882
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5883
				$transient_duration = HOUR_IN_SECONDS;
5884
			} else {
5885
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5886
				$idc_allowed = '1';
5887
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5888
			}
5889
5890
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5891
		}
5892
5893
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5894
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5895
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5896
			$local_options = self::get_sync_error_idc_option();
5897
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5898
				$is_valid = true;
5899
			}
5900
		}
5901
5902
		/**
5903
		 * Filters whether the sync_error_idc option is valid.
5904
		 *
5905
		 * @since 4.4.0
5906
		 *
5907
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5908
		 */
5909
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5910
5911
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5912
			// Since the option exists, and did not validate, delete it
5913
			Jetpack_Options::delete_option( 'sync_error_idc' );
5914
		}
5915
5916
		return $is_valid;
5917
	}
5918
5919
	/**
5920
	 * Normalizes a url by doing three things:
5921
	 *  - Strips protocol
5922
	 *  - Strips www
5923
	 *  - Adds a trailing slash
5924
	 *
5925
	 * @since 4.4.0
5926
	 * @param string $url
5927
	 * @return WP_Error|string
5928
	 */
5929
	public static function normalize_url_protocol_agnostic( $url ) {
5930
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5931
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5932
			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...
5933
		}
5934
5935
		// Strip www and protocols
5936
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5937
		return $url;
5938
	}
5939
5940
	/**
5941
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5942
	 *
5943
	 * @since 4.4.0
5944
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5945
	 *
5946
	 * @param array $response
5947
	 * @return array Array of the local urls, wpcom urls, and error code
5948
	 */
5949
	public static function get_sync_error_idc_option( $response = array() ) {
5950
		// Since the local options will hit the database directly, store the values
5951
		// in a transient to allow for autoloading and caching on subsequent views.
5952
		$local_options = get_transient( 'jetpack_idc_local' );
5953
		if ( false === $local_options ) {
5954
			$local_options = array(
5955
				'home'    => Functions::home_url(),
5956
				'siteurl' => Functions::site_url(),
5957
			);
5958
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5959
		}
5960
5961
		$options = array_merge( $local_options, $response );
5962
5963
		$returned_values = array();
5964
		foreach( $options as $key => $option ) {
5965
			if ( 'error_code' === $key ) {
5966
				$returned_values[ $key ] = $option;
5967
				continue;
5968
			}
5969
5970
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5971
				continue;
5972
			}
5973
5974
			$returned_values[ $key ] = $normalized_url;
5975
		}
5976
5977
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5978
5979
		return $returned_values;
5980
	}
5981
5982
	/**
5983
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5984
	 * If set to true, the site will be put into staging mode.
5985
	 *
5986
	 * @since 4.3.2
5987
	 * @return bool
5988
	 */
5989
	public static function sync_idc_optin() {
5990
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5991
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5992
		} else {
5993
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5994
		}
5995
5996
		/**
5997
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5998
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5999
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6000
		 *
6001
		 * @since 4.3.2
6002
		 *
6003
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6004
		 */
6005
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6006
	}
6007
6008
	/**
6009
	 * Maybe Use a .min.css stylesheet, maybe not.
6010
	 *
6011
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6012
	 */
6013
	public static function maybe_min_asset( $url, $path, $plugin ) {
6014
		// Short out on things trying to find actual paths.
6015
		if ( ! $path || empty( $plugin ) ) {
6016
			return $url;
6017
		}
6018
6019
		$path = ltrim( $path, '/' );
6020
6021
		// Strip out the abspath.
6022
		$base = dirname( plugin_basename( $plugin ) );
6023
6024
		// Short out on non-Jetpack assets.
6025
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6026
			return $url;
6027
		}
6028
6029
		// File name parsing.
6030
		$file              = "{$base}/{$path}";
6031
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6032
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6033
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6034
		$extension         = array_shift( $file_name_parts_r );
6035
6036
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6037
			// Already pointing at the minified version.
6038
			if ( 'min' === $file_name_parts_r[0] ) {
6039
				return $url;
6040
			}
6041
6042
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6043
			if ( file_exists( $min_full_path ) ) {
6044
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6045
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6046
				if ( 'css' === $extension ) {
6047
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6048
					self::$min_assets[ $key ] = $path;
6049
				}
6050
			}
6051
		}
6052
6053
		return $url;
6054
	}
6055
6056
	/**
6057
	 * If the asset is minified, let's flag .min as the suffix.
6058
	 *
6059
	 * Attached to `style_loader_src` filter.
6060
	 *
6061
	 * @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...
6062
	 * @param string $handle The registered handle of the script in question.
6063
	 * @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...
6064
	 */
6065
	public static function set_suffix_on_min( $src, $handle ) {
6066
		if ( false === strpos( $src, '.min.css' ) ) {
6067
			return $src;
6068
		}
6069
6070
		if ( ! empty( self::$min_assets ) ) {
6071
			foreach ( self::$min_assets as $file => $path ) {
6072
				if ( false !== strpos( $src, $file ) ) {
6073
					wp_style_add_data( $handle, 'suffix', '.min' );
6074
					return $src;
6075
				}
6076
			}
6077
		}
6078
6079
		return $src;
6080
	}
6081
6082
	/**
6083
	 * Maybe inlines a stylesheet.
6084
	 *
6085
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6086
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6087
	 *
6088
	 * Attached to `style_loader_tag` filter.
6089
	 *
6090
	 * @param string $tag The tag that would link to the external asset.
6091
	 * @param string $handle The registered handle of the script in question.
6092
	 *
6093
	 * @return string
6094
	 */
6095
	public static function maybe_inline_style( $tag, $handle ) {
6096
		global $wp_styles;
6097
		$item = $wp_styles->registered[ $handle ];
6098
6099
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6100
			return $tag;
6101
		}
6102
6103
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6104
			$href = $matches[1];
6105
			// Strip off query string
6106
			if ( $pos = strpos( $href, '?' ) ) {
6107
				$href = substr( $href, 0, $pos );
6108
			}
6109
			// Strip off fragment
6110
			if ( $pos = strpos( $href, '#' ) ) {
6111
				$href = substr( $href, 0, $pos );
6112
			}
6113
		} else {
6114
			return $tag;
6115
		}
6116
6117
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6118
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6119
			return $tag;
6120
		}
6121
6122
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6123
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6124
			// And this isn't the pass that actually deals with the RTL version...
6125
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6126
				// Short out, as the RTL version will deal with it in a moment.
6127
				return $tag;
6128
			}
6129
		}
6130
6131
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6132
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6133
		if ( $css ) {
6134
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6135
			if ( empty( $item->extra['after'] ) ) {
6136
				wp_add_inline_style( $handle, $css );
6137
			} else {
6138
				array_unshift( $item->extra['after'], $css );
6139
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6140
			}
6141
		}
6142
6143
		return $tag;
6144
	}
6145
6146
	/**
6147
	 * Loads a view file from the views
6148
	 *
6149
	 * Data passed in with the $data parameter will be available in the
6150
	 * template file as $data['value']
6151
	 *
6152
	 * @param string $template - Template file to load
6153
	 * @param array $data - Any data to pass along to the template
6154
	 * @return boolean - If template file was found
6155
	 **/
6156
	public function load_view( $template, $data = array() ) {
6157
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6158
6159
		if( file_exists( $views_dir . $template ) ) {
6160
			require_once( $views_dir . $template );
6161
			return true;
6162
		}
6163
6164
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6165
		return false;
6166
	}
6167
6168
	/**
6169
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6170
	 */
6171
	public function deprecated_hooks() {
6172
		global $wp_filter;
6173
6174
		/*
6175
		 * Format:
6176
		 * deprecated_filter_name => replacement_name
6177
		 *
6178
		 * If there is no replacement, use null for replacement_name
6179
		 */
6180
		$deprecated_list = array(
6181
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6182
			'wpl_sharing_2014_1'                                     => null,
6183
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6184
			'jetpack_identity_crisis_options_to_check'               => null,
6185
			'update_option_jetpack_single_user_site'                 => null,
6186
			'audio_player_default_colors'                            => null,
6187
			'add_option_jetpack_featured_images_enabled'             => null,
6188
			'add_option_jetpack_update_details'                      => null,
6189
			'add_option_jetpack_updates'                             => null,
6190
			'add_option_jetpack_network_name'                        => null,
6191
			'add_option_jetpack_network_allow_new_registrations'     => null,
6192
			'add_option_jetpack_network_add_new_users'               => null,
6193
			'add_option_jetpack_network_site_upload_space'           => null,
6194
			'add_option_jetpack_network_upload_file_types'           => null,
6195
			'add_option_jetpack_network_enable_administration_menus' => null,
6196
			'add_option_jetpack_is_multi_site'                       => null,
6197
			'add_option_jetpack_is_main_network'                     => null,
6198
			'add_option_jetpack_main_network_site'                   => null,
6199
			'jetpack_sync_all_registered_options'                    => null,
6200
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6201
			'jetpack_is_post_mailable'                               => null,
6202
			'jetpack_seo_site_host'                                  => null,
6203
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6204
			'jetpack_holiday_snow_option_name'                       => null,
6205
			'jetpack_holiday_chance_of_snow'                         => null,
6206
			'jetpack_holiday_snow_js_url'                            => null,
6207
			'jetpack_is_holiday_snow_season'                         => null,
6208
			'jetpack_holiday_snow_option_updated'                    => null,
6209
			'jetpack_holiday_snowing'                                => null,
6210
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6211
			'jetpack_cache_plans'                                    => null,
6212
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6213
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6214
			'jetpack_enable_site_verification'                       => null,
6215
			'can_display_jetpack_manage_notice'                      => null,
6216
			// Removed in Jetpack 7.3.0
6217
			'atd_load_scripts'                                       => null,
6218
			'atd_http_post_timeout'                                  => null,
6219
			'atd_http_post_error'                                    => null,
6220
			'atd_service_domain'                                     => null,
6221
			'jetpack_widget_authors_exclude'                         => 'jetpack_widget_authors_params',
6222
		);
6223
6224
		// This is a silly loop depth. Better way?
6225
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6226
			if ( has_action( $hook ) ) {
6227
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6228
					foreach( $values AS $hooked ) {
6229
						if ( is_callable( $hooked['function'] ) ) {
6230
							$function_name = 'an anonymous function';
6231
						} else {
6232
							$function_name = $hooked['function'];
6233
						}
6234
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6235
					}
6236
				}
6237
			}
6238
		}
6239
	}
6240
6241
	/**
6242
	 * Converts any url in a stylesheet, to the correct absolute url.
6243
	 *
6244
	 * Considerations:
6245
	 *  - Normal, relative URLs     `feh.png`
6246
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6247
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6248
	 *  - Absolute URLs             `http://domain.com/feh.png`
6249
	 *  - Domain root relative URLs `/feh.png`
6250
	 *
6251
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6252
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6253
	 *
6254
	 * @return mixed|string
6255
	 */
6256
	public static function absolutize_css_urls( $css, $css_file_url ) {
6257
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6258
		$css_dir = dirname( $css_file_url );
6259
		$p       = parse_url( $css_dir );
6260
		$domain  = sprintf(
6261
					'%1$s//%2$s%3$s%4$s',
6262
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6263
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6264
					$p['host'],
6265
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6266
				);
6267
6268
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6269
			$find = $replace = array();
6270
			foreach ( $matches as $match ) {
6271
				$url = trim( $match['path'], "'\" \t" );
6272
6273
				// If this is a data url, we don't want to mess with it.
6274
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6275
					continue;
6276
				}
6277
6278
				// If this is an absolute or protocol-agnostic url,
6279
				// we don't want to mess with it.
6280
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6281
					continue;
6282
				}
6283
6284
				switch ( substr( $url, 0, 1 ) ) {
6285
					case '/':
6286
						$absolute = $domain . $url;
6287
						break;
6288
					default:
6289
						$absolute = $css_dir . '/' . $url;
6290
				}
6291
6292
				$find[]    = $match[0];
6293
				$replace[] = sprintf( 'url("%s")', $absolute );
6294
			}
6295
			$css = str_replace( $find, $replace, $css );
6296
		}
6297
6298
		return $css;
6299
	}
6300
6301
	/**
6302
	 * This methods removes all of the registered css files on the front end
6303
	 * from Jetpack in favor of using a single file. In effect "imploding"
6304
	 * all the files into one file.
6305
	 *
6306
	 * Pros:
6307
	 * - Uses only ONE css asset connection instead of 15
6308
	 * - Saves a minimum of 56k
6309
	 * - Reduces server load
6310
	 * - Reduces time to first painted byte
6311
	 *
6312
	 * Cons:
6313
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6314
	 *		should not cause any issues with themes.
6315
	 * - Plugins/themes dequeuing styles no longer do anything. See
6316
	 *		jetpack_implode_frontend_css filter for a workaround
6317
	 *
6318
	 * For some situations developers may wish to disable css imploding and
6319
	 * instead operate in legacy mode where each file loads seperately and
6320
	 * can be edited individually or dequeued. This can be accomplished with
6321
	 * the following line:
6322
	 *
6323
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6324
	 *
6325
	 * @since 3.2
6326
	 **/
6327
	public function implode_frontend_css( $travis_test = false ) {
6328
		$do_implode = true;
6329
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6330
			$do_implode = false;
6331
		}
6332
6333
		// Do not implode CSS when the page loads via the AMP plugin.
6334
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6335
			$do_implode = false;
6336
		}
6337
6338
		/**
6339
		 * Allow CSS to be concatenated into a single jetpack.css file.
6340
		 *
6341
		 * @since 3.2.0
6342
		 *
6343
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6344
		 */
6345
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6346
6347
		// Do not use the imploded file when default behavior was altered through the filter
6348
		if ( ! $do_implode ) {
6349
			return;
6350
		}
6351
6352
		// We do not want to use the imploded file in dev mode, or if not connected
6353
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6354
			if ( ! $travis_test ) {
6355
				return;
6356
			}
6357
		}
6358
6359
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6360
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6361
			return;
6362
		}
6363
6364
		/*
6365
		 * Now we assume Jetpack is connected and able to serve the single
6366
		 * file.
6367
		 *
6368
		 * In the future there will be a check here to serve the file locally
6369
		 * or potentially from the Jetpack CDN
6370
		 *
6371
		 * For now:
6372
		 * - Enqueue a single imploded css file
6373
		 * - Zero out the style_loader_tag for the bundled ones
6374
		 * - Be happy, drink scotch
6375
		 */
6376
6377
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6378
6379
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6380
6381
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6382
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6383
	}
6384
6385
	function concat_remove_style_loader_tag( $tag, $handle ) {
6386
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6387
			$tag = '';
6388
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6389
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6390
			}
6391
		}
6392
6393
		return $tag;
6394
	}
6395
6396
	/**
6397
	 * Add an async attribute to scripts that can be loaded asynchronously.
6398
	 * https://www.w3schools.com/tags/att_script_async.asp
6399
	 *
6400
	 * @since 7.7.0
6401
	 *
6402
	 * @param string $tag    The <script> tag for the enqueued script.
6403
	 * @param string $handle The script's registered handle.
6404
	 * @param string $src    The script's source URL.
6405
	 */
6406
	public function script_add_async( $tag, $handle, $src ) {
6407
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6408
			return preg_replace( '/^<script /i', '<script async ', $tag );
6409
		}
6410
6411
		return $tag;
6412
	}
6413
6414
	/*
6415
	 * Check the heartbeat data
6416
	 *
6417
	 * Organizes the heartbeat data by severity.  For example, if the site
6418
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6419
	 *
6420
	 * Data will be added to "caution" array, if it either:
6421
	 *  - Out of date Jetpack version
6422
	 *  - Out of date WP version
6423
	 *  - Out of date PHP version
6424
	 *
6425
	 * $return array $filtered_data
6426
	 */
6427
	public static function jetpack_check_heartbeat_data() {
6428
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6429
6430
		$good    = array();
6431
		$caution = array();
6432
		$bad     = array();
6433
6434
		foreach ( $raw_data as $stat => $value ) {
6435
6436
			// Check jetpack version
6437
			if ( 'version' == $stat ) {
6438
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6439
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6440
					continue;
6441
				}
6442
			}
6443
6444
			// Check WP version
6445
			if ( 'wp-version' == $stat ) {
6446
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6447
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6448
					continue;
6449
				}
6450
			}
6451
6452
			// Check PHP version
6453
			if ( 'php-version' == $stat ) {
6454
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6455
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6456
					continue;
6457
				}
6458
			}
6459
6460
			// Check ID crisis
6461
			if ( 'identitycrisis' == $stat ) {
6462
				if ( 'yes' == $value ) {
6463
					$bad[ $stat ] = $value;
6464
					continue;
6465
				}
6466
			}
6467
6468
			// The rest are good :)
6469
			$good[ $stat ] = $value;
6470
		}
6471
6472
		$filtered_data = array(
6473
			'good'    => $good,
6474
			'caution' => $caution,
6475
			'bad'     => $bad
6476
		);
6477
6478
		return $filtered_data;
6479
	}
6480
6481
6482
	/*
6483
	 * This method is used to organize all options that can be reset
6484
	 * without disconnecting Jetpack.
6485
	 *
6486
	 * It is used in class.jetpack-cli.php to reset options
6487
	 *
6488
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6489
	 *
6490
	 * @return array of options to delete.
6491
	 */
6492
	public static function get_jetpack_options_for_reset() {
6493
		return Jetpack_Options::get_options_for_reset();
6494
	}
6495
6496
	/*
6497
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6498
	 * so we can bring them directly to their site in calypso.
6499
	 *
6500
	 * @param string | url
6501
	 * @return string | url without the guff
6502
	 */
6503
	public static function build_raw_urls( $url ) {
6504
		$strip_http = '/.*?:\/\//i';
6505
		$url = preg_replace( $strip_http, '', $url  );
6506
		$url = str_replace( '/', '::', $url );
6507
		return $url;
6508
	}
6509
6510
	/**
6511
	 * Stores and prints out domains to prefetch for page speed optimization.
6512
	 *
6513
	 * @param mixed $new_urls
6514
	 */
6515
	public static function dns_prefetch( $new_urls = null ) {
6516
		static $prefetch_urls = array();
6517
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6518
			echo "\r\n";
6519
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6520
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6521
			}
6522
		} elseif ( ! empty( $new_urls ) ) {
6523
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6524
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6525
			}
6526
			foreach ( (array) $new_urls as $this_new_url ) {
6527
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6528
			}
6529
			$prefetch_urls = array_unique( $prefetch_urls );
6530
		}
6531
	}
6532
6533
	public function wp_dashboard_setup() {
6534
		if ( self::is_active() ) {
6535
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6536
		}
6537
6538
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6539
			$jetpack_logo = new Jetpack_Logo();
6540
			$widget_title = sprintf(
6541
				wp_kses(
6542
					/* translators: Placeholder is a Jetpack logo. */
6543
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6544
					array( 'span' => array() )
6545
				),
6546
				$jetpack_logo->get_jp_emblem( true )
6547
			);
6548
6549
			wp_add_dashboard_widget(
6550
				'jetpack_summary_widget',
6551
				$widget_title,
6552
				array( __CLASS__, 'dashboard_widget' )
6553
			);
6554
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6555
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6556
6557
			// If we're inactive and not in development mode, sort our box to the top.
6558
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6559
				global $wp_meta_boxes;
6560
6561
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6562
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6563
6564
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6565
			}
6566
		}
6567
	}
6568
6569
	/**
6570
	 * @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...
6571
	 * @return mixed
6572
	 */
6573
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6574
		if ( ! is_array( $sorted ) ) {
6575
			return $sorted;
6576
		}
6577
6578
		foreach ( $sorted as $box_context => $ids ) {
6579
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6580
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6581
				continue;
6582
			}
6583
6584
			$ids_array = explode( ',', $ids );
6585
			$key = array_search( 'dashboard_stats', $ids_array );
6586
6587
			if ( false !== $key ) {
6588
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6589
				$ids_array[ $key ] = 'jetpack_summary_widget';
6590
				$sorted[ $box_context ] = implode( ',', $ids_array );
6591
				// We've found it, stop searching, and just return.
6592
				break;
6593
			}
6594
		}
6595
6596
		return $sorted;
6597
	}
6598
6599
	public static function dashboard_widget() {
6600
		/**
6601
		 * Fires when the dashboard is loaded.
6602
		 *
6603
		 * @since 3.4.0
6604
		 */
6605
		do_action( 'jetpack_dashboard_widget' );
6606
	}
6607
6608
	public static function dashboard_widget_footer() {
6609
		?>
6610
		<footer>
6611
6612
		<div class="protect">
6613
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6614
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6615
				<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>
6616
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6617
				<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' ); ?>">
6618
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6619
				</a>
6620
			<?php else : ?>
6621
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6622
			<?php endif; ?>
6623
		</div>
6624
6625
		<div class="akismet">
6626
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6627
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6628
				<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>
6629
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6630
				<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">
6631
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6632
				</a>
6633
			<?php else : ?>
6634
				<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>
6635
			<?php endif; ?>
6636
		</div>
6637
6638
		</footer>
6639
		<?php
6640
	}
6641
6642
	/*
6643
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6644
	 */
6645
	function jetpack_icon_user_connected( $columns ) {
6646
		$columns['user_jetpack'] = '';
6647
		return $columns;
6648
	}
6649
6650
	/*
6651
	 * Show Jetpack icon if the user is linked.
6652
	 */
6653
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6654
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6655
			$jetpack_logo = new Jetpack_Logo();
6656
			$emblem_html = sprintf(
6657
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6658
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6659
				$jetpack_logo->get_jp_emblem()
6660
			);
6661
			return $emblem_html;
6662
		}
6663
6664
		return $val;
6665
	}
6666
6667
	/*
6668
	 * Style the Jetpack user column
6669
	 */
6670
	function jetpack_user_col_style() {
6671
		global $current_screen;
6672
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6673
			<style>
6674
				.fixed .column-user_jetpack {
6675
					width: 21px;
6676
				}
6677
				.jp-emblem-user-admin svg {
6678
					width: 20px;
6679
					height: 20px;
6680
				}
6681
				.jp-emblem-user-admin path {
6682
					fill: #00BE28;
6683
				}
6684
			</style>
6685
		<?php }
6686
	}
6687
6688
	/**
6689
	 * Checks if Akismet is active and working.
6690
	 *
6691
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6692
	 * that implied usage of methods present since more recent version.
6693
	 * See https://github.com/Automattic/jetpack/pull/9585
6694
	 *
6695
	 * @since  5.1.0
6696
	 *
6697
	 * @return bool True = Akismet available. False = Aksimet not available.
6698
	 */
6699
	public static function is_akismet_active() {
6700
		static $status = null;
6701
6702
		if ( ! is_null( $status ) ) {
6703
			return $status;
6704
		}
6705
6706
		// Check if a modern version of Akismet is active.
6707
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6708
			$status = false;
6709
			return $status;
6710
		}
6711
6712
		// Make sure there is a key known to Akismet at all before verifying key.
6713
		$akismet_key = Akismet::get_api_key();
6714
		if ( ! $akismet_key ) {
6715
			$status = false;
6716
			return $status;
6717
		}
6718
6719
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6720
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6721
6722
		// 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.
6723
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6724
		// We cache the result of the Akismet key verification for ten minutes.
6725
		if ( ! $akismet_key_state || $recheck ) {
6726
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6727
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6728
		}
6729
6730
		$status = 'valid' === $akismet_key_state;
6731
6732
		return $status;
6733
	}
6734
6735
	/**
6736
	 * @deprecated
6737
	 *
6738
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6739
	 */
6740
	public static function is_function_in_backtrace() {
6741
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6742
	}
6743
6744
	/**
6745
	 * Given a minified path, and a non-minified path, will return
6746
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6747
	 *
6748
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6749
	 * root Jetpack directory.
6750
	 *
6751
	 * @since 5.6.0
6752
	 *
6753
	 * @param string $min_path
6754
	 * @param string $non_min_path
6755
	 * @return string The URL to the file
6756
	 */
6757
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6758
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6759
	}
6760
6761
	/**
6762
	 * Checks for whether Jetpack Backup & Scan is enabled.
6763
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6764
	 * @return bool|int|mixed
6765
	 */
6766
	public static function is_rewind_enabled() {
6767
		if ( ! Jetpack::is_active() ) {
6768
			return false;
6769
		}
6770
6771
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6772
		if ( false === $rewind_enabled ) {
6773
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6774
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6775
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6776
				&& ! empty( $rewind_data['state'] )
6777
				&& 'active' === $rewind_data['state'] )
6778
				? 1
6779
				: 0;
6780
6781
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6782
		}
6783
		return $rewind_enabled;
6784
	}
6785
6786
	/**
6787
	 * Return Calypso environment value; used for developing Jetpack and pairing
6788
	 * it with different Calypso enrionments, such as localhost.
6789
	 *
6790
	 * @since 7.4.0
6791
	 *
6792
	 * @return string Calypso environment
6793
	 */
6794
	public static function get_calypso_env() {
6795
		if ( isset( $_GET['calypso_env'] ) ) {
6796
			return sanitize_key( $_GET['calypso_env'] );
6797
		}
6798
6799
		if ( getenv( 'CALYPSO_ENV' ) ) {
6800
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6801
		}
6802
6803
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6804
			return sanitize_key( CALYPSO_ENV );
6805
		}
6806
6807
		return '';
6808
	}
6809
6810
	/**
6811
	 * Checks whether or not TOS has been agreed upon.
6812
	 * Will return true if a user has clicked to register, or is already connected.
6813
	 */
6814
	public static function jetpack_tos_agreed() {
6815
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6816
	}
6817
6818
	/**
6819
	 * Handles activating default modules as well general cleanup for the new connection.
6820
	 *
6821
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6822
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6823
	 * @param boolean $send_state_messages          Whether to send state messages.
6824
	 * @return void
6825
	 */
6826
	public static function handle_post_authorization_actions(
6827
		$activate_sso = false,
6828
		$redirect_on_activation_error = false,
6829
		$send_state_messages = true
6830
	) {
6831
		$other_modules = $activate_sso
6832
			? array( 'sso' )
6833
			: array();
6834
6835
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6836
			Jetpack::delete_active_modules();
6837
6838
			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...
6839
		} else {
6840
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6841
		}
6842
6843
		// Since this is a fresh connection, be sure to clear out IDC options
6844
		Jetpack_IDC::clear_all_idc_options();
6845
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6846
6847
		// Start nonce cleaner
6848
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6849
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6850
6851
		if ( $send_state_messages ) {
6852
			Jetpack::state( 'message', 'authorized' );
6853
		}
6854
	}
6855
6856
	/**
6857
	 * Returns a boolean for whether backups UI should be displayed or not.
6858
	 *
6859
	 * @return bool Should backups UI be displayed?
6860
	 */
6861
	public static function show_backups_ui() {
6862
		/**
6863
		 * Whether UI for backups should be displayed.
6864
		 *
6865
		 * @since 6.5.0
6866
		 *
6867
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6868
		 */
6869
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6870
	}
6871
6872
	/*
6873
	 * Deprecated manage functions
6874
	 */
6875
	function prepare_manage_jetpack_notice() {
6876
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6877
	}
6878
	function manage_activate_screen() {
6879
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6880
	}
6881
	function admin_jetpack_manage_notice() {
6882
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6883
	}
6884
	function opt_out_jetpack_manage_url() {
6885
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6886
	}
6887
	function opt_in_jetpack_manage_url() {
6888
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6889
	}
6890
	function opt_in_jetpack_manage_notice() {
6891
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6892
	}
6893
	function can_display_jetpack_manage_notice() {
6894
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6895
	}
6896
6897
	/**
6898
	 * Clean leftoveruser meta.
6899
	 *
6900
	 * Delete Jetpack-related user meta when it is no longer needed.
6901
	 *
6902
	 * @since 7.3.0
6903
	 *
6904
	 * @param int $user_id User ID being updated.
6905
	 */
6906
	public static function user_meta_cleanup( $user_id ) {
6907
		$meta_keys = array(
6908
			// AtD removed from Jetpack 7.3
6909
			'AtD_options',
6910
			'AtD_check_when',
6911
			'AtD_guess_lang',
6912
			'AtD_ignored_phrases',
6913
		);
6914
6915
		foreach ( $meta_keys as $meta_key ) {
6916
			if ( get_user_meta( $user_id, $meta_key ) ) {
6917
				delete_user_meta( $user_id, $meta_key );
6918
			}
6919
		}
6920
	}
6921
6922
	function is_active_and_not_development_mode( $maybe ) {
6923
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6924
			return false;
6925
		}
6926
		return true;
6927
	}
6928
}
6929