Completed
Push — try/statically-access-asset-to... ( f0c1d6...542253 )
by
unknown
396:52 queued 388:09
created

Jetpack::verify_xml_rpc_signature()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

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

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

Loading history...
463
	 */
464
	static function update_active_modules( $modules ) {
465
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
466
		$active_modules       = Jetpack::get_active_modules();
467
		$new_active_modules   = array_diff( $modules, $current_modules );
468
		$new_inactive_modules = array_diff( $active_modules, $modules );
469
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
470
		$reindexed_modules    = array_values( $new_current_modules );
471
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
472
473
		foreach ( $new_active_modules as $module ) {
474
			/**
475
			 * Fires when a specific module is activated.
476
			 *
477
			 * @since 1.9.0
478
			 *
479
			 * @param string $module Module slug.
480
			 * @param boolean $success whether the module was activated. @since 4.2
481
			 */
482
			do_action( 'jetpack_activate_module', $module, $success );
483
			/**
484
			 * Fires when a module is activated.
485
			 * The dynamic part of the filter, $module, is the module slug.
486
			 *
487
			 * @since 1.9.0
488
			 *
489
			 * @param string $module Module slug.
490
			 */
491
			do_action( "jetpack_activate_module_$module", $module );
492
		}
493
494
		foreach ( $new_inactive_modules as $module ) {
495
			/**
496
			 * Fired after a module has been deactivated.
497
			 *
498
			 * @since 4.2.0
499
			 *
500
			 * @param string $module Module slug.
501
			 * @param boolean $success whether the module was deactivated.
502
			 */
503
			do_action( 'jetpack_deactivate_module', $module, $success );
504
			/**
505
			 * Fires when a module is deactivated.
506
			 * The dynamic part of the filter, $module, is the module slug.
507
			 *
508
			 * @since 1.9.0
509
			 *
510
			 * @param string $module Module slug.
511
			 */
512
			do_action( "jetpack_deactivate_module_$module", $module );
513
		}
514
515
		return $success;
516
	}
517
518
	static function delete_active_modules() {
519
		self::update_active_modules( array() );
520
	}
521
522
	/**
523
	 * Constructor.  Initializes WordPress hooks
524
	 */
525
	private function __construct() {
526
		/*
527
		 * Check for and alert any deprecated hooks
528
		 */
529
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
530
531
		/*
532
		 * Enable enhanced handling of previewing sites in Calypso
533
		 */
534
		if ( Jetpack::is_active() ) {
535
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
536
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
537
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
538
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
539
		}
540
541
		if ( self::jetpack_tos_agreed() ) {
542
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
543
			add_action( 'init', array( $tracking, 'init' ) );
544
		}
545
546
		/*
547
		 * Load things that should only be in Network Admin.
548
		 *
549
		 * For now blow away everything else until a more full
550
		 * understanding of what is needed at the network level is
551
		 * available
552
		 */
553
		if ( is_multisite() ) {
554
			Jetpack_Network::init();
555
		}
556
557
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
558
			return function() {
559
				return wp_generate_password( 32, false );
560
			};
561
		} );
562
563
		$this->connection_manager = new Connection_Manager( );
564
565
		/**
566
		 * Prepare Gutenberg Editor functionality
567
		 */
568
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
569
		Jetpack_Gutenberg::init();
570
		Jetpack_Gutenberg::load_independent_blocks();
571
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
572
573
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
574
575
		// Unlink user before deleting the user from .com
576
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
577
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
578
579
		// Alternate XML-RPC, via ?for=jetpack&jetpack=comms
580
		if ( isset( $_GET['jetpack'] ) && 'comms' == $_GET['jetpack'] && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
581
			if ( ! defined( 'XMLRPC_REQUEST' ) ) {
582
				define( 'XMLRPC_REQUEST', true );
583
			}
584
585
			add_action( 'template_redirect', array( $this, 'alternate_xmlrpc' ) );
586
587
			add_filter( 'xmlrpc_methods', array( $this, 'remove_non_jetpack_xmlrpc_methods' ), 1000 );
588
		}
589
590
		if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
591
			@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
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...
592
593
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
594
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
595
596
			$this->require_jetpack_authentication();
597
598
			if ( Jetpack::is_active() ) {
599
				// Hack to preserve $HTTP_RAW_POST_DATA
600
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
601
602 View Code Duplication
				if ( $this->verify_xml_rpc_signature() ) {
603
					// The actual API methods.
604
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
605
				} else {
606
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
607
					// active Jetpack connection, so that additional users can link their account.
608
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
609
				}
610 View Code Duplication
			} else {
611
				new XMLRPC_Connector( $this->connection_manager );
612
613
				// The bootstrap API methods.
614
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
615
616
				if ( $this->verify_xml_rpc_signature() ) {
617
					// the jetpack Provision method is available for blog-token-signed requests
618
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
619
				}
620
			}
621
622
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
623
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
624
		} elseif (
625
			is_admin() &&
626
			isset( $_POST['action'] ) && (
627
				'jetpack_upload_file' == $_POST['action'] ||
628
				'jetpack_update_file' == $_POST['action']
629
			)
630
		) {
631
			$this->require_jetpack_authentication();
632
			$this->add_remote_request_handlers();
633
		} else {
634
			if ( Jetpack::is_active() ) {
635
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
636
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
637
			} else {
638
				add_action( 'rest_api_init', array( $this, 'initialize_rest_api_registration_connector' ) );
639
			}
640
		}
641
642
		if ( Jetpack::is_active() ) {
643
			Jetpack_Heartbeat::init();
644
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
645
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
646
				Jetpack_Search_Performance_Logger::init();
647
			}
648
		}
649
650
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
651
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
652
653
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
654
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
655
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
656
		}
657
658
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
659
660
		add_action( 'admin_init', array( $this, 'admin_init' ) );
661
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
662
663
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
664
665
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
666
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
667
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
668
669
		// returns HTTPS support status
670
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
671
672
		// JITM AJAX callback function
673
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
674
675
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
676
677
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
678
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
679
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
680
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
681
682
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
683
684
		/**
685
		 * These actions run checks to load additional files.
686
		 * They check for external files or plugins, so they need to run as late as possible.
687
		 */
688
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
689
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
690
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
691
692
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
693
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
694
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
695
696
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
697
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
698
699
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
700
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
701
702
		// A filter to control all just in time messages
703
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
704
705
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
706
707
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
708
		// We should make sure to only do this for front end links.
709
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
710
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
711
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
712
713
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
714
			//so they point moderation links on emails to Calypso
715
			jetpack_require_lib( 'functions.wp-notify' );
716
		}
717
718
		// Update the Jetpack plan from API on heartbeats
719
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
720
721
		/**
722
		 * This is the hack to concatenate all css files into one.
723
		 * For description and reasoning see the implode_frontend_css method
724
		 *
725
		 * Super late priority so we catch all the registered styles
726
		 */
727
		if( !is_admin() ) {
728
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
729
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
730
		}
731
732
733
		/**
734
		 * These are sync actions that we need to keep track of for jitms
735
		 */
736
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
737
738
		// Actually push the stats on shutdown.
739
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
740
			add_action( 'shutdown', array( $this, 'push_stats' ) );
741
		}
742
743
	}
744
745
	function initialize_rest_api_registration_connector() {
746
		new REST_Connector( $this->connection_manager );
747
	}
748
749
	/**
750
	 * This is ported over from the manage module, which has been deprecated and baked in here.
751
	 *
752
	 * @param $domains
753
	 */
754
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
755
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
756
	}
757
758
	/**
759
	 * Return $domains, with 'wordpress.com' appended.
760
	 * This is ported over from the manage module, which has been deprecated and baked in here.
761
	 *
762
	 * @param $domains
763
	 * @return array
764
	 */
765
	function allow_wpcom_domain( $domains ) {
766
		if ( empty( $domains ) ) {
767
			$domains = array();
768
		}
769
		$domains[] = 'wordpress.com';
770
		return array_unique( $domains );
771
	}
772
773
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
774
		$post = get_post( $post_id );
775
776
		if ( empty( $post ) ) {
777
			return $default_url;
778
		}
779
780
		$post_type = $post->post_type;
781
782
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
783
		// https://en.support.wordpress.com/custom-post-types/
784
		$allowed_post_types = array(
785
			'post' => 'post',
786
			'page' => 'page',
787
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
788
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
789
		);
790
791
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
792
			return $default_url;
793
		}
794
795
		$path_prefix = $allowed_post_types[ $post_type ];
796
797
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
798
799
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
800
	}
801
802
	function point_edit_comment_links_to_calypso( $url ) {
803
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
804
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

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

Loading history...
805
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
806
			Jetpack::build_raw_urls( get_home_url() ),
807
			$query_args['amp;c']
808
		) );
809
	}
810
811
	function jetpack_track_last_sync_callback( $params ) {
812
		/**
813
		 * Filter to turn off jitm caching
814
		 *
815
		 * @since 5.4.0
816
		 *
817
		 * @param bool false Whether to cache just in time messages
818
		 */
819
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
820
			return $params;
821
		}
822
823
		if ( is_array( $params ) && isset( $params[0] ) ) {
824
			$option = $params[0];
825
			if ( 'active_plugins' === $option ) {
826
				// use the cache if we can, but not terribly important if it gets evicted
827
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
828
			}
829
		}
830
831
		return $params;
832
	}
833
834
	function jetpack_connection_banner_callback() {
835
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
836
837
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
838
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
839
			wp_send_json_success();
840
		}
841
842
		wp_die();
843
	}
844
845
	/**
846
	 * Removes all XML-RPC methods that are not `jetpack.*`.
847
	 * Only used in our alternate XML-RPC endpoint, where we want to
848
	 * ensure that Core and other plugins' methods are not exposed.
849
	 *
850
	 * @param array $methods
851
	 * @return array filtered $methods
852
	 */
853
	function remove_non_jetpack_xmlrpc_methods( $methods ) {
854
		$jetpack_methods = array();
855
856
		foreach ( $methods as $method => $callback ) {
857
			if ( 0 === strpos( $method, 'jetpack.' ) ) {
858
				$jetpack_methods[ $method ] = $callback;
859
			}
860
		}
861
862
		return $jetpack_methods;
863
	}
864
865
	/**
866
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
867
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
868
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
869
	 * which is accessible via a different URI. Most of the below is copied directly
870
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
871
	 */
872
	function alternate_xmlrpc() {
873
		// phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved
874
		global $HTTP_RAW_POST_DATA;
875
876
		// Some browser-embedded clients send cookies. We don't want them.
877
		$_COOKIE = array();
878
879
		// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
880
		// but we can do it ourself.
881
		if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
882
			$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
883
		}
884
885
		// fix for mozBlog and other cases where '<?xml' isn't on the very first line
886
		if ( isset( $HTTP_RAW_POST_DATA ) ) {
887
			$HTTP_RAW_POST_DATA = trim( $HTTP_RAW_POST_DATA );
888
		}
889
890
		// phpcs:enable
891
892
		include_once( ABSPATH . 'wp-admin/includes/admin.php' );
893
		include_once( ABSPATH . WPINC . '/class-IXR.php' );
894
		include_once( ABSPATH . WPINC . '/class-wp-xmlrpc-server.php' );
895
896
		/**
897
		 * Filters the class used for handling XML-RPC requests.
898
		 *
899
		 * @since 3.1.0
900
		 *
901
		 * @param string $class The name of the XML-RPC server class.
902
		 */
903
		$wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' );
904
		$wp_xmlrpc_server = new $wp_xmlrpc_server_class;
905
906
		// Fire off the request
907
		nocache_headers();
908
		$wp_xmlrpc_server->serve_request();
909
910
		exit;
911
	}
912
913
	/**
914
	 * The callback for the JITM ajax requests.
915
	 */
916
	function jetpack_jitm_ajax_callback() {
917
		// Check for nonce
918
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
919
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
920
		}
921
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
922
			$module_slug = $_REQUEST['jitmModule'];
923
			Jetpack::log( 'activate', $module_slug );
924
			Jetpack::activate_module( $module_slug, false, false );
925
			Jetpack::state( 'message', 'no_message' );
926
927
			//A Jetpack module is being activated through a JITM, track it
928
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
929
			$this->do_stats( 'server_side' );
930
931
			wp_send_json_success();
932
		}
933
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
934
			// get the hide_jitm options array
935
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
936
			$module_slug = $_REQUEST['jitmModule'];
937
938
			if( ! $jetpack_hide_jitm ) {
939
				$jetpack_hide_jitm = array(
940
					$module_slug => 'hide'
941
				);
942
			} else {
943
				$jetpack_hide_jitm[$module_slug] = 'hide';
944
			}
945
946
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
947
948
			//jitm is being dismissed forever, track it
949
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
950
			$this->do_stats( 'server_side' );
951
952
			wp_send_json_success();
953
		}
954 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
955
			$module_slug = $_REQUEST['jitmModule'];
956
957
			// User went to WordPress.com, track this
958
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
959
			$this->do_stats( 'server_side' );
960
961
			wp_send_json_success();
962
		}
963 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
964
			$track = $_REQUEST['jitmModule'];
965
966
			// User is viewing JITM, track it.
967
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
968
			$this->do_stats( 'server_side' );
969
970
			wp_send_json_success();
971
		}
972
	}
973
974
	/**
975
	 * If there are any stats that need to be pushed, but haven't been, push them now.
976
	 */
977
	function push_stats() {
978
		if ( ! empty( $this->stats ) ) {
979
			$this->do_stats( 'server_side' );
980
		}
981
	}
982
983
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
984
		switch( $cap ) {
985
			case 'jetpack_connect' :
986
			case 'jetpack_reconnect' :
987
				if ( Jetpack::is_development_mode() ) {
988
					$caps = array( 'do_not_allow' );
989
					break;
990
				}
991
				/**
992
				 * Pass through. If it's not development mode, these should match disconnect.
993
				 * Let users disconnect if it's development mode, just in case things glitch.
994
				 */
995
			case 'jetpack_disconnect' :
996
				/**
997
				 * In multisite, can individual site admins manage their own connection?
998
				 *
999
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
1000
				 */
1001
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
1002
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
1003
						/**
1004
						 * We need to update the option name -- it's terribly unclear which
1005
						 * direction the override goes.
1006
						 *
1007
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
1008
						 */
1009
						$caps = array( 'do_not_allow' );
1010
						break;
1011
					}
1012
				}
1013
1014
				$caps = array( 'manage_options' );
1015
				break;
1016
			case 'jetpack_manage_modules' :
1017
			case 'jetpack_activate_modules' :
1018
			case 'jetpack_deactivate_modules' :
1019
				$caps = array( 'manage_options' );
1020
				break;
1021
			case 'jetpack_configure_modules' :
1022
				$caps = array( 'manage_options' );
1023
				break;
1024
			case 'jetpack_manage_autoupdates' :
1025
				$caps = array(
1026
					'manage_options',
1027
					'update_plugins',
1028
				);
1029
				break;
1030
			case 'jetpack_network_admin_page':
1031
			case 'jetpack_network_settings_page':
1032
				$caps = array( 'manage_network_plugins' );
1033
				break;
1034
			case 'jetpack_network_sites_page':
1035
				$caps = array( 'manage_sites' );
1036
				break;
1037
			case 'jetpack_admin_page' :
1038
				if ( Jetpack::is_development_mode() ) {
1039
					$caps = array( 'manage_options' );
1040
					break;
1041
				} else {
1042
					$caps = array( 'read' );
1043
				}
1044
				break;
1045
			case 'jetpack_connect_user' :
1046
				if ( Jetpack::is_development_mode() ) {
1047
					$caps = array( 'do_not_allow' );
1048
					break;
1049
				}
1050
				$caps = array( 'read' );
1051
				break;
1052
		}
1053
		return $caps;
1054
	}
1055
1056
	function require_jetpack_authentication() {
1057
		// Don't let anyone authenticate
1058
		$_COOKIE = array();
1059
		remove_all_filters( 'authenticate' );
1060
		remove_all_actions( 'wp_login_failed' );
1061
1062
		if ( Jetpack::is_active() ) {
1063
			// Allow Jetpack authentication
1064
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
1065
		}
1066
	}
1067
1068
	/**
1069
	 * Load language files
1070
	 * @action plugins_loaded
1071
	 */
1072
	public static function plugin_textdomain() {
1073
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1074
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1075
	}
1076
1077
	/**
1078
	 * Register assets for use in various modules and the Jetpack admin page.
1079
	 *
1080
	 * @uses wp_script_is, wp_register_script, plugins_url
1081
	 * @action wp_loaded
1082
	 * @return null
1083
	 */
1084
	public function register_assets() {
1085
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1086
			wp_register_script(
1087
				'spin',
1088
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1089
				false,
1090
				'1.3'
1091
			);
1092
		}
1093
1094 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1095
			wp_register_script(
1096
				'jquery.spin',
1097
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1098
				array( 'jquery', 'spin' ),
1099
				'1.3'
1100
			);
1101
		}
1102
1103 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1104
			wp_register_script(
1105
				'jetpack-gallery-settings',
1106
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1107
				array( 'media-views' ),
1108
				'20121225'
1109
			);
1110
		}
1111
1112 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1113
			wp_register_script(
1114
				'jetpack-twitter-timeline',
1115
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1116
				array( 'jquery' ),
1117
				'4.0.0',
1118
				true
1119
			);
1120
		}
1121
1122
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1123
			wp_register_script(
1124
				'jetpack-facebook-embed',
1125
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1126
				array( 'jquery' ),
1127
				null,
1128
				true
1129
			);
1130
1131
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1132
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1133
			if ( ! is_numeric( $fb_app_id ) ) {
1134
				$fb_app_id = '';
1135
			}
1136
			wp_localize_script(
1137
				'jetpack-facebook-embed',
1138
				'jpfbembed',
1139
				array(
1140
					'appid' => $fb_app_id,
1141
					'locale' => $this->get_locale(),
1142
				)
1143
			);
1144
		}
1145
1146
		/**
1147
		 * As jetpack_register_genericons is by default fired off a hook,
1148
		 * the hook may have already fired by this point.
1149
		 * So, let's just trigger it manually.
1150
		 */
1151
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1152
		jetpack_register_genericons();
1153
1154
		/**
1155
		 * Register the social logos
1156
		 */
1157
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1158
		jetpack_register_social_logos();
1159
1160 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1161
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1162
	}
1163
1164
	/**
1165
	 * Guess locale from language code.
1166
	 *
1167
	 * @param string $lang Language code.
1168
	 * @return string|bool
1169
	 */
1170 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1171
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1172
			return 'en_US';
1173
		}
1174
1175
		if ( ! class_exists( 'GP_Locales' ) ) {
1176
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1177
				return false;
1178
			}
1179
1180
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1181
		}
1182
1183
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1184
			// WP.com: get_locale() returns 'it'
1185
			$locale = GP_Locales::by_slug( $lang );
1186
		} else {
1187
			// Jetpack: get_locale() returns 'it_IT';
1188
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1189
		}
1190
1191
		if ( ! $locale ) {
1192
			return false;
1193
		}
1194
1195
		if ( empty( $locale->facebook_locale ) ) {
1196
			if ( empty( $locale->wp_locale ) ) {
1197
				return false;
1198
			} else {
1199
				// Facebook SDK is smart enough to fall back to en_US if a
1200
				// locale isn't supported. Since supported Facebook locales
1201
				// can fall out of sync, we'll attempt to use the known
1202
				// wp_locale value and rely on said fallback.
1203
				return $locale->wp_locale;
1204
			}
1205
		}
1206
1207
		return $locale->facebook_locale;
1208
	}
1209
1210
	/**
1211
	 * Get the locale.
1212
	 *
1213
	 * @return string|bool
1214
	 */
1215
	function get_locale() {
1216
		$locale = $this->guess_locale_from_lang( get_locale() );
1217
1218
		if ( ! $locale ) {
1219
			$locale = 'en_US';
1220
		}
1221
1222
		return $locale;
1223
	}
1224
1225
	/**
1226
	 * Device Pixels support
1227
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1228
	 */
1229
	function devicepx() {
1230
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1231
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1232
		}
1233
	}
1234
1235
	/**
1236
	 * Return the network_site_url so that .com knows what network this site is a part of.
1237
	 * @param  bool $option
1238
	 * @return string
1239
	 */
1240
	public function jetpack_main_network_site_option( $option ) {
1241
		return network_site_url();
1242
	}
1243
	/**
1244
	 * Network Name.
1245
	 */
1246
	static function network_name( $option = null ) {
1247
		global $current_site;
1248
		return $current_site->site_name;
1249
	}
1250
	/**
1251
	 * Does the network allow new user and site registrations.
1252
	 * @return string
1253
	 */
1254
	static function network_allow_new_registrations( $option = null ) {
1255
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1256
	}
1257
	/**
1258
	 * Does the network allow admins to add new users.
1259
	 * @return boolian
1260
	 */
1261
	static function network_add_new_users( $option = null ) {
1262
		return (bool) get_site_option( 'add_new_users' );
1263
	}
1264
	/**
1265
	 * File upload psace left per site in MB.
1266
	 *  -1 means NO LIMIT.
1267
	 * @return number
1268
	 */
1269
	static function network_site_upload_space( $option = null ) {
1270
		// value in MB
1271
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1272
	}
1273
1274
	/**
1275
	 * Network allowed file types.
1276
	 * @return string
1277
	 */
1278
	static function network_upload_file_types( $option = null ) {
1279
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1280
	}
1281
1282
	/**
1283
	 * Maximum file upload size set by the network.
1284
	 * @return number
1285
	 */
1286
	static function network_max_upload_file_size( $option = null ) {
1287
		// value in KB
1288
		return get_site_option( 'fileupload_maxk', 300 );
1289
	}
1290
1291
	/**
1292
	 * Lets us know if a site allows admins to manage the network.
1293
	 * @return array
1294
	 */
1295
	static function network_enable_administration_menus( $option = null ) {
1296
		return get_site_option( 'menu_items' );
1297
	}
1298
1299
	/**
1300
	 * If a user has been promoted to or demoted from admin, we need to clear the
1301
	 * jetpack_other_linked_admins transient.
1302
	 *
1303
	 * @since 4.3.2
1304
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1305
	 *
1306
	 * @param int    $user_id   The user ID whose role changed.
1307
	 * @param string $role      The new role.
1308
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

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

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

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

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2918
		}
2919
2920
		Jetpack::catch_errors( false );
2921
		/**
2922
		 * Fires when default modules are activated.
2923
		 *
2924
		 * @since 1.9.0
2925
		 *
2926
		 * @param string $min_version Minimum version number required to use modules.
2927
		 * @param string $max_version Maximum version number required to use modules.
2928
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2929
		 */
2930
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2931
	}
2932
2933
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2934
		/**
2935
		 * Fires before a module is activated.
2936
		 *
2937
		 * @since 2.6.0
2938
		 *
2939
		 * @param string $module Module slug.
2940
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2941
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2942
		 */
2943
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2944
2945
		$jetpack = Jetpack::init();
2946
2947
		if ( ! strlen( $module ) )
2948
			return false;
2949
2950
		if ( ! Jetpack::is_module( $module ) )
2951
			return false;
2952
2953
		// If it's already active, then don't do it again
2954
		$active = Jetpack::get_active_modules();
2955
		foreach ( $active as $act ) {
2956
			if ( $act == $module )
2957
				return true;
2958
		}
2959
2960
		$module_data = Jetpack::get_module( $module );
2961
2962
		if ( ! Jetpack::is_active() ) {
2963
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2964
				return false;
2965
2966
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2967
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2968
				return false;
2969
		}
2970
2971
		// Check and see if the old plugin is active
2972
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2973
			// Deactivate the old plugin
2974
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2975
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2976
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2977
				Jetpack::state( 'deactivated_plugins', $module );
2978
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2979
				exit;
2980
			}
2981
		}
2982
2983
		// Protect won't work with mis-configured IPs
2984
		if ( 'protect' === $module ) {
2985
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2986
			if ( ! jetpack_protect_get_ip() ) {
2987
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2988
				return false;
2989
			}
2990
		}
2991
2992
		if ( ! Jetpack_Plan::supports( $module ) ) {
2993
			return false;
2994
		}
2995
2996
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2997
		Jetpack::state( 'module', $module );
2998
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2999
3000
		Jetpack::catch_errors( true );
3001
		ob_start();
3002
		require Jetpack::get_module_path( $module );
3003
		/** This action is documented in class.jetpack.php */
3004
		do_action( 'jetpack_activate_module', $module );
3005
		$active[] = $module;
3006
		Jetpack::update_active_modules( $active );
3007
3008
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3009
		ob_end_clean();
3010
		Jetpack::catch_errors( false );
3011
3012
		if ( $redirect ) {
3013
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3014
		}
3015
		if ( $exit ) {
3016
			exit;
3017
		}
3018
		return true;
3019
	}
3020
3021
	function activate_module_actions( $module ) {
3022
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3023
	}
3024
3025
	public static function deactivate_module( $module ) {
3026
		/**
3027
		 * Fires when a module is deactivated.
3028
		 *
3029
		 * @since 1.9.0
3030
		 *
3031
		 * @param string $module Module slug.
3032
		 */
3033
		do_action( 'jetpack_pre_deactivate_module', $module );
3034
3035
		$jetpack = Jetpack::init();
0 ignored issues
show
Unused Code introduced by
$jetpack is not used, you could remove the assignment.

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

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

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

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

Loading history...
3036
3037
		$active = Jetpack::get_active_modules();
3038
		$new    = array_filter( array_diff( $active, (array) $module ) );
3039
3040
		return self::update_active_modules( $new );
3041
	}
3042
3043
	public static function enable_module_configurable( $module ) {
3044
		$module = Jetpack::get_module_slug( $module );
3045
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3046
	}
3047
3048
	/**
3049
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3050
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3051
	 *
3052
	 * @param string $module Module slug
3053
	 * @return string $url module configuration URL
3054
	 */
3055
	public static function module_configuration_url( $module ) {
3056
		$module = Jetpack::get_module_slug( $module );
3057
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3058
		/**
3059
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3060
		 *
3061
		 * @since 6.9.0
3062
		 *
3063
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3064
		 */
3065
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3066
3067
		return $url;
3068
	}
3069
3070
/* Installation */
3071
	public static function bail_on_activation( $message, $deactivate = true ) {
3072
?>
3073
<!doctype html>
3074
<html>
3075
<head>
3076
<meta charset="<?php bloginfo( 'charset' ); ?>">
3077
<style>
3078
* {
3079
	text-align: center;
3080
	margin: 0;
3081
	padding: 0;
3082
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3083
}
3084
p {
3085
	margin-top: 1em;
3086
	font-size: 18px;
3087
}
3088
</style>
3089
<body>
3090
<p><?php echo esc_html( $message ); ?></p>
3091
</body>
3092
</html>
3093
<?php
3094
		if ( $deactivate ) {
3095
			$plugins = get_option( 'active_plugins' );
3096
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3097
			$update  = false;
3098
			foreach ( $plugins as $i => $plugin ) {
3099
				if ( $plugin === $jetpack ) {
3100
					$plugins[$i] = false;
3101
					$update = true;
3102
				}
3103
			}
3104
3105
			if ( $update ) {
3106
				update_option( 'active_plugins', array_filter( $plugins ) );
3107
			}
3108
		}
3109
		exit;
3110
	}
3111
3112
	/**
3113
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3114
	 * @static
3115
	 */
3116
	public static function plugin_activation( $network_wide ) {
3117
		Jetpack_Options::update_option( 'activated', 1 );
3118
3119
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3120
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3121
		}
3122
3123
		if ( $network_wide )
3124
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3125
3126
		// For firing one-off events (notices) immediately after activation
3127
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3128
3129
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3130
3131
		Jetpack::plugin_initialize();
3132
	}
3133
3134
	public static function get_activation_source( $referer_url ) {
3135
3136
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3137
			return array( 'wp-cli', null );
3138
		}
3139
3140
		$referer = parse_url( $referer_url );
3141
3142
		$source_type = 'unknown';
3143
		$source_query = null;
3144
3145
		if ( ! is_array( $referer ) ) {
3146
			return array( $source_type, $source_query );
3147
		}
3148
3149
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3150
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3151
3152
		if ( isset( $referer['query'] ) ) {
3153
			parse_str( $referer['query'], $query_parts );
3154
		} else {
3155
			$query_parts = array();
3156
		}
3157
3158
		if ( $plugins_path === $referer['path'] ) {
3159
			$source_type = 'list';
3160
		} elseif ( $plugins_install_path === $referer['path'] ) {
3161
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3162
			switch( $tab ) {
3163
				case 'popular':
3164
					$source_type = 'popular';
3165
					break;
3166
				case 'recommended':
3167
					$source_type = 'recommended';
3168
					break;
3169
				case 'favorites':
3170
					$source_type = 'favorites';
3171
					break;
3172
				case 'search':
3173
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3174
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3175
					break;
3176
				default:
3177
					$source_type = 'featured';
3178
			}
3179
		}
3180
3181
		return array( $source_type, $source_query );
3182
	}
3183
3184
	/**
3185
	 * Runs before bumping version numbers up to a new version
3186
	 * @param  string $version    Version:timestamp
3187
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3188
	 * @return null              [description]
3189
	 */
3190
	public static function do_version_bump( $version, $old_version ) {
3191
		if ( ! $old_version ) { // For new sites
3192
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3193
		}
3194
	}
3195
3196
	/**
3197
	 * Sets the internal version number and activation state.
3198
	 * @static
3199
	 */
3200
	public static function plugin_initialize() {
3201
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3202
			Jetpack_Options::update_option( 'activated', 2 );
3203
		}
3204
3205 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3206
			$version = $old_version = JETPACK__VERSION . ':' . time();
3207
			/** This action is documented in class.jetpack.php */
3208
			do_action( 'updating_jetpack_version', $version, false );
3209
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3210
		}
3211
3212
		Jetpack::load_modules();
3213
3214
		Jetpack_Options::delete_option( 'do_activate' );
3215
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3216
	}
3217
3218
	/**
3219
	 * Removes all connection options
3220
	 * @static
3221
	 */
3222
	public static function plugin_deactivation( ) {
3223
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3224
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3225
			Jetpack_Network::init()->deactivate();
3226
		} else {
3227
			Jetpack::disconnect( false );
3228
			//Jetpack_Heartbeat::init()->deactivate();
3229
		}
3230
	}
3231
3232
	/**
3233
	 * Disconnects from the Jetpack servers.
3234
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3235
	 * @static
3236
	 */
3237
	public static function disconnect( $update_activated_state = true ) {
3238
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3239
		Jetpack::clean_nonces( true );
3240
3241
		// If the site is in an IDC because sync is not allowed,
3242
		// let's make sure to not disconnect the production site.
3243
		if ( ! self::validate_sync_error_idc_option() ) {
3244
			$tracking = new Tracking();
3245
			$tracking->record_user_event( 'disconnect_site', array() );
3246
			Jetpack::load_xml_rpc_client();
3247
			$xml = new Jetpack_IXR_Client();
3248
			$xml->query( 'jetpack.deregister' );
3249
		}
3250
3251
		Jetpack_Options::delete_option(
3252
			array(
3253
				'blog_token',
3254
				'user_token',
3255
				'user_tokens',
3256
				'master_user',
3257
				'time_diff',
3258
				'fallback_no_verify_ssl_certs',
3259
			)
3260
		);
3261
3262
		Jetpack_IDC::clear_all_idc_options();
3263
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3264
3265
		if ( $update_activated_state ) {
3266
			Jetpack_Options::update_option( 'activated', 4 );
3267
		}
3268
3269
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3270
			// Check then record unique disconnection if site has never been disconnected previously
3271
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3272
				$jetpack_unique_connection['disconnected'] = 1;
3273
			} else {
3274
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3275
					//track unique disconnect
3276
					$jetpack = Jetpack::init();
3277
3278
					$jetpack->stat( 'connections', 'unique-disconnect' );
3279
					$jetpack->do_stats( 'server_side' );
3280
				}
3281
				// increment number of times disconnected
3282
				$jetpack_unique_connection['disconnected'] += 1;
3283
			}
3284
3285
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3286
		}
3287
3288
		// Delete cached connected user data
3289
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3290
		delete_transient( $transient_key );
3291
3292
		// Delete all the sync related data. Since it could be taking up space.
3293
		Sender::get_instance()->uninstall();
3294
3295
		// Disable the Heartbeat cron
3296
		Jetpack_Heartbeat::init()->deactivate();
3297
	}
3298
3299
	/**
3300
	 * Unlinks the current user from the linked WordPress.com user
3301
	 */
3302
	public static function unlink_user( $user_id = null ) {
3303
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3304
			return false;
3305
3306
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3307
3308
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3309
			return false;
3310
3311
		if ( ! isset( $tokens[ $user_id ] ) )
3312
			return false;
3313
3314
		Jetpack::load_xml_rpc_client();
3315
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3316
		$xml->query( 'jetpack.unlink_user', $user_id );
3317
3318
		unset( $tokens[ $user_id ] );
3319
3320
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3321
3322
		/**
3323
		 * Fires after the current user has been unlinked from WordPress.com.
3324
		 *
3325
		 * @since 4.1.0
3326
		 *
3327
		 * @param int $user_id The current user's ID.
3328
		 */
3329
		do_action( 'jetpack_unlinked_user', $user_id );
3330
3331
		return true;
3332
	}
3333
3334
	/**
3335
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3336
	 */
3337
	public static function try_registration() {
3338
		// The user has agreed to the TOS at some point by now.
3339
		Jetpack_Options::update_option( 'tos_agreed', true );
3340
3341
		// Let's get some testing in beta versions and such.
3342
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3343
			// Before attempting to connect, let's make sure that the domains are viable.
3344
			$domains_to_check = array_unique( array(
3345
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3346
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3347
			) );
3348
			foreach ( $domains_to_check as $domain ) {
3349
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3348 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...
3350
				if ( is_wp_error( $result ) ) {
3351
					return $result;
3352
				}
3353
			}
3354
		}
3355
3356
		$result = Jetpack::register();
3357
3358
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3359
		if ( ! $result || is_wp_error( $result ) ) {
3360
			return $result;
3361
		} else {
3362
			return true;
3363
		}
3364
	}
3365
3366
	/**
3367
	 * Tracking an internal event log. Try not to put too much chaff in here.
3368
	 *
3369
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3370
	 */
3371
	public static function log( $code, $data = null ) {
3372
		// only grab the latest 200 entries
3373
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3374
3375
		// Append our event to the log
3376
		$log_entry = array(
3377
			'time'    => time(),
3378
			'user_id' => get_current_user_id(),
3379
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3380
			'code'    => $code,
3381
		);
3382
		// Don't bother storing it unless we've got some.
3383
		if ( ! is_null( $data ) ) {
3384
			$log_entry['data'] = $data;
3385
		}
3386
		$log[] = $log_entry;
3387
3388
		// Try add_option first, to make sure it's not autoloaded.
3389
		// @todo: Add an add_option method to Jetpack_Options
3390
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3391
			Jetpack_Options::update_option( 'log', $log );
3392
		}
3393
3394
		/**
3395
		 * Fires when Jetpack logs an internal event.
3396
		 *
3397
		 * @since 3.0.0
3398
		 *
3399
		 * @param array $log_entry {
3400
		 *	Array of details about the log entry.
3401
		 *
3402
		 *	@param string time Time of the event.
3403
		 *	@param int user_id ID of the user who trigerred the event.
3404
		 *	@param int blog_id Jetpack Blog ID.
3405
		 *	@param string code Unique name for the event.
3406
		 *	@param string data Data about the event.
3407
		 * }
3408
		 */
3409
		do_action( 'jetpack_log_entry', $log_entry );
3410
	}
3411
3412
	/**
3413
	 * Get the internal event log.
3414
	 *
3415
	 * @param $event (string) - only return the specific log events
3416
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3417
	 *
3418
	 * @return array of log events || WP_Error for invalid params
3419
	 */
3420
	public static function get_log( $event = false, $num = false ) {
3421
		if ( $event && ! is_string( $event ) ) {
3422
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

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

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

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

Loading history...
3423
		}
3424
3425
		if ( $num && ! is_numeric( $num ) ) {
3426
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

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

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

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

Loading history...
3427
		}
3428
3429
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3430
3431
		// If nothing set - act as it did before, otherwise let's start customizing the output
3432
		if ( ! $num && ! $event ) {
3433
			return $entire_log;
3434
		} else {
3435
			$entire_log = array_reverse( $entire_log );
3436
		}
3437
3438
		$custom_log_output = array();
3439
3440
		if ( $event ) {
3441
			foreach ( $entire_log as $log_event ) {
3442
				if ( $event == $log_event[ 'code' ] ) {
3443
					$custom_log_output[] = $log_event;
3444
				}
3445
			}
3446
		} else {
3447
			$custom_log_output = $entire_log;
3448
		}
3449
3450
		if ( $num ) {
3451
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3452
		}
3453
3454
		return $custom_log_output;
3455
	}
3456
3457
	/**
3458
	 * Log modification of important settings.
3459
	 */
3460
	public static function log_settings_change( $option, $old_value, $value ) {
3461
		switch( $option ) {
3462
			case 'jetpack_sync_non_public_post_stati':
3463
				self::log( $option, $value );
3464
				break;
3465
		}
3466
	}
3467
3468
	/**
3469
	 * Return stat data for WPCOM sync
3470
	 */
3471
	public static function get_stat_data( $encode = true, $extended = true ) {
3472
		$data = Jetpack_Heartbeat::generate_stats_array();
3473
3474
		if ( $extended ) {
3475
			$additional_data = self::get_additional_stat_data();
3476
			$data = array_merge( $data, $additional_data );
3477
		}
3478
3479
		if ( $encode ) {
3480
			return json_encode( $data );
3481
		}
3482
3483
		return $data;
3484
	}
3485
3486
	/**
3487
	 * Get additional stat data to sync to WPCOM
3488
	 */
3489
	public static function get_additional_stat_data( $prefix = '' ) {
3490
		$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...
3491
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3492
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3493
		$return["{$prefix}site-count"]     = 0;
3494
3495
		if ( function_exists( 'get_blog_count' ) ) {
3496
			$return["{$prefix}site-count"] = get_blog_count();
3497
		}
3498
		return $return;
3499
	}
3500
3501
	private static function get_site_user_count() {
3502
		global $wpdb;
3503
3504
		if ( function_exists( 'wp_is_large_network' ) ) {
3505
			if ( wp_is_large_network( 'users' ) ) {
3506
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3507
			}
3508
		}
3509 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3510
			// It wasn't there, so regenerate the data and save the transient
3511
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3512
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3513
		}
3514
		return $user_count;
3515
	}
3516
3517
	/* Admin Pages */
3518
3519
	function admin_init() {
3520
		// If the plugin is not connected, display a connect message.
3521
		if (
3522
			// the plugin was auto-activated and needs its candy
3523
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3524
		||
3525
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3526
			! Jetpack_Options::get_option( 'activated' )
3527
		) {
3528
			Jetpack::plugin_initialize();
3529
		}
3530
3531
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3532
			Jetpack_Connection_Banner::init();
3533
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3534
			// Upgrade: 1.1 -> 1.1.1
3535
			// Check and see if host can verify the Jetpack servers' SSL certificate
3536
			$args = array();
3537
			Client::_wp_remote_request(
3538
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3539
				$args,
3540
				true
3541
			);
3542
		}
3543
3544
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3545
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3546
		}
3547
3548
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3549
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3550
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3551
3552
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3553
			// Artificially throw errors in certain whitelisted cases during plugin activation
3554
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3555
		}
3556
3557
		// Add custom column in wp-admin/users.php to show whether user is linked.
3558
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3559
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3560
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3561
	}
3562
3563
	function admin_body_class( $admin_body_class = '' ) {
3564
		$classes = explode( ' ', trim( $admin_body_class ) );
3565
3566
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3567
3568
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3569
		return " $admin_body_class ";
3570
	}
3571
3572
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3573
		return $admin_body_class . ' jetpack-pagestyles ';
3574
	}
3575
3576
	/**
3577
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3578
	 * This function artificially throws errors for such cases (whitelisted).
3579
	 *
3580
	 * @param string $plugin The activated plugin.
3581
	 */
3582
	function throw_error_on_activate_plugin( $plugin ) {
3583
		$active_modules = Jetpack::get_active_modules();
3584
3585
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3586
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3587
			$throw = false;
3588
3589
			// Try and make sure it really was the stats plugin
3590
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3591
				if ( 'stats.php' == basename( $plugin ) ) {
3592
					$throw = true;
3593
				}
3594
			} else {
3595
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3596
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3597
					$throw = true;
3598
				}
3599
			}
3600
3601
			if ( $throw ) {
3602
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3603
			}
3604
		}
3605
	}
3606
3607
	function intercept_plugin_error_scrape_init() {
3608
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3609
	}
3610
3611
	function intercept_plugin_error_scrape( $action, $result ) {
3612
		if ( ! $result ) {
3613
			return;
3614
		}
3615
3616
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3617
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3618
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3619
			}
3620
		}
3621
	}
3622
3623
	function add_remote_request_handlers() {
3624
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3625
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3626
	}
3627
3628
	function remote_request_handlers() {
3629
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

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

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

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

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

Loading history...
3630
3631
		switch ( current_filter() ) {
3632
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3633
			$response = $this->upload_handler();
3634
			break;
3635
3636
		case 'wp_ajax_nopriv_jetpack_update_file' :
3637
			$response = $this->upload_handler( true );
3638
			break;
3639
		default :
3640
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_handler'.

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

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

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

Loading history...
3641
			break;
3642
		}
3643
3644
		if ( ! $response ) {
3645
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
3646
		}
3647
3648
		if ( is_wp_error( $response ) ) {
3649
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
The method get_error_data() does not seem to exist on object<Jetpack_Error>.

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

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

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

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

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

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

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

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

Loading history...
3652
3653
			if ( ! is_int( $status_code ) ) {
3654
				$status_code = 400;
3655
			}
3656
3657
			status_header( $status_code );
3658
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3659
		}
3660
3661
		status_header( 200 );
3662
		if ( true === $response ) {
3663
			exit;
3664
		}
3665
3666
		die( json_encode( (object) $response ) );
3667
	}
3668
3669
	/**
3670
	 * Uploads a file gotten from the global $_FILES.
3671
	 * If `$update_media_item` is true and `post_id` is defined
3672
	 * the attachment file of the media item (gotten through of the post_id)
3673
	 * will be updated instead of add a new one.
3674
	 *
3675
	 * @param  boolean $update_media_item - update media attachment
3676
	 * @return array - An array describing the uploadind files process
3677
	 */
3678
	function upload_handler( $update_media_item = false ) {
3679
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3680
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 405.

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

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

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

Loading history...
3681
		}
3682
3683
		$user = wp_authenticate( '', '' );
3684
		if ( ! $user || is_wp_error( $user ) ) {
3685
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 403.

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

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

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

Loading history...
3686
		}
3687
3688
		wp_set_current_user( $user->ID );
3689
3690
		if ( ! current_user_can( 'upload_files' ) ) {
3691
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

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

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

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

Loading history...
3692
		}
3693
3694
		if ( empty( $_FILES ) ) {
3695
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

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

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

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

Loading history...
3696
		}
3697
3698
		foreach ( array_keys( $_FILES ) as $files_key ) {
3699
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3700
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_hmac'.

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

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

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

Loading history...
3701
			}
3702
		}
3703
3704
		$media_keys = array_keys( $_FILES['media'] );
3705
3706
		$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...
3707
		if ( ! $token || is_wp_error( $token ) ) {
3708
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_token'.

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

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

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

Loading history...
3709
		}
3710
3711
		$uploaded_files = array();
3712
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3713
		unset( $GLOBALS['post'] );
3714
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3715
			$file = array();
3716
			foreach ( $media_keys as $media_key ) {
3717
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3718
			}
3719
3720
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3721
3722
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3723
			if ( $hmac_provided !== $hmac_file ) {
3724
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3725
				continue;
3726
			}
3727
3728
			$_FILES['.jetpack.upload.'] = $file;
3729
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3730
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3731
				$post_id = 0;
3732
			}
3733
3734
			if ( $update_media_item ) {
3735
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3736
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'invalid_input'.

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

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

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

Loading history...
3737
				}
3738
3739
				$media_array = $_FILES['media'];
3740
3741
				$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...
3742
				$file_array['type'] = $media_array['type'][0];
3743
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3744
				$file_array['error'] = $media_array['error'][0];
3745
				$file_array['size'] = $media_array['size'][0];
3746
3747
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3748
3749
				if ( is_wp_error( $edited_media_item ) ) {
3750
					return $edited_media_item;
3751
				}
3752
3753
				$response = (object) array(
3754
					'id'   => (string) $post_id,
3755
					'file' => (string) $edited_media_item->post_title,
3756
					'url'  => (string) wp_get_attachment_url( $post_id ),
3757
					'type' => (string) $edited_media_item->post_mime_type,
3758
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3759
				);
3760
3761
				return (array) array( $response );
3762
			}
3763
3764
			$attachment_id = media_handle_upload(
3765
				'.jetpack.upload.',
3766
				$post_id,
3767
				array(),
3768
				array(
3769
					'action' => 'jetpack_upload_file',
3770
				)
3771
			);
3772
3773
			if ( ! $attachment_id ) {
3774
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3775
			} elseif ( is_wp_error( $attachment_id ) ) {
3776
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3777
			} else {
3778
				$attachment = get_post( $attachment_id );
3779
				$uploaded_files[$index] = (object) array(
3780
					'id'   => (string) $attachment_id,
3781
					'file' => $attachment->post_title,
3782
					'url'  => wp_get_attachment_url( $attachment_id ),
3783
					'type' => $attachment->post_mime_type,
3784
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3785
				);
3786
				// Zip files uploads are not supported unless they are done for installation purposed
3787
				// lets delete them in case something goes wrong in this whole process
3788
				if ( 'application/zip' === $attachment->post_mime_type ) {
3789
					// Schedule a cleanup for 2 hours from now in case of failed install.
3790
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3791
				}
3792
			}
3793
		}
3794
		if ( ! is_null( $global_post ) ) {
3795
			$GLOBALS['post'] = $global_post;
3796
		}
3797
3798
		return $uploaded_files;
3799
	}
3800
3801
	/**
3802
	 * Add help to the Jetpack page
3803
	 *
3804
	 * @since Jetpack (1.2.3)
3805
	 * @return false if not the Jetpack page
3806
	 */
3807
	function admin_help() {
3808
		$current_screen = get_current_screen();
3809
3810
		// Overview
3811
		$current_screen->add_help_tab(
3812
			array(
3813
				'id'		=> 'home',
3814
				'title'		=> __( 'Home', 'jetpack' ),
3815
				'content'	=>
3816
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3817
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3818
					'<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>',
3819
			)
3820
		);
3821
3822
		// Screen Content
3823
		if ( current_user_can( 'manage_options' ) ) {
3824
			$current_screen->add_help_tab(
3825
				array(
3826
					'id'		=> 'settings',
3827
					'title'		=> __( 'Settings', 'jetpack' ),
3828
					'content'	=>
3829
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3830
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3831
						'<ol>' .
3832
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3833
							'<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>' .
3834
						'</ol>' .
3835
						'<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>'
3836
				)
3837
			);
3838
		}
3839
3840
		// Help Sidebar
3841
		$current_screen->set_help_sidebar(
3842
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3843
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3844
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3845
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3846
		);
3847
	}
3848
3849
	function admin_menu_css() {
3850
		wp_enqueue_style( 'jetpack-icons' );
3851
	}
3852
3853
	function admin_menu_order() {
3854
		return true;
3855
	}
3856
3857 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3858
		$jp_menu_order = array();
3859
3860
		foreach ( $menu_order as $index => $item ) {
3861
			if ( $item != 'jetpack' ) {
3862
				$jp_menu_order[] = $item;
3863
			}
3864
3865
			if ( $index == 0 ) {
3866
				$jp_menu_order[] = 'jetpack';
3867
			}
3868
		}
3869
3870
		return $jp_menu_order;
3871
	}
3872
3873
	function admin_banner_styles() {
3874
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3875
3876
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3877
			wp_register_style(
3878
				'jetpack-dops-style',
3879
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3880
				array(),
3881
				JETPACK__VERSION
3882
			);
3883
		}
3884
3885
		wp_enqueue_style(
3886
			'jetpack',
3887
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3888
			array( 'jetpack-dops-style' ),
3889
			 JETPACK__VERSION . '-20121016'
3890
		);
3891
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3892
		wp_style_add_data( 'jetpack', 'suffix', $min );
3893
	}
3894
3895
	function plugin_action_links( $actions ) {
3896
3897
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3898
3899
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3900
			return array_merge(
3901
				$jetpack_home,
3902
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3903
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3904
				$actions
3905
				);
3906
			}
3907
3908
		return array_merge( $jetpack_home, $actions );
3909
	}
3910
3911
	/*
3912
	 * Registration flow:
3913
	 * 1 - ::admin_page_load() action=register
3914
	 * 2 - ::try_registration()
3915
	 * 3 - ::register()
3916
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3917
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3918
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3919
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3920
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3921
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3922
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3923
	 *       jetpack_id, jetpack_secret, jetpack_public
3924
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3925
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3926
	 * 5 - user logs in with WP.com account
3927
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3928
	 *		- Jetpack_Client_Server::authorize()
3929
	 *		- Jetpack_Client_Server::get_token()
3930
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3931
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3932
	 *			- which responds with access_token, token_type, scope
3933
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3934
	 *		- Jetpack::activate_default_modules()
3935
	 *     		- Deactivates deprecated plugins
3936
	 *     		- Activates all default modules
3937
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3938
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3939
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3940
	 *     Done!
3941
	 */
3942
3943
	/**
3944
	 * Handles the page load events for the Jetpack admin page
3945
	 */
3946
	function admin_page_load() {
3947
		$error = false;
3948
3949
		// Make sure we have the right body class to hook stylings for subpages off of.
3950
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3951
3952
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3953
			// Should only be used in intermediate redirects to preserve state across redirects
3954
			Jetpack::restate();
3955
		}
3956
3957
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3958
			// @todo: Add validation against a known whitelist
3959
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3960
			// User clicked in the iframe to link their accounts
3961
			if ( ! Jetpack::is_user_connected() ) {
3962
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3963
3964
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3965
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3966
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3967
3968
				if ( isset( $_GET['notes_iframe'] ) )
3969
					$connect_url .= '&notes_iframe';
3970
				wp_redirect( $connect_url );
3971
				exit;
3972
			} else {
3973
				if ( ! isset( $_GET['calypso_env'] ) ) {
3974
					Jetpack::state( 'message', 'already_authorized' );
3975
					wp_safe_redirect( Jetpack::admin_url() );
3976
					exit;
3977
				} else {
3978
					$connect_url = $this->build_connect_url( true, false, $from );
3979
					$connect_url .= '&already_authorized=true';
3980
					wp_redirect( $connect_url );
3981
					exit;
3982
				}
3983
			}
3984
		}
3985
3986
3987
		if ( isset( $_GET['action'] ) ) {
3988
			switch ( $_GET['action'] ) {
3989
			case 'authorize':
3990
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3991
					Jetpack::state( 'message', 'already_authorized' );
3992
					wp_safe_redirect( Jetpack::admin_url() );
3993
					exit;
3994
				}
3995
				Jetpack::log( 'authorize' );
3996
				$client_server = new Jetpack_Client_Server;
3997
				$client_server->client_authorize();
3998
				exit;
3999
			case 'register' :
4000
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4001
					$error = 'cheatin';
4002
					break;
4003
				}
4004
				check_admin_referer( 'jetpack-register' );
4005
				Jetpack::log( 'register' );
4006
				Jetpack::maybe_set_version_option();
4007
				$registered = Jetpack::try_registration();
4008
				if ( is_wp_error( $registered ) ) {
4009
					$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
The method get_error_code() does not seem to exist on object<WP_Error>.

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

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

Loading history...
4010
					Jetpack::state( 'error', $error );
4011
					Jetpack::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WP_Error>.

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

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

Loading history...
4012
4013
					/**
4014
					 * Jetpack registration Error.
4015
					 *
4016
					 * @since 7.5.0
4017
					 *
4018
					 * @param string|int $error The error code.
4019
					 * @param \WP_Error $registered The error object.
4020
					 */
4021
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4022
					break;
4023
				}
4024
4025
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4026
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4027
4028
				/**
4029
				 * Jetpack registration Success.
4030
				 *
4031
				 * @since 7.5.0
4032
				 *
4033
				 * @param string $from 'from' GET parameter;
4034
				 */
4035
				do_action( 'jetpack_connection_register_success', $from );
4036
4037
				$url = $this->build_connect_url( true, $redirect, $from );
4038
4039
				if ( ! empty( $_GET['onboarding'] ) ) {
4040
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4041
				}
4042
4043
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4044
					$url = add_query_arg( 'auth_approved', 'true', $url );
4045
				}
4046
4047
				wp_redirect( $url );
4048
				exit;
4049
			case 'activate' :
4050
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4051
					$error = 'cheatin';
4052
					break;
4053
				}
4054
4055
				$module = stripslashes( $_GET['module'] );
4056
				check_admin_referer( "jetpack_activate-$module" );
4057
				Jetpack::log( 'activate', $module );
4058
				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...
4059
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4060
				}
4061
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4062
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4063
				exit;
4064
			case 'activate_default_modules' :
4065
				check_admin_referer( 'activate_default_modules' );
4066
				Jetpack::log( 'activate_default_modules' );
4067
				Jetpack::restate();
4068
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4069
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4070
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4071
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4072
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4073
				exit;
4074
			case 'disconnect' :
4075
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4076
					$error = 'cheatin';
4077
					break;
4078
				}
4079
4080
				check_admin_referer( 'jetpack-disconnect' );
4081
				Jetpack::log( 'disconnect' );
4082
				Jetpack::disconnect();
4083
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4084
				exit;
4085
			case 'reconnect' :
4086
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4087
					$error = 'cheatin';
4088
					break;
4089
				}
4090
4091
				check_admin_referer( 'jetpack-reconnect' );
4092
				Jetpack::log( 'reconnect' );
4093
				$this->disconnect();
4094
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4095
				exit;
4096 View Code Duplication
			case 'deactivate' :
4097
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4098
					$error = 'cheatin';
4099
					break;
4100
				}
4101
4102
				$modules = stripslashes( $_GET['module'] );
4103
				check_admin_referer( "jetpack_deactivate-$modules" );
4104
				foreach ( explode( ',', $modules ) as $module ) {
4105
					Jetpack::log( 'deactivate', $module );
4106
					Jetpack::deactivate_module( $module );
4107
					Jetpack::state( 'message', 'module_deactivated' );
4108
				}
4109
				Jetpack::state( 'module', $modules );
4110
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4111
				exit;
4112
			case 'unlink' :
4113
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4114
				check_admin_referer( 'jetpack-unlink' );
4115
				Jetpack::log( 'unlink' );
4116
				$this->unlink_user();
4117
				Jetpack::state( 'message', 'unlinked' );
4118
				if ( 'sub-unlink' == $redirect ) {
4119
					wp_safe_redirect( admin_url() );
4120
				} else {
4121
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4122
				}
4123
				exit;
4124
			case 'onboard' :
4125
				if ( ! current_user_can( 'manage_options' ) ) {
4126
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4127
				} else {
4128
					Jetpack::create_onboarding_token();
4129
					$url = $this->build_connect_url( true );
4130
4131
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4132
						$url = add_query_arg( 'onboarding', $token, $url );
4133
					}
4134
4135
					$calypso_env = $this->get_calypso_env();
4136
					if ( ! empty( $calypso_env ) ) {
4137
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4138
					}
4139
4140
					wp_redirect( $url );
4141
					exit;
4142
				}
4143
				exit;
4144
			default:
4145
				/**
4146
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4147
				 *
4148
				 * @since 2.6.0
4149
				 *
4150
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4151
				 */
4152
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4153
			}
4154
		}
4155
4156
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4157
			self::activate_new_modules( true );
4158
		}
4159
4160
		$message_code = Jetpack::state( 'message' );
4161
		if ( Jetpack::state( 'optin-manage' ) ) {
4162
			$activated_manage = $message_code;
4163
			$message_code = 'jetpack-manage';
4164
		}
4165
4166
		switch ( $message_code ) {
4167
		case 'jetpack-manage':
4168
			$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>';
4169
			if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4170
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4171
			}
4172
			break;
4173
4174
		}
4175
4176
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4177
4178
		if ( ! empty( $deactivated_plugins ) ) {
4179
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4180
			$deactivated_titles  = array();
4181
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4182
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4183
					continue;
4184
				}
4185
4186
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4187
			}
4188
4189
			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...
4190
				if ( $this->message ) {
4191
					$this->message .= "<br /><br />\n";
4192
				}
4193
4194
				$this->message .= wp_sprintf(
4195
					_n(
4196
						'Jetpack contains the most recent version of the old %l plugin.',
4197
						'Jetpack contains the most recent versions of the old %l plugins.',
4198
						count( $deactivated_titles ),
4199
						'jetpack'
4200
					),
4201
					$deactivated_titles
4202
				);
4203
4204
				$this->message .= "<br />\n";
4205
4206
				$this->message .= _n(
4207
					'The old version has been deactivated and can be removed from your site.',
4208
					'The old versions have been deactivated and can be removed from your site.',
4209
					count( $deactivated_titles ),
4210
					'jetpack'
4211
				);
4212
			}
4213
		}
4214
4215
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4216
4217
		if ( $this->message || $this->error || $this->privacy_checks ) {
4218
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4219
		}
4220
4221
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4222
	}
4223
4224
	function admin_notices() {
4225
4226
		if ( $this->error ) {
4227
?>
4228
<div id="message" class="jetpack-message jetpack-err">
4229
	<div class="squeezer">
4230
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4231
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4232
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4233
<?php	endif; ?>
4234
	</div>
4235
</div>
4236
<?php
4237
		}
4238
4239
		if ( $this->message ) {
4240
?>
4241
<div id="message" class="jetpack-message">
4242
	<div class="squeezer">
4243
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4244
	</div>
4245
</div>
4246
<?php
4247
		}
4248
4249
		if ( $this->privacy_checks ) :
4250
			$module_names = $module_slugs = array();
4251
4252
			$privacy_checks = explode( ',', $this->privacy_checks );
4253
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4254
			foreach ( $privacy_checks as $module_slug ) {
4255
				$module = Jetpack::get_module( $module_slug );
4256
				if ( ! $module ) {
4257
					continue;
4258
				}
4259
4260
				$module_slugs[] = $module_slug;
4261
				$module_names[] = "<strong>{$module['name']}</strong>";
4262
			}
4263
4264
			$module_slugs = join( ',', $module_slugs );
4265
?>
4266
<div id="message" class="jetpack-message jetpack-err">
4267
	<div class="squeezer">
4268
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4269
		<p><?php
4270
			echo wp_kses(
4271
				wptexturize(
4272
					wp_sprintf(
4273
						_nx(
4274
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4275
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4276
							count( $privacy_checks ),
4277
							'%l = list of Jetpack module/feature names',
4278
							'jetpack'
4279
						),
4280
						$module_names
4281
					)
4282
				),
4283
				array( 'strong' => true )
4284
			);
4285
4286
			echo "\n<br />\n";
4287
4288
			echo wp_kses(
4289
				sprintf(
4290
					_nx(
4291
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4292
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4293
						count( $privacy_checks ),
4294
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4295
						'jetpack'
4296
					),
4297
					wp_nonce_url(
4298
						Jetpack::admin_url(
4299
							array(
4300
								'page'   => 'jetpack',
4301
								'action' => 'deactivate',
4302
								'module' => urlencode( $module_slugs ),
4303
							)
4304
						),
4305
						"jetpack_deactivate-$module_slugs"
4306
					),
4307
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4308
				),
4309
				array( 'a' => array( 'href' => true, 'title' => true ) )
4310
			);
4311
		?></p>
4312
	</div>
4313
</div>
4314
<?php endif;
4315
	}
4316
4317
	/**
4318
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4319
	 */
4320
	function stat( $group, $detail ) {
4321
		if ( ! isset( $this->stats[ $group ] ) )
4322
			$this->stats[ $group ] = array();
4323
		$this->stats[ $group ][] = $detail;
4324
	}
4325
4326
	/**
4327
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4328
	 */
4329
	function do_stats( $method = '' ) {
4330
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4331
			foreach ( $this->stats as $group => $stats ) {
4332
				if ( is_array( $stats ) && count( $stats ) ) {
4333
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4334
					if ( 'server_side' === $method ) {
4335
						self::do_server_side_stat( $args );
4336
					} else {
4337
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4338
					}
4339
				}
4340
				unset( $this->stats[ $group ] );
4341
			}
4342
		}
4343
	}
4344
4345
	/**
4346
	 * Runs stats code for a one-off, server-side.
4347
	 *
4348
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4349
	 *
4350
	 * @return bool If it worked.
4351
	 */
4352
	static function do_server_side_stat( $args ) {
4353
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4354
		if ( is_wp_error( $response ) )
4355
			return false;
4356
4357
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4358
			return false;
4359
4360
		return true;
4361
	}
4362
4363
	/**
4364
	 * Builds the stats url.
4365
	 *
4366
	 * @param $args array|string The arguments to append to the URL.
4367
	 *
4368
	 * @return string The URL to be pinged.
4369
	 */
4370
	static function build_stats_url( $args ) {
4371
		$defaults = array(
4372
			'v'    => 'wpcom2',
4373
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4374
		);
4375
		$args     = wp_parse_args( $args, $defaults );
4376
		/**
4377
		 * Filter the URL used as the Stats tracking pixel.
4378
		 *
4379
		 * @since 2.3.2
4380
		 *
4381
		 * @param string $url Base URL used as the Stats tracking pixel.
4382
		 */
4383
		$base_url = apply_filters(
4384
			'jetpack_stats_base_url',
4385
			'https://pixel.wp.com/g.gif'
4386
		);
4387
		$url      = add_query_arg( $args, $base_url );
4388
		return $url;
4389
	}
4390
4391
	static function translate_current_user_to_role() {
4392
		foreach ( self::$capability_translations as $role => $cap ) {
4393
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4394
				return $role;
4395
			}
4396
		}
4397
4398
		return false;
4399
	}
4400
4401
	static function translate_user_to_role( $user ) {
4402
		foreach ( self::$capability_translations as $role => $cap ) {
4403
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4404
				return $role;
4405
			}
4406
		}
4407
4408
		return false;
4409
    }
4410
4411
	static function translate_role_to_cap( $role ) {
4412
		if ( ! isset( self::$capability_translations[$role] ) ) {
4413
			return false;
4414
		}
4415
4416
		return self::$capability_translations[$role];
4417
	}
4418
4419
	static function sign_role( $role, $user_id = null ) {
4420
		if ( empty( $user_id ) ) {
4421
			$user_id = (int) get_current_user_id();
4422
		}
4423
4424
		if ( ! $user_id  ) {
4425
			return false;
4426
		}
4427
4428
		$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...
4429
		if ( ! $token || is_wp_error( $token ) ) {
4430
			return false;
4431
		}
4432
4433
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4434
	}
4435
4436
4437
	/**
4438
	 * Builds a URL to the Jetpack connection auth page
4439
	 *
4440
	 * @since 3.9.5
4441
	 *
4442
	 * @param bool $raw If true, URL will not be escaped.
4443
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4444
	 *                              If string, will be a custom redirect.
4445
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4446
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4447
	 *
4448
	 * @return string Connect URL
4449
	 */
4450
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4451
		$site_id = Jetpack_Options::get_option( 'id' );
4452
		$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...
4453
4454
		if ( $register || ! $blog_token || ! $site_id ) {
4455
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4456
4457
			if ( ! empty( $redirect ) ) {
4458
				$url = add_query_arg(
4459
					'redirect',
4460
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4461
					$url
4462
				);
4463
			}
4464
4465
			if( is_network_admin() ) {
4466
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4467
			}
4468
		} else {
4469
4470
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4471
			// because otherwise this logic can get us in to a loop.
4472
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4473
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4474
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4475
4476
				$response = Client::wpcom_json_api_request_as_blog(
4477
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4478
					'1.1'
4479
				);
4480
4481
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4482
4483
					// Generating a register URL instead to refresh the existing token
4484
					return $this->build_connect_url( $raw, $redirect, $from, true );
4485
				}
4486
			}
4487
4488
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4489
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4490
			}
4491
4492
			$role = self::translate_current_user_to_role();
4493
			$signed_role = self::sign_role( $role );
4494
4495
			$user = wp_get_current_user();
4496
4497
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4498
			$redirect = $redirect
4499
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4500
				: $jetpack_admin_page;
4501
4502
			if( isset( $_REQUEST['is_multisite'] ) ) {
4503
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4504
			}
4505
4506
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4507
4508
			/**
4509
			 * Filter the type of authorization.
4510
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4511
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4512
			 *
4513
			 * @since 4.3.3
4514
			 *
4515
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4516
			 */
4517
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4518
4519
4520
			$tracks = new Tracking();
4521
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4522
4523
			$args = urlencode_deep(
4524
				array(
4525
					'response_type' => 'code',
4526
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4527
					'redirect_uri'  => add_query_arg(
4528
						array(
4529
							'action'   => 'authorize',
4530
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4531
							'redirect' => urlencode( $redirect ),
4532
						),
4533
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4534
					),
4535
					'state'         => $user->ID,
4536
					'scope'         => $signed_role,
4537
					'user_email'    => $user->user_email,
4538
					'user_login'    => $user->user_login,
4539
					'is_active'     => Jetpack::is_active(),
4540
					'jp_version'    => JETPACK__VERSION,
4541
					'auth_type'     => $auth_type,
4542
					'secret'        => $secrets['secret_1'],
4543
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4544
					'blogname'      => get_option( 'blogname' ),
4545
					'site_url'      => site_url(),
4546
					'home_url'      => home_url(),
4547
					'site_icon'     => get_site_icon_url(),
4548
					'site_lang'     => get_locale(),
4549
					'_ui'           => $tracks_identity['_ui'],
4550
					'_ut'           => $tracks_identity['_ut'],
4551
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4552
				)
4553
			);
4554
4555
			self::apply_activation_source_to_args( $args );
4556
4557
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4558
		}
4559
4560
		if ( $from ) {
4561
			$url = add_query_arg( 'from', $from, $url );
4562
		}
4563
4564
		// Ensure that class to get the affiliate code is loaded
4565
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4566
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4567
		}
4568
		// Get affiliate code and add it to the URL
4569
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4570
4571
		$calypso_env = $this->get_calypso_env();
4572
4573
		if ( ! empty( $calypso_env ) ) {
4574
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4575
		}
4576
4577
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4578
	}
4579
4580
	/**
4581
	 * Get our assumed site creation date.
4582
	 * Calculated based on the earlier date of either:
4583
	 * - Earliest admin user registration date.
4584
	 * - Earliest date of post of any post type.
4585
	 *
4586
	 * @since 7.2.0
4587
	 *
4588
	 * @return string Assumed site creation date and time.
4589
	 */
4590
	public static function get_assumed_site_creation_date() {
4591
		$earliest_registered_users = get_users( array(
4592
			'role'    => 'administrator',
4593
			'orderby' => 'user_registered',
4594
			'order'   => 'ASC',
4595
			'fields'  => array( 'user_registered' ),
4596
			'number'  => 1,
4597
		) );
4598
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4599
4600
		$earliest_posts = get_posts( array(
4601
			'posts_per_page' => 1,
4602
			'post_type'      => 'any',
4603
			'post_status'    => 'any',
4604
			'orderby'        => 'date',
4605
			'order'          => 'ASC',
4606
		) );
4607
4608
		// If there are no posts at all, we'll count only on user registration date.
4609
		if ( $earliest_posts ) {
4610
			$earliest_post_date = $earliest_posts[0]->post_date;
4611
		} else {
4612
			$earliest_post_date = PHP_INT_MAX;
4613
		}
4614
4615
		return min( $earliest_registration_date, $earliest_post_date );
4616
	}
4617
4618
	public static function apply_activation_source_to_args( &$args ) {
4619
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4620
4621
		if ( $activation_source_name ) {
4622
			$args['_as'] = urlencode( $activation_source_name );
4623
		}
4624
4625
		if ( $activation_source_keyword ) {
4626
			$args['_ak'] = urlencode( $activation_source_keyword );
4627
		}
4628
	}
4629
4630
	function build_reconnect_url( $raw = false ) {
4631
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4632
		return $raw ? $url : esc_url( $url );
4633
	}
4634
4635
	public static function admin_url( $args = null ) {
4636
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4637
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4638
		return $url;
4639
	}
4640
4641
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4642
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4643
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4644
	}
4645
4646
	function dismiss_jetpack_notice() {
4647
4648
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4649
			return;
4650
		}
4651
4652
		switch( $_GET['jetpack-notice'] ) {
4653
			case 'dismiss':
4654
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4655
4656
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4657
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4658
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4659
				}
4660
				break;
4661
			case 'jetpack-protect-multisite-opt-out':
4662
4663
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4664
					// Don't show the banner again
4665
4666
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4667
					// redirect back to the page that had the notice
4668
					if ( wp_get_referer() ) {
4669
						wp_safe_redirect( wp_get_referer() );
4670
					} else {
4671
						// Take me to Jetpack
4672
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4673
					}
4674
				}
4675
				break;
4676
		}
4677
	}
4678
4679
	public static function sort_modules( $a, $b ) {
4680
		if ( $a['sort'] == $b['sort'] )
4681
			return 0;
4682
4683
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4684
	}
4685
4686
	function ajax_recheck_ssl() {
4687
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4688
		$result = Jetpack::permit_ssl( true );
4689
		wp_send_json( array(
4690
			'enabled' => $result,
4691
			'message' => get_transient( 'jetpack_https_test_message' )
4692
		) );
4693
	}
4694
4695
/* Client API */
4696
4697
	/**
4698
	 * Returns the requested Jetpack API URL
4699
	 *
4700
	 * @return string
4701
	 */
4702
	public static function api_url( $relative_url ) {
4703
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
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
	/**
4727
	 * Create a random secret for validating onboarding payload
4728
	 *
4729
	 * @return string Secret token
4730
	 */
4731
	public static function create_onboarding_token() {
4732
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4733
			$token = wp_generate_password( 32, false );
4734
			Jetpack_Options::update_option( 'onboarding', $token );
4735
		}
4736
4737
		return $token;
4738
	}
4739
4740
	/**
4741
	 * Remove the onboarding token
4742
	 *
4743
	 * @return bool True on success, false on failure
4744
	 */
4745
	public static function invalidate_onboarding_token() {
4746
		return Jetpack_Options::delete_option( 'onboarding' );
4747
	}
4748
4749
	/**
4750
	 * Validate an onboarding token for a specific action
4751
	 *
4752
	 * @return boolean True if token/action pair is accepted, false if not
4753
	 */
4754
	public static function validate_onboarding_token_action( $token, $action ) {
4755
		// Compare tokens, bail if tokens do not match
4756
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4757
			return false;
4758
		}
4759
4760
		// List of valid actions we can take
4761
		$valid_actions = array(
4762
			'/jetpack/v4/settings',
4763
		);
4764
4765
		// Whitelist the action
4766
		if ( ! in_array( $action, $valid_actions ) ) {
4767
			return false;
4768
		}
4769
4770
		return true;
4771
	}
4772
4773
	/**
4774
	 * Checks to see if the URL is using SSL to connect with Jetpack
4775
	 *
4776
	 * @since 2.3.3
4777
	 * @return boolean
4778
	 */
4779
	public static function permit_ssl( $force_recheck = false ) {
4780
		// Do some fancy tests to see if ssl is being supported
4781
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4782
			$message = '';
4783
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4784
				$ssl = 0;
4785
			} else {
4786
				switch ( JETPACK_CLIENT__HTTPS ) {
4787
					case 'NEVER':
4788
						$ssl = 0;
4789
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4790
						break;
4791
					case 'ALWAYS':
4792
					case 'AUTO':
4793
					default:
4794
						$ssl = 1;
4795
						break;
4796
				}
4797
4798
				// If it's not 'NEVER', test to see
4799
				if ( $ssl ) {
4800
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4801
						$ssl = 0;
4802
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4803
					} else {
4804
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4805
						if ( is_wp_error( $response ) ) {
4806
							$ssl = 0;
4807
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4808
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4809
							$ssl = 0;
4810
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4811
						}
4812
					}
4813
				}
4814
			}
4815
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4816
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4817
		}
4818
4819
		return (bool) $ssl;
4820
	}
4821
4822
	/*
4823
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4824
	 */
4825
	public function alert_auto_ssl_fail() {
4826
		if ( ! current_user_can( 'manage_options' ) )
4827
			return;
4828
4829
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4830
		?>
4831
4832
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4833
			<div class="jp-banner__content">
4834
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4835
				<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>
4836
				<p>
4837
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4838
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4839
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4840
				</p>
4841
				<p>
4842
					<?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' ),
4843
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4844
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4845
				</p>
4846
			</div>
4847
		</div>
4848
		<style>
4849
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4850
		</style>
4851
		<script type="text/javascript">
4852
			jQuery( document ).ready( function( $ ) {
4853
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4854
					var $this = $( this );
4855
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4856
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4857
					e.preventDefault();
4858
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4859
					$.post( ajaxurl, data )
4860
					  .done( function( response ) {
4861
					  	if ( response.enabled ) {
4862
					  		$( '#jetpack-ssl-warning' ).hide();
4863
					  	} else {
4864
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4865
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4866
					  	}
4867
					  }.bind( $this ) );
4868
				} );
4869
			} );
4870
		</script>
4871
4872
		<?php
4873
	}
4874
4875
	/**
4876
	 * Returns the Jetpack XML-RPC API
4877
	 *
4878
	 * @return string
4879
	 */
4880
	public static function xmlrpc_api_url() {
4881
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4882
		return untrailingslashit( $base ) . '/xmlrpc.php';
4883
	}
4884
4885
	public static function connection() {
4886
		return self::init()->connection_manager;
4887
	}
4888
4889
	/**
4890
	 * Creates two secret tokens and the end of life timestamp for them.
4891
	 *
4892
	 * Note these tokens are unique per call, NOT static per site for connecting.
4893
	 *
4894
	 * @since 2.6
4895
	 * @return array
4896
	 */
4897
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4898
		if ( false === $user_id ) {
4899
			$user_id = get_current_user_id();
4900
		}
4901
4902
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4903
	}
4904
4905
	public static function get_secrets( $action, $user_id ) {
4906
		$secrets = self::connection()->get_secrets( $action, $user_id );
4907
4908
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4909
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

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

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

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

Loading history...
4910
		}
4911
4912
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4913
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

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

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

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

Loading history...
4914
		}
4915
4916
		return $secrets;
4917
	}
4918
4919
	/**
4920
	 * @deprecated 7.5 Use Connection_Manager instead.
4921
	 *
4922
	 * @param $action
4923
	 * @param $user_id
4924
	 */
4925
	public static function delete_secrets( $action, $user_id ) {
4926
		return self::connection()->delete_secrets( $action, $user_id );
4927
	}
4928
4929
	/**
4930
	 * Builds the timeout limit for queries talking with the wpcom servers.
4931
	 *
4932
	 * Based on local php max_execution_time in php.ini
4933
	 *
4934
	 * @since 2.6
4935
	 * @return int
4936
	 * @deprecated
4937
	 **/
4938
	public function get_remote_query_timeout_limit() {
4939
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4940
		return Jetpack::get_max_execution_time();
4941
	}
4942
4943
	/**
4944
	 * Builds the timeout limit for queries talking with the wpcom servers.
4945
	 *
4946
	 * Based on local php max_execution_time in php.ini
4947
	 *
4948
	 * @since 5.4
4949
	 * @return int
4950
	 **/
4951
	public static function get_max_execution_time() {
4952
		$timeout = (int) ini_get( 'max_execution_time' );
4953
4954
		// Ensure exec time set in php.ini
4955
		if ( ! $timeout ) {
4956
			$timeout = 30;
4957
		}
4958
		return $timeout;
4959
	}
4960
4961
	/**
4962
	 * Sets a minimum request timeout, and returns the current timeout
4963
	 *
4964
	 * @since 5.4
4965
	 **/
4966
	public static function set_min_time_limit( $min_timeout ) {
4967
		$timeout = self::get_max_execution_time();
4968
		if ( $timeout < $min_timeout ) {
4969
			$timeout = $min_timeout;
4970
			set_time_limit( $timeout );
4971
		}
4972
		return $timeout;
4973
	}
4974
4975
4976
	/**
4977
	 * Takes the response from the Jetpack register new site endpoint and
4978
	 * verifies it worked properly.
4979
	 *
4980
	 * @since 2.6
4981
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4982
	 **/
4983
	public function validate_remote_register_response( $response ) {
4984
	  if ( is_wp_error( $response ) ) {
4985
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

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...
4986
		}
4987
4988
		$code   = wp_remote_retrieve_response_code( $response );
4989
		$entity = wp_remote_retrieve_body( $response );
4990
		if ( $entity )
4991
			$registration_response = json_decode( $entity );
4992
		else
4993
			$registration_response = false;
4994
4995
		$code_type = intval( $code / 100 );
4996
		if ( 5 == $code_type ) {
4997
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_5??'.

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...
4998
		} elseif ( 408 == $code ) {
4999
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_408'.

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...
5000
		} elseif ( ! empty( $registration_response->error ) ) {
5001
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5002
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5003
			} else {
5004
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5005
			}
5006
5007
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with (string) $registration_response->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...
5008
		} elseif ( 200 != $code ) {
5009
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_bad_response'.

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...
5010
		}
5011
5012
		// Jetpack ID error block
5013
		if ( empty( $registration_response->jetpack_id ) ) {
5014
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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...
5015
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5016
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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...
5017
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5018
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

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...
5019
		}
5020
5021
	    return $registration_response;
5022
	}
5023
	/**
5024
	 * @return bool|WP_Error
5025
	 */
5026
	public static function register() {
5027
		$tracking = new Tracking();
5028
		$tracking->record_user_event( 'jpc_register_begin' );
5029
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5030
		$secrets = Jetpack::generate_secrets( 'register' );
5031
5032 View Code Duplication
		if (
5033
			empty( $secrets['secret_1'] ) ||
5034
			empty( $secrets['secret_2'] ) ||
5035
			empty( $secrets['exp'] )
5036
		) {
5037
			return new Jetpack_Error( 'missing_secrets' );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_secrets'.

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...
5038
		}
5039
5040
		// better to try (and fail) to set a higher timeout than this system
5041
		// supports than to have register fail for more users than it should
5042
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5043
5044
		$gmt_offset = get_option( 'gmt_offset' );
5045
		if ( ! $gmt_offset ) {
5046
			$gmt_offset = 0;
5047
		}
5048
5049
		$stats_options = get_option( 'stats_options' );
5050
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5051
5052
		$tracks = new Tracking();
5053
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
5054
5055
		$args = array(
5056
			'method'  => 'POST',
5057
			'body'    => array(
5058
				'siteurl'         => site_url(),
5059
				'home'            => home_url(),
5060
				'gmt_offset'      => $gmt_offset,
5061
				'timezone_string' => (string) get_option( 'timezone_string' ),
5062
				'site_name'       => (string) get_option( 'blogname' ),
5063
				'secret_1'        => $secrets['secret_1'],
5064
				'secret_2'        => $secrets['secret_2'],
5065
				'site_lang'       => get_locale(),
5066
				'timeout'         => $timeout,
5067
				'stats_id'        => $stats_id,
5068
				'state'           => get_current_user_id(),
5069
				'_ui'             => $tracks_identity['_ui'],
5070
				'_ut'             => $tracks_identity['_ut'],
5071
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
5072
				'jetpack_version' => JETPACK__VERSION
5073
			),
5074
			'headers' => array(
5075
				'Accept' => 'application/json',
5076
			),
5077
			'timeout' => $timeout,
5078
		);
5079
5080
		self::apply_activation_source_to_args( $args['body'] );
5081
5082
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5083
5084
		// Make sure the response is valid and does not contain any Jetpack errors
5085
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5086
		if ( is_wp_error( $registration_details ) ) {
5087
			return $registration_details;
5088
		} elseif ( ! $registration_details ) {
5089
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

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

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

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

Loading history...
5090
		}
5091
5092 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5093
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
Unused Code introduced by
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_secret'.

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...
5094
		}
5095
5096
		if ( isset( $registration_details->jetpack_public ) ) {
5097
			$jetpack_public = (int) $registration_details->jetpack_public;
5098
		} else {
5099
			$jetpack_public = false;
5100
		}
5101
5102
		Jetpack_Options::update_options(
5103
			array(
5104
				'id'         => (int)    $registration_details->jetpack_id,
5105
				'blog_token' => (string) $registration_details->jetpack_secret,
5106
				'public'     => $jetpack_public,
5107
			)
5108
		);
5109
5110
		/**
5111
		 * Fires when a site is registered on WordPress.com.
5112
		 *
5113
		 * @since 3.7.0
5114
		 *
5115
		 * @param int $json->jetpack_id Jetpack Blog ID.
5116
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5117
		 * @param int|bool $jetpack_public Is the site public.
5118
		 */
5119
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5120
5121
		// Initialize Jump Start for the first and only time.
5122
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5123
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5124
5125
			$jetpack = Jetpack::init();
5126
5127
			$jetpack->stat( 'jumpstart', 'unique-views' );
5128
			$jetpack->do_stats( 'server_side' );
5129
		};
5130
5131
		return true;
5132
	}
5133
5134
	/**
5135
	 * If the db version is showing something other that what we've got now, bump it to current.
5136
	 *
5137
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

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

Loading history...
5138
	 */
5139
	public static function maybe_set_version_option() {
5140
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5141
		if ( JETPACK__VERSION != $version ) {
5142
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5143
5144
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5145
				/** This action is documented in class.jetpack.php */
5146
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5147
			}
5148
5149
			return true;
5150
		}
5151
		return false;
5152
	}
5153
5154
/* Client Server API */
5155
5156
	/**
5157
	 * Loads the Jetpack XML-RPC client
5158
	 */
5159
	public static function load_xml_rpc_client() {
5160
		require_once ABSPATH . WPINC . '/class-IXR.php';
5161
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5162
	}
5163
5164
	/**
5165
	 * Resets the saved authentication state in between testing requests.
5166
	 */
5167
	public function reset_saved_auth_state() {
5168
		$this->xmlrpc_verification = null;
5169
		$this->rest_authentication_status = null;
5170
	}
5171
5172
	/**
5173
	 * Verifies the signature of the current request.
5174
	 *
5175
	 * @return false|array
5176
	 */
5177
	function verify_xml_rpc_signature() {
5178
		if ( is_null( $this->xmlrpc_verification ) ) {
5179
			$this->xmlrpc_verification = $this->internal_verify_xml_rpc_signature();
5180
5181
			if ( is_wp_error( $this->xmlrpc_verification ) ) {
5182
				/**
5183
				 * Action for logging XMLRPC signature verification errors. This data is sensitive.
5184
				 *
5185
				 * Error codes:
5186
				 * - malformed_token
5187
				 * - malformed_user_id
5188
				 * - unknown_token
5189
				 * - could_not_sign
5190
				 * - invalid_nonce
5191
				 * - signature_mismatch
5192
				 *
5193
				 * @since 7.5.0
5194
				 *
5195
				 * @param WP_Error $signature_verification_error The verification error
5196
				 */
5197
				do_action( 'jetpack_verify_signature_error', $this->xmlrpc_verification );
5198
			}
5199
		}
5200
5201
		return is_wp_error( $this->xmlrpc_verification ) ? false : $this->xmlrpc_verification;
5202
	}
5203
5204
	/**
5205
	 * Verifies the signature of the current request.
5206
	 *
5207
	 * This function has side effects and should not be used. Instead,
5208
	 * use the memoized version `->verify_xml_rpc_signature()`.
5209
	 *
5210
	 * @internal
5211
	 */
5212
	private function internal_verify_xml_rpc_signature() {
5213
		// It's not for us
5214
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5215
			return false;
5216
		}
5217
5218
		$signature_details = array(
5219
			'token'     => isset( $_GET['token'] )     ? wp_unslash( $_GET['token'] )     : '',
5220
			'timestamp' => isset( $_GET['timestamp'] ) ? wp_unslash( $_GET['timestamp'] ) : '',
5221
			'nonce'     => isset( $_GET['nonce'] )     ? wp_unslash( $_GET['nonce'] )     : '',
5222
			'body_hash' => isset( $_GET['body-hash'] ) ? wp_unslash( $_GET['body-hash'] ) : '',
5223
			'method'    => wp_unslash( $_SERVER['REQUEST_METHOD'] ),
5224
			'url'       => wp_unslash( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ), // Temp - will get real signature URL later.
5225
			'signature' => isset( $_GET['signature'] ) ? wp_unslash( $_GET['signature'] ) : '',
5226
		);
5227
5228
		@list( $token_key, $version, $user_id ) = explode( ':', wp_unslash( $_GET['token'] ) );
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...
5229
		if (
5230
			empty( $token_key )
5231
		||
5232
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5233
		) {
5234
			return new WP_Error( 'malformed_token', 'Malformed token in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_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...
5235
		}
5236
5237
		if ( '0' === $user_id ) {
5238
			$token_type = 'blog';
5239
			$user_id = 0;
5240
		} else {
5241
			$token_type = 'user';
5242
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5243
				return new WP_Error( 'malformed_user_id', 'Malformed user_id in request', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'malformed_user_id'.

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...
5244
			}
5245
			$user_id = (int) $user_id;
5246
5247
			$user = new WP_User( $user_id );
5248
			if ( ! $user || ! $user->exists() ) {
5249
				return new WP_Error( 'unknown_user', sprintf( 'User %d does not exist', $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unknown_user'.

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...
5250
			}
5251
		}
5252
5253
		$token = Jetpack_Data::get_access_token( $user_id, $token_key, false );
0 ignored issues
show
Documentation introduced by
$user_id 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...
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...
5254
		if ( is_wp_error( $token ) ) {
5255
			$token->add_data( compact( 'signature_details' ) );
5256
			return $token;
5257
		} elseif ( ! $token ) {
5258
			return new WP_Error( 'unknown_token', sprintf( 'Token %s:%s:%d does not exist', $token_key, $version, $user_id ), compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_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...
5259
		}
5260
5261
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5262
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5263
			$post_data   = $_POST;
5264
			$file_hashes = array();
5265
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5266
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5267
					continue;
5268
				}
5269
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5270
				$file_hashes[$post_data_key] = $post_data_value;
5271
			}
5272
5273
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5274
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5275
				$post_data[$post_data_key] = $post_data_value;
5276
			}
5277
5278
			ksort( $post_data );
5279
5280
			$body = http_build_query( stripslashes_deep( $post_data ) );
5281
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5282
			$body = file_get_contents( 'php://input' );
5283
		} else {
5284
			$body = null;
5285
		}
5286
5287
		$signature = $jetpack_signature->sign_current_request(
5288
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5289
		);
5290
5291
		$signature_details['url'] = $jetpack_signature->current_request_url;
5292
5293
		if ( ! $signature ) {
5294
			return new WP_Error( 'could_not_sign', 'Unknown signature error', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'could_not_sign'.

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

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

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

Loading history...
5295
		} else if ( is_wp_error( $signature ) ) {
5296
			return $signature;
5297
		}
5298
5299
		$timestamp = (int) $_GET['timestamp'];
5300
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5301
5302
		// Use up the nonce regardless of whether the signature matches.
5303
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5304
			return new WP_Error( 'invalid_nonce', 'Could not add nonce', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_nonce'.

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...
5305
		}
5306
5307
		// Be careful about what you do with this debugging data.
5308
		// If a malicious requester has access to the expected signature,
5309
		// bad things might be possible.
5310
		$signature_details['expected'] = $signature;
5311
5312
		if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5313
			return new WP_Error( 'signature_mismatch', 'Signature mismatch', compact( 'signature_details' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'signature_mismatch'.

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...
5314
		}
5315
5316
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5317
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5318
			if ( ! empty( $_GET['onboarding'] ) ) {
5319
				$jpo = $_GET;
5320
			} else {
5321
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5322
			}
5323
5324
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5325
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5326
5327
			if (
5328
				isset( $jpo_user ) && isset( $jpo_token ) &&
5329
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5330
				isset( $_GET['rest_route'] ) &&
5331
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5332
			) {
5333
				$jpUser = get_user_by( 'email', $jpo_user );
5334
				if ( is_a( $jpUser, 'WP_User' ) ) {
5335
					wp_set_current_user( $jpUser->ID );
5336
					$user_can = is_multisite()
5337
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5338
						: current_user_can( 'manage_options' );
5339
					if ( $user_can ) {
5340
						$token_type = 'user';
5341
						$token->external_user_id = $jpUser->ID;
5342
					}
5343
				}
5344
			}
5345
		}
5346
5347
		return array(
5348
			'type'      => $token_type,
5349
			'token_key' => $token_key,
5350
			'user_id'   => $token->external_user_id,
5351
		);
5352
	}
5353
5354
	/**
5355
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5356
	 */
5357
	function authenticate_jetpack( $user, $username, $password ) {
5358
		if ( is_a( $user, 'WP_User' ) ) {
5359
			return $user;
5360
		}
5361
5362
		$token_details = $this->verify_xml_rpc_signature();
5363
5364
		if ( ! $token_details ) {
5365
			return $user;
5366
		}
5367
5368
		if ( 'user' !== $token_details['type'] ) {
5369
			return $user;
5370
		}
5371
5372
		if ( ! $token_details['user_id'] ) {
5373
			return $user;
5374
		}
5375
5376
		nocache_headers();
5377
5378
		return new WP_User( $token_details['user_id'] );
5379
	}
5380
5381
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5382
	// Uses the existing XMLRPC request signing implementation.
5383
	function wp_rest_authenticate( $user ) {
5384
		if ( ! empty( $user ) ) {
5385
			// Another authentication method is in effect.
5386
			return $user;
5387
		}
5388
5389
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5390
			// Nothing to do for this authentication method.
5391
			return null;
5392
		}
5393
5394
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5395
			// Nothing to do for this authentication method.
5396
			return null;
5397
		}
5398
5399
		// Ensure that we always have the request body available.  At this
5400
		// point, the WP REST API code to determine the request body has not
5401
		// run yet.  That code may try to read from 'php://input' later, but
5402
		// this can only be done once per request in PHP versions prior to 5.6.
5403
		// So we will go ahead and perform this read now if needed, and save
5404
		// the request body where both the Jetpack signature verification code
5405
		// and the WP REST API code can see it.
5406
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5407
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5408
		}
5409
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5410
5411
		// Only support specific request parameters that have been tested and
5412
		// are known to work with signature verification.  A different method
5413
		// can be passed to the WP REST API via the '?_method=' parameter if
5414
		// needed.
5415
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5416
			$this->rest_authentication_status = new WP_Error(
5417
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5418
				__( 'This request method is not supported.', 'jetpack' ),
5419
				array( 'status' => 400 )
5420
			);
5421
			return null;
5422
		}
5423
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5424
			$this->rest_authentication_status = new WP_Error(
5425
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

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

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

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

Loading history...
5426
				__( 'This request method does not support body parameters.', 'jetpack' ),
5427
				array( 'status' => 400 )
5428
			);
5429
			return null;
5430
		}
5431
5432
		$verified = $this->verify_xml_rpc_signature();
5433
5434
		if (
5435
			$verified &&
5436
			isset( $verified['type'] ) &&
5437
			'user' === $verified['type'] &&
5438
			! empty( $verified['user_id'] )
5439
		) {
5440
			// Authentication successful.
5441
			$this->rest_authentication_status = true;
5442
			return $verified['user_id'];
5443
		}
5444
5445
		// Something else went wrong.  Probably a signature error.
5446
		$this->rest_authentication_status = new WP_Error(
5447
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

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

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

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

Loading history...
5448
			__( 'The request is not signed correctly.', 'jetpack' ),
5449
			array( 'status' => 400 )
5450
		);
5451
		return null;
5452
	}
5453
5454
	/**
5455
	 * Report authentication status to the WP REST API.
5456
	 *
5457
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

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

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

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

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

Loading history...
5458
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5459
	 */
5460
	public function wp_rest_authentication_errors( $value ) {
5461
		if ( $value !== null ) {
5462
			return $value;
5463
		}
5464
		return $this->rest_authentication_status;
5465
	}
5466
5467
	function add_nonce( $timestamp, $nonce ) {
5468
		global $wpdb;
5469
		static $nonces_used_this_request = array();
5470
5471
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5472
			return $nonces_used_this_request["$timestamp:$nonce"];
5473
		}
5474
5475
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5476
		$timestamp = (int) $timestamp;
5477
		$nonce     = esc_sql( $nonce );
5478
5479
		// Raw query so we can avoid races: add_option will also update
5480
		$show_errors = $wpdb->show_errors( false );
5481
5482
		$old_nonce = $wpdb->get_row(
5483
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5484
		);
5485
5486
		if ( is_null( $old_nonce ) ) {
5487
			$return = $wpdb->query(
5488
				$wpdb->prepare(
5489
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5490
					"jetpack_nonce_{$timestamp}_{$nonce}",
5491
					time(),
5492
					'no'
5493
				)
5494
			);
5495
		} else {
5496
			$return = false;
5497
		}
5498
5499
		$wpdb->show_errors( $show_errors );
5500
5501
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5502
5503
		return $return;
5504
	}
5505
5506
	/**
5507
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5508
	 * Capture it here so we can verify the signature later.
5509
	 */
5510
	function xmlrpc_methods( $methods ) {
5511
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5512
		return $methods;
5513
	}
5514
5515
	function public_xmlrpc_methods( $methods ) {
5516
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5517
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5518
		}
5519
		return $methods;
5520
	}
5521
5522
	function jetpack_getOptions( $args ) {
5523
		global $wp_xmlrpc_server;
5524
5525
		$wp_xmlrpc_server->escape( $args );
5526
5527
		$username	= $args[1];
5528
		$password	= $args[2];
5529
5530
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5531
			return $wp_xmlrpc_server->error;
5532
		}
5533
5534
		$options = array();
5535
		$user_data = $this->get_connected_user_data();
5536
		if ( is_array( $user_data ) ) {
5537
			$options['jetpack_user_id'] = array(
5538
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5539
				'readonly'      => true,
5540
				'value'         => $user_data['ID'],
5541
			);
5542
			$options['jetpack_user_login'] = array(
5543
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5544
				'readonly'      => true,
5545
				'value'         => $user_data['login'],
5546
			);
5547
			$options['jetpack_user_email'] = array(
5548
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5549
				'readonly'      => true,
5550
				'value'         => $user_data['email'],
5551
			);
5552
			$options['jetpack_user_site_count'] = array(
5553
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5554
				'readonly'      => true,
5555
				'value'         => $user_data['site_count'],
5556
			);
5557
		}
5558
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5559
		$args = stripslashes_deep( $args );
5560
		return $wp_xmlrpc_server->wp_getOptions( $args );
5561
	}
5562
5563
	function xmlrpc_options( $options ) {
5564
		$jetpack_client_id = false;
5565
		if ( self::is_active() ) {
5566
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5567
		}
5568
		$options['jetpack_version'] = array(
5569
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5570
				'readonly'      => true,
5571
				'value'         => JETPACK__VERSION,
5572
		);
5573
5574
		$options['jetpack_client_id'] = array(
5575
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5576
				'readonly'      => true,
5577
				'value'         => $jetpack_client_id,
5578
		);
5579
		return $options;
5580
	}
5581
5582
	public static function clean_nonces( $all = false ) {
5583
		global $wpdb;
5584
5585
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5586
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5587
5588
		if ( true !== $all ) {
5589
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5590
			$sql_args[] = time() - 3600;
5591
		}
5592
5593
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5594
5595
		$sql = $wpdb->prepare( $sql, $sql_args );
5596
5597
		for ( $i = 0; $i < 1000; $i++ ) {
5598
			if ( ! $wpdb->query( $sql ) ) {
5599
				break;
5600
			}
5601
		}
5602
	}
5603
5604
	/**
5605
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5606
	 * SET: state( $key, $value );
5607
	 * GET: $value = state( $key );
5608
	 *
5609
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

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

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

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

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

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

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

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

Loading history...
5611
	 * @param bool $restate private
5612
	 */
5613
	public static function state( $key = null, $value = null, $restate = false ) {
5614
		static $state = array();
5615
		static $path, $domain;
5616
		if ( ! isset( $path ) ) {
5617
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5618
			$admin_url = Jetpack::admin_url();
5619
			$bits      = wp_parse_url( $admin_url );
5620
5621
			if ( is_array( $bits ) ) {
5622
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5623
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5624
			} else {
5625
				$path = $domain = null;
5626
			}
5627
		}
5628
5629
		// Extract state from cookies and delete cookies
5630
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5631
			$yum = $_COOKIE[ 'jetpackState' ];
5632
			unset( $_COOKIE[ 'jetpackState' ] );
5633
			foreach ( $yum as $k => $v ) {
5634
				if ( strlen( $v ) )
5635
					$state[ $k ] = $v;
5636
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5637
			}
5638
		}
5639
5640
		if ( $restate ) {
5641
			foreach ( $state as $k => $v ) {
5642
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5643
			}
5644
			return;
5645
		}
5646
5647
		// Get a state variable
5648
		if ( isset( $key ) && ! isset( $value ) ) {
5649
			if ( array_key_exists( $key, $state ) )
5650
				return $state[ $key ];
5651
			return null;
5652
		}
5653
5654
		// Set a state variable
5655
		if ( isset ( $key ) && isset( $value ) ) {
5656
			if( is_array( $value ) && isset( $value[0] ) ) {
5657
				$value = $value[0];
5658
			}
5659
			$state[ $key ] = $value;
5660
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5661
		}
5662
	}
5663
5664
	public static function restate() {
5665
		Jetpack::state( null, null, true );
5666
	}
5667
5668
	public static function check_privacy( $file ) {
5669
		static $is_site_publicly_accessible = null;
5670
5671
		if ( is_null( $is_site_publicly_accessible ) ) {
5672
			$is_site_publicly_accessible = false;
5673
5674
			Jetpack::load_xml_rpc_client();
5675
			$rpc = new Jetpack_IXR_Client();
5676
5677
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5678
			if ( $success ) {
5679
				$response = $rpc->getResponse();
5680
				if ( $response ) {
5681
					$is_site_publicly_accessible = true;
5682
				}
5683
			}
5684
5685
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5686
		}
5687
5688
		if ( $is_site_publicly_accessible ) {
5689
			return;
5690
		}
5691
5692
		$module_slug = self::get_module_slug( $file );
5693
5694
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5695
		if ( ! $privacy_checks ) {
5696
			$privacy_checks = $module_slug;
5697
		} else {
5698
			$privacy_checks .= ",$module_slug";
5699
		}
5700
5701
		Jetpack::state( 'privacy_checks', $privacy_checks );
5702
	}
5703
5704
	/**
5705
	 * Helper method for multicall XMLRPC.
5706
	 */
5707
	public static function xmlrpc_async_call() {
5708
		global $blog_id;
5709
		static $clients = array();
5710
5711
		$client_blog_id = is_multisite() ? $blog_id : 0;
5712
5713
		if ( ! isset( $clients[$client_blog_id] ) ) {
5714
			Jetpack::load_xml_rpc_client();
5715
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5716
			if ( function_exists( 'ignore_user_abort' ) ) {
5717
				ignore_user_abort( true );
5718
			}
5719
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5720
		}
5721
5722
		$args = func_get_args();
5723
5724
		if ( ! empty( $args[0] ) ) {
5725
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5726
		} elseif ( is_multisite() ) {
5727
			foreach ( $clients as $client_blog_id => $client ) {
5728
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5729
					continue;
5730
				}
5731
5732
				$switch_success = switch_to_blog( $client_blog_id, true );
5733
				if ( ! $switch_success ) {
5734
					continue;
5735
				}
5736
5737
				flush();
5738
				$client->query();
5739
5740
				restore_current_blog();
5741
			}
5742
		} else {
5743
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5744
				flush();
5745
				$clients[0]->query();
5746
			}
5747
		}
5748
	}
5749
5750
	public static function staticize_subdomain( $url ) {
5751
5752
		// Extract hostname from URL
5753
		$host = parse_url( $url, PHP_URL_HOST );
5754
5755
		// Explode hostname on '.'
5756
		$exploded_host = explode( '.', $host );
5757
5758
		// Retrieve the name and TLD
5759
		if ( count( $exploded_host ) > 1 ) {
5760
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5761
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5762
			// Rebuild domain excluding subdomains
5763
			$domain = $name . '.' . $tld;
5764
		} else {
5765
			$domain = $host;
5766
		}
5767
		// Array of Automattic domains
5768
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5769
5770
		// Return $url if not an Automattic domain
5771
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5772
			return $url;
5773
		}
5774
5775
		if ( is_ssl() ) {
5776
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5777
		}
5778
5779
		srand( crc32( basename( $url ) ) );
5780
		$static_counter = rand( 0, 2 );
5781
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5782
5783
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5784
	}
5785
5786
/* JSON API Authorization */
5787
5788
	/**
5789
	 * Handles the login action for Authorizing the JSON API
5790
	 */
5791
	function login_form_json_api_authorization() {
5792
		$this->verify_json_api_authorization_request();
5793
5794
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5795
5796
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5797
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5798
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5799
	}
5800
5801
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5802
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5803
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5804
			return $url;
5805
		}
5806
5807
		$parsed_url = parse_url( $url );
5808
		$url = strtok( $url, '?' );
5809
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5810
		if ( ! empty( $parsed_url['query'] ) )
5811
			$url .= "&{$parsed_url['query']}";
5812
5813
		return $url;
5814
	}
5815
5816
	// Make sure the POSTed request is handled by the same action
5817
	function preserve_action_in_login_form_for_json_api_authorization() {
5818
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5819
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5820
	}
5821
5822
	// If someone logs in to approve API access, store the Access Code in usermeta
5823
	function store_json_api_authorization_token( $user_login, $user ) {
5824
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5825
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5826
		$token = wp_generate_password( 32, false );
5827
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5828
	}
5829
5830
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5831
	function allow_wpcom_public_api_domain( $domains ) {
5832
		$domains[] = 'public-api.wordpress.com';
5833
		return $domains;
5834
	}
5835
5836
	static function is_redirect_encoded( $redirect_url ) {
5837
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5838
	}
5839
5840
	// Add all wordpress.com environments to the safe redirect whitelist
5841
	function allow_wpcom_environments( $domains ) {
5842
		$domains[] = 'wordpress.com';
5843
		$domains[] = 'wpcalypso.wordpress.com';
5844
		$domains[] = 'horizon.wordpress.com';
5845
		$domains[] = 'calypso.localhost';
5846
		return $domains;
5847
	}
5848
5849
	// Add the Access Code details to the public-api.wordpress.com redirect
5850
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5851
		return add_query_arg(
5852
			urlencode_deep(
5853
				array(
5854
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5855
					'jetpack-user-id' => (int) $user->ID,
5856
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5857
				)
5858
			),
5859
			$redirect_to
5860
		);
5861
	}
5862
5863
5864
	/**
5865
	 * Verifies the request by checking the signature
5866
	 *
5867
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5868
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5869
	 *
5870
	 * @param null|array $environment
5871
	 */
5872
	function verify_json_api_authorization_request( $environment = null ) {
5873
		$environment = is_null( $environment )
5874
			? $_REQUEST
5875
			: $environment;
5876
5877
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
5878
		$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...
5879
		if ( ! $token || empty( $token->secret ) ) {
5880
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5881
		}
5882
5883
		$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' );
5884
5885
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5886
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5887
			/**
5888
			 * Jetpack authorisation request Error.
5889
			 *
5890
			 * @since 7.5.0
5891
			 *
5892
			 */
5893
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5894
			$die_error = sprintf(
5895
				/* translators: %s is a URL */
5896
				__( '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' ),
5897
				'https://jetpack.com/support/double-encoding/'
5898
			);
5899
		}
5900
5901
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5902
5903
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5904
			$signature = $jetpack_signature->sign_request(
5905
				$environment['token'],
5906
				$environment['timestamp'],
5907
				$environment['nonce'],
5908
				'',
5909
				'GET',
5910
				$environment['jetpack_json_api_original_query'],
5911
				null,
5912
				true
5913
			);
5914
		} else {
5915
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5916
		}
5917
5918
		if ( ! $signature ) {
5919
			wp_die( $die_error );
5920
		} else if ( is_wp_error( $signature ) ) {
5921
			wp_die( $die_error );
5922
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5923
			if ( is_ssl() ) {
5924
				// 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
5925
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5926
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5927
					wp_die( $die_error );
5928
				}
5929
			} else {
5930
				wp_die( $die_error );
5931
			}
5932
		}
5933
5934
		$timestamp = (int) $environment['timestamp'];
5935
		$nonce     = stripslashes( (string) $environment['nonce'] );
5936
5937
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5938
			// De-nonce the nonce, at least for 5 minutes.
5939
			// 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)
5940
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5941
			if ( $old_nonce_time < time() - 300 ) {
5942
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5943
			}
5944
		}
5945
5946
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5947
		$data_filters = array(
5948
			'state'        => 'opaque',
5949
			'client_id'    => 'int',
5950
			'client_title' => 'string',
5951
			'client_image' => 'url',
5952
		);
5953
5954
		foreach ( $data_filters as $key => $sanitation ) {
5955
			if ( ! isset( $data->$key ) ) {
5956
				wp_die( $die_error );
5957
			}
5958
5959
			switch ( $sanitation ) {
5960
			case 'int' :
5961
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5962
				break;
5963
			case 'opaque' :
5964
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5965
				break;
5966
			case 'string' :
5967
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5968
				break;
5969
			case 'url' :
5970
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5971
				break;
5972
			}
5973
		}
5974
5975
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5976
			wp_die( $die_error );
5977
		}
5978
	}
5979
5980
	function login_message_json_api_authorization( $message ) {
5981
		return '<p class="message">' . sprintf(
5982
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5983
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5984
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5985
	}
5986
5987
	/**
5988
	 * Get $content_width, but with a <s>twist</s> filter.
5989
	 */
5990
	public static function get_content_width() {
5991
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5992
			? $GLOBALS['content_width']
5993
			: false;
5994
		/**
5995
		 * Filter the Content Width value.
5996
		 *
5997
		 * @since 2.2.3
5998
		 *
5999
		 * @param string $content_width Content Width value.
6000
		 */
6001
		return apply_filters( 'jetpack_content_width', $content_width );
6002
	}
6003
6004
	/**
6005
	 * Pings the WordPress.com Mirror Site for the specified options.
6006
	 *
6007
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6008
	 *
6009
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6010
	 */
6011
	public function get_cloud_site_options( $option_names ) {
6012
		$option_names = array_filter( (array) $option_names, 'is_string' );
6013
6014
		Jetpack::load_xml_rpc_client();
6015
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6016
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6017
		if ( $xml->isError() ) {
6018
			return array(
6019
				'error_code' => $xml->getErrorCode(),
6020
				'error_msg'  => $xml->getErrorMessage(),
6021
			);
6022
		}
6023
		$cloud_site_options = $xml->getResponse();
6024
6025
		return $cloud_site_options;
6026
	}
6027
6028
	/**
6029
	 * Checks if the site is currently in an identity crisis.
6030
	 *
6031
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6032
	 */
6033
	public static function check_identity_crisis() {
6034
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6035
			return false;
6036
		}
6037
6038
		return Jetpack_Options::get_option( 'sync_error_idc' );
6039
	}
6040
6041
	/**
6042
	 * Checks whether the home and siteurl specifically are whitelisted
6043
	 * Written so that we don't have re-check $key and $value params every time
6044
	 * we want to check if this site is whitelisted, for example in footer.php
6045
	 *
6046
	 * @since  3.8.0
6047
	 * @return bool True = already whitelisted False = not whitelisted
6048
	 */
6049
	public static function is_staging_site() {
6050
		$is_staging = false;
6051
6052
		$known_staging = array(
6053
			'urls' => array(
6054
				'#\.staging\.wpengine\.com$#i', // WP Engine
6055
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6056
				'#\.stage\.site$#i'             // DreamPress
6057
			),
6058
			'constants' => array(
6059
				'IS_WPE_SNAPSHOT',      // WP Engine
6060
				'KINSTA_DEV_ENV',       // Kinsta.com
6061
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6062
				'JETPACK_STAGING_MODE', // Generic
6063
			)
6064
		);
6065
		/**
6066
		 * Filters the flags of known staging sites.
6067
		 *
6068
		 * @since 3.9.0
6069
		 *
6070
		 * @param array $known_staging {
6071
		 *     An array of arrays that each are used to check if the current site is staging.
6072
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6073
		 *     @type array $constants PHP constants of known staging/developement environments.
6074
		 *  }
6075
		 */
6076
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6077
6078
		if ( isset( $known_staging['urls'] ) ) {
6079
			foreach ( $known_staging['urls'] as $url ){
6080
				if ( preg_match( $url, site_url() ) ) {
6081
					$is_staging = true;
6082
					break;
6083
				}
6084
			}
6085
		}
6086
6087
		if ( isset( $known_staging['constants'] ) ) {
6088
			foreach ( $known_staging['constants'] as $constant ) {
6089
				if ( defined( $constant ) && constant( $constant ) ) {
6090
					$is_staging = true;
6091
				}
6092
			}
6093
		}
6094
6095
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6096
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6097
			$is_staging = true;
6098
		}
6099
6100
		/**
6101
		 * Filters is_staging_site check.
6102
		 *
6103
		 * @since 3.9.0
6104
		 *
6105
		 * @param bool $is_staging If the current site is a staging site.
6106
		 */
6107
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6108
	}
6109
6110
	/**
6111
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6112
	 *
6113
	 * @since 4.4.0
6114
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6115
	 *
6116
	 * @return bool
6117
	 */
6118
	public static function validate_sync_error_idc_option() {
6119
		$is_valid = false;
6120
6121
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6122
		if ( false === $idc_allowed ) {
6123
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6124
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6125
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6126
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6127
				$transient_duration = HOUR_IN_SECONDS;
6128
			} else {
6129
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6130
				$idc_allowed = '1';
6131
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6132
			}
6133
6134
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6135
		}
6136
6137
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6138
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6139
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6140
			$local_options = self::get_sync_error_idc_option();
6141
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6142
				$is_valid = true;
6143
			}
6144
		}
6145
6146
		/**
6147
		 * Filters whether the sync_error_idc option is valid.
6148
		 *
6149
		 * @since 4.4.0
6150
		 *
6151
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6152
		 */
6153
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6154
6155
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6156
			// Since the option exists, and did not validate, delete it
6157
			Jetpack_Options::delete_option( 'sync_error_idc' );
6158
		}
6159
6160
		return $is_valid;
6161
	}
6162
6163
	/**
6164
	 * Normalizes a url by doing three things:
6165
	 *  - Strips protocol
6166
	 *  - Strips www
6167
	 *  - Adds a trailing slash
6168
	 *
6169
	 * @since 4.4.0
6170
	 * @param string $url
6171
	 * @return WP_Error|string
6172
	 */
6173
	public static function normalize_url_protocol_agnostic( $url ) {
6174
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6175
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6176
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

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

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

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

Loading history...
6177
		}
6178
6179
		// Strip www and protocols
6180
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6181
		return $url;
6182
	}
6183
6184
	/**
6185
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6186
	 *
6187
	 * @since 4.4.0
6188
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6189
	 *
6190
	 * @param array $response
6191
	 * @return array Array of the local urls, wpcom urls, and error code
6192
	 */
6193
	public static function get_sync_error_idc_option( $response = array() ) {
6194
		// Since the local options will hit the database directly, store the values
6195
		// in a transient to allow for autoloading and caching on subsequent views.
6196
		$local_options = get_transient( 'jetpack_idc_local' );
6197
		if ( false === $local_options ) {
6198
			$local_options = array(
6199
				'home'    => Jetpack_Sync_Functions::home_url(),
6200
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6201
			);
6202
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6203
		}
6204
6205
		$options = array_merge( $local_options, $response );
6206
6207
		$returned_values = array();
6208
		foreach( $options as $key => $option ) {
6209
			if ( 'error_code' === $key ) {
6210
				$returned_values[ $key ] = $option;
6211
				continue;
6212
			}
6213
6214
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6215
				continue;
6216
			}
6217
6218
			$returned_values[ $key ] = $normalized_url;
6219
		}
6220
6221
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6222
6223
		return $returned_values;
6224
	}
6225
6226
	/**
6227
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6228
	 * If set to true, the site will be put into staging mode.
6229
	 *
6230
	 * @since 4.3.2
6231
	 * @return bool
6232
	 */
6233
	public static function sync_idc_optin() {
6234
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6235
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6236
		} else {
6237
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6238
		}
6239
6240
		/**
6241
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6242
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6243
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6244
		 *
6245
		 * @since 4.3.2
6246
		 *
6247
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6248
		 */
6249
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6250
	}
6251
6252
	/**
6253
	 * Maybe Use a .min.css stylesheet, maybe not.
6254
	 *
6255
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6256
	 */
6257
	public static function maybe_min_asset( $url, $path, $plugin ) {
6258
		// Short out on things trying to find actual paths.
6259
		if ( ! $path || empty( $plugin ) ) {
6260
			return $url;
6261
		}
6262
6263
		$path = ltrim( $path, '/' );
6264
6265
		// Strip out the abspath.
6266
		$base = dirname( plugin_basename( $plugin ) );
6267
6268
		// Short out on non-Jetpack assets.
6269
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6270
			return $url;
6271
		}
6272
6273
		// File name parsing.
6274
		$file              = "{$base}/{$path}";
6275
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6276
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6277
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6278
		$extension         = array_shift( $file_name_parts_r );
6279
6280
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6281
			// Already pointing at the minified version.
6282
			if ( 'min' === $file_name_parts_r[0] ) {
6283
				return $url;
6284
			}
6285
6286
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6287
			if ( file_exists( $min_full_path ) ) {
6288
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6289
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6290
				if ( 'css' === $extension ) {
6291
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6292
					self::$min_assets[ $key ] = $path;
6293
				}
6294
			}
6295
		}
6296
6297
		return $url;
6298
	}
6299
6300
	/**
6301
	 * If the asset is minified, let's flag .min as the suffix.
6302
	 *
6303
	 * Attached to `style_loader_src` filter.
6304
	 *
6305
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
6795
	 * @return mixed
6796
	 */
6797
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6798
		if ( ! is_array( $sorted ) ) {
6799
			return $sorted;
6800
		}
6801
6802
		foreach ( $sorted as $box_context => $ids ) {
6803
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6804
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6805
				continue;
6806
			}
6807
6808
			$ids_array = explode( ',', $ids );
6809
			$key = array_search( 'dashboard_stats', $ids_array );
6810
6811
			if ( false !== $key ) {
6812
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6813
				$ids_array[ $key ] = 'jetpack_summary_widget';
6814
				$sorted[ $box_context ] = implode( ',', $ids_array );
6815
				// We've found it, stop searching, and just return.
6816
				break;
6817
			}
6818
		}
6819
6820
		return $sorted;
6821
	}
6822
6823
	public static function dashboard_widget() {
6824
		/**
6825
		 * Fires when the dashboard is loaded.
6826
		 *
6827
		 * @since 3.4.0
6828
		 */
6829
		do_action( 'jetpack_dashboard_widget' );
6830
	}
6831
6832
	public static function dashboard_widget_footer() {
6833
		?>
6834
		<footer>
6835
6836
		<div class="protect">
6837
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6838
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6839
				<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>
6840
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6841
				<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' ); ?>">
6842
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6843
				</a>
6844
			<?php else : ?>
6845
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6846
			<?php endif; ?>
6847
		</div>
6848
6849
		<div class="akismet">
6850
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6851
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6852
				<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>
6853
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6854
				<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">
6855
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6856
				</a>
6857
			<?php else : ?>
6858
				<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>
6859
			<?php endif; ?>
6860
		</div>
6861
6862
		</footer>
6863
		<?php
6864
	}
6865
6866
	/*
6867
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6868
	 */
6869
	function jetpack_icon_user_connected( $columns ) {
6870
		$columns['user_jetpack'] = '';
6871
		return $columns;
6872
	}
6873
6874
	/*
6875
	 * Show Jetpack icon if the user is linked.
6876
	 */
6877
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6878
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6879
			$jetpack_logo = new Jetpack_Logo();
6880
			$emblem_html = sprintf(
6881
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6882
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6883
				$jetpack_logo->get_jp_emblem()
6884
			);
6885
			return $emblem_html;
6886
		}
6887
6888
		return $val;
6889
	}
6890
6891
	/*
6892
	 * Style the Jetpack user column
6893
	 */
6894
	function jetpack_user_col_style() {
6895
		global $current_screen;
6896
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6897
			<style>
6898
				.fixed .column-user_jetpack {
6899
					width: 21px;
6900
				}
6901
				.jp-emblem-user-admin svg {
6902
					width: 20px;
6903
					height: 20px;
6904
				}
6905
				.jp-emblem-user-admin path {
6906
					fill: #00BE28;
6907
				}
6908
			</style>
6909
		<?php }
6910
	}
6911
6912
	/**
6913
	 * Checks if Akismet is active and working.
6914
	 *
6915
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6916
	 * that implied usage of methods present since more recent version.
6917
	 * See https://github.com/Automattic/jetpack/pull/9585
6918
	 *
6919
	 * @since  5.1.0
6920
	 *
6921
	 * @return bool True = Akismet available. False = Aksimet not available.
6922
	 */
6923
	public static function is_akismet_active() {
6924
		static $status = null;
6925
6926
		if ( ! is_null( $status ) ) {
6927
			return $status;
6928
		}
6929
6930
		// Check if a modern version of Akismet is active.
6931
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6932
			$status = false;
6933
			return $status;
6934
		}
6935
6936
		// Make sure there is a key known to Akismet at all before verifying key.
6937
		$akismet_key = Akismet::get_api_key();
6938
		if ( ! $akismet_key ) {
6939
			$status = false;
6940
			return $status;
6941
		}
6942
6943
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6944
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6945
6946
		// 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.
6947
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6948
		// We cache the result of the Akismet key verification for ten minutes.
6949
		if ( ! $akismet_key_state || $recheck ) {
6950
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6951
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6952
		}
6953
6954
		$status = 'valid' === $akismet_key_state;
6955
6956
		return $status;
6957
	}
6958
6959
	/**
6960
	 * Checks if one or more function names is in debug_backtrace
6961
	 *
6962
	 * @param $names Mixed string name of function or array of string names of functions
6963
	 *
6964
	 * @return bool
6965
	 */
6966
	public static function is_function_in_backtrace( $names ) {
6967
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6968
		if ( ! is_array( $names ) ) {
6969
			$names = array( $names );
6970
		}
6971
		$names_as_keys = array_flip( $names );
6972
6973
		//Do check in constant O(1) time for PHP5.5+
6974
		if ( function_exists( 'array_column' ) ) {
6975
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6976
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6977
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6978
			return ! empty ( $intersection );
6979
		}
6980
6981
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6982
		foreach ( $backtrace as $call ) {
6983
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6984
				return true;
6985
			}
6986
		}
6987
		return false;
6988
	}
6989
6990
	/**
6991
	 * Given a minified path, and a non-minified path, will return
6992
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6993
	 *
6994
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6995
	 * root Jetpack directory.
6996
	 *
6997
	 * @since 5.6.0
6998
	 *
6999
	 * @param string $min_path
7000
	 * @param string $non_min_path
7001
	 * @return string The URL to the file
7002
	 */
7003
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7004
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7005
	}
7006
7007
	/**
7008
	 * Checks for whether Jetpack Backup & Scan is enabled.
7009
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
7010
	 * @return bool|int|mixed
7011
	 */
7012
	public static function is_rewind_enabled() {
7013
		if ( ! Jetpack::is_active() ) {
7014
			return false;
7015
		}
7016
7017
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7018
		if ( false === $rewind_enabled ) {
7019
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7020
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7021
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7022
				&& ! empty( $rewind_data['state'] )
7023
				&& 'active' === $rewind_data['state'] )
7024
				? 1
7025
				: 0;
7026
7027
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7028
		}
7029
		return $rewind_enabled;
7030
	}
7031
7032
	/**
7033
	 * Return Calypso environment value; used for developing Jetpack and pairing
7034
	 * it with different Calypso enrionments, such as localhost.
7035
	 *
7036
	 * @since 7.4.0
7037
	 *
7038
	 * @return string Calypso environment
7039
	 */
7040
	public static function get_calypso_env() {
7041
		if ( isset( $_GET['calypso_env'] ) ) {
7042
			return sanitize_key( $_GET['calypso_env'] );
7043
		}
7044
7045
		if ( getenv( 'CALYPSO_ENV' ) ) {
7046
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7047
		}
7048
7049
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7050
			return sanitize_key( CALYPSO_ENV );
7051
		}
7052
7053
		return '';
7054
	}
7055
7056
	/**
7057
	 * Checks whether or not TOS has been agreed upon.
7058
	 * Will return true if a user has clicked to register, or is already connected.
7059
	 */
7060
	public static function jetpack_tos_agreed() {
7061
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7062
	}
7063
7064
	/**
7065
	 * Handles activating default modules as well general cleanup for the new connection.
7066
	 *
7067
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7068
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7069
	 * @param boolean $send_state_messages          Whether to send state messages.
7070
	 * @return void
7071
	 */
7072
	public static function handle_post_authorization_actions(
7073
		$activate_sso = false,
7074
		$redirect_on_activation_error = false,
7075
		$send_state_messages = true
7076
	) {
7077
		$other_modules = $activate_sso
7078
			? array( 'sso' )
7079
			: array();
7080
7081
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7082
			Jetpack::delete_active_modules();
7083
7084
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7085
		} else {
7086
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7087
		}
7088
7089
		// Since this is a fresh connection, be sure to clear out IDC options
7090
		Jetpack_IDC::clear_all_idc_options();
7091
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7092
7093
		// Start nonce cleaner
7094
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7095
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7096
7097
		if ( $send_state_messages ) {
7098
			Jetpack::state( 'message', 'authorized' );
7099
		}
7100
	}
7101
7102
	/**
7103
	 * Returns a boolean for whether backups UI should be displayed or not.
7104
	 *
7105
	 * @return bool Should backups UI be displayed?
7106
	 */
7107
	public static function show_backups_ui() {
7108
		/**
7109
		 * Whether UI for backups should be displayed.
7110
		 *
7111
		 * @since 6.5.0
7112
		 *
7113
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7114
		 */
7115
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7116
	}
7117
7118
	/*
7119
	 * Deprecated manage functions
7120
	 */
7121
	function prepare_manage_jetpack_notice() {
7122
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7123
	}
7124
	function manage_activate_screen() {
7125
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7126
	}
7127
	function admin_jetpack_manage_notice() {
7128
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7129
	}
7130
	function opt_out_jetpack_manage_url() {
7131
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7132
	}
7133
	function opt_in_jetpack_manage_url() {
7134
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7135
	}
7136
	function opt_in_jetpack_manage_notice() {
7137
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7138
	}
7139
	function can_display_jetpack_manage_notice() {
7140
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7141
	}
7142
7143
	/**
7144
	 * Clean leftoveruser meta.
7145
	 *
7146
	 * Delete Jetpack-related user meta when it is no longer needed.
7147
	 *
7148
	 * @since 7.3.0
7149
	 *
7150
	 * @param int $user_id User ID being updated.
7151
	 */
7152
	public static function user_meta_cleanup( $user_id ) {
7153
		$meta_keys = array(
7154
			// AtD removed from Jetpack 7.3
7155
			'AtD_options',
7156
			'AtD_check_when',
7157
			'AtD_guess_lang',
7158
			'AtD_ignored_phrases',
7159
		);
7160
7161
		foreach ( $meta_keys as $meta_key ) {
7162
			if ( get_user_meta( $user_id, $meta_key ) ) {
7163
				delete_user_meta( $user_id, $meta_key );
7164
			}
7165
		}
7166
	}
7167
7168
	function is_active_and_not_development_mode( $maybe ) {
7169
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
7170
			return false;
7171
		}
7172
		return true;
7173
	}
7174
7175
}
7176