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