Completed
Push — master ( 12c82f...0b6a28 )
by Marin
08:35
created

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