Completed
Push — fix/protect-multisite-activati... ( 487dcc...b52342 )
by Jeremy
25:55 queued 18:04
created

Jetpack::alert_auto_ssl_fail()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 49
rs 9.1127
c 0
b 0
f 0
1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * The handles of scripts that can be loaded asynchronously.
86
	 *
87
	 * @var array
88
	 */
89
	public $async_script_handles = array(
90
		'woocommerce-analytics',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
115
	);
116
117
	/**
118
	 * Map of roles we care about, and their corresponding minimum capabilities.
119
	 *
120
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
121
	 *
122
	 * @access public
123
	 * @static
124
	 *
125
	 * @var array
126
	 */
127
	public static $capability_translations = array(
128
		'administrator' => 'manage_options',
129
		'editor'        => 'edit_others_posts',
130
		'author'        => 'publish_posts',
131
		'contributor'   => 'edit_posts',
132
		'subscriber'    => 'read',
133
	);
134
135
	/**
136
	 * Map of modules that have conflicts with plugins and should not be auto-activated
137
	 * if the plugins are active.  Used by filter_default_modules
138
	 *
139
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
140
	 * change `module-slug` and add this to your plugin:
141
	 *
142
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
143
	 * function my_jetpack_get_default_modules( $modules ) {
144
	 *     return array_diff( $modules, array( 'module-slug' ) );
145
	 * }
146
	 *
147
	 * @var array
148
	 */
149
	private $conflicting_plugins = array(
150
		'comments'          => array(
151
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
152
			'Disqus'                               => 'disqus-comment-system/disqus.php',
153
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
154
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
155
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
156
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
157
		),
158
		'comment-likes' => array(
159
			'Epoch'                                => 'epoch/plugincore.php',
160
		),
161
		'contact-form'      => array(
162
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
163
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
164
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
165
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
166
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
167
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
168
		),
169
		'minileven'         => array(
170
			'WPtouch'                              => 'wptouch/wptouch.php',
171
		),
172
		'latex'             => array(
173
			'LaTeX for WordPress'                  => 'latex/latex.php',
174
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
175
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
176
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
177
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
178
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
179
		),
180
		'protect'           => array(
181
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
182
			'Captcha'                              => 'captcha/captcha.php',
183
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
184
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
185
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
186
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
187
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
188
			'Security-protection'                  => 'security-protection/security-protection.php',
189
			'Login Security'                       => 'login-security/login-security.php',
190
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
191
			'Wordfence Security'                   => 'wordfence/wordfence.php',
192
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
193
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
194
		),
195
		'random-redirect'   => array(
196
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
197
		),
198
		'related-posts'     => array(
199
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
200
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
201
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
202
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
203
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
204
			'outbrain'                             => 'outbrain/outbrain.php',
205
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
206
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
207
		),
208
		'sharedaddy'        => array(
209
			'AddThis'                              => 'addthis/addthis_social_widget.php',
210
			'Add To Any'                           => 'add-to-any/add-to-any.php',
211
			'ShareThis'                            => 'share-this/sharethis.php',
212
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
213
		),
214
		'seo-tools' => array(
215
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'                    => 'autodescription/autodescription.php',
220
		),
221
		'verification-tools' => array(
222
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
223
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
224
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
225
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
226
			'The SEO Framework'                    => 'autodescription/autodescription.php',
227
		),
228
		'widget-visibility' => array(
229
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
230
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
231
		),
232
		'sitemaps' => array(
233
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
234
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
235
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
236
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
237
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
238
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
239
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
240
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242
			'The SEO Framework'                    => 'autodescription/autodescription.php',
243
			'Sitemap'                              => 'sitemap/sitemap.php',
244
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
245
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
246
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
247
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
248
		),
249
		'lazy-images' => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		                                                         // 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		                                                         // Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		                                                         // Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		                                                         // Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		                                                         // Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		                                                         // NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		                                                         // Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		                                                         // Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		                                                         // WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
	//	'twitter/twitter.php',                       // The official one handles this on its own.
321
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 * @var string
342
	 */
343
	public $error = '';
344
345
	/**
346
	 * Modules that need more privacy description.
347
	 * @var string
348
	 */
349
	public $privacy_checks = '';
350
351
	/**
352
	 * Stats to record once the page loads
353
	 *
354
	 * @var array
355
	 */
356
	public $stats = array();
357
358
	/**
359
	 * Jetpack_Sync object
360
	 */
361
	public $sync;
362
363
	/**
364
	 * Verified data for JSON authorization request
365
	 */
366
	public $json_api_authorization_request = array();
367
368
	/**
369
	 * @var \Automattic\Jetpack\Connection\Manager
370
	 */
371
	protected $connection_manager;
372
373
	/**
374
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
375
	 */
376
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
377
378
	/**
379
	 * Holds the singleton instance of this class
380
	 * @since 2.3.3
381
	 * @var Jetpack
382
	 */
383
	static $instance = false;
384
385
	/**
386
	 * Singleton
387
	 * @static
388
	 */
389
	public static function init() {
390
		if ( ! self::$instance ) {
391
			self::$instance = new Jetpack;
392
393
			self::$instance->plugin_upgrade();
394
		}
395
396
		return self::$instance;
397
	}
398
399
	/**
400
	 * Must never be called statically
401
	 */
402
	function plugin_upgrade() {
403
		if ( Jetpack::is_active() ) {
404
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
405
			if ( JETPACK__VERSION != $version ) {
406
				// Prevent multiple upgrades at once - only a single process should trigger
407
				// an upgrade to avoid stampedes
408
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
409
					return;
410
				}
411
412
				// Set a short lock to prevent multiple instances of the upgrade
413
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
414
415
				// check which active modules actually exist and remove others from active_modules list
416
				$unfiltered_modules = Jetpack::get_active_modules();
417
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
418
				if ( array_diff( $unfiltered_modules, $modules ) ) {
419
					Jetpack::update_active_modules( $modules );
420
				}
421
422
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
423
424
				// Upgrade to 4.3.0
425
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
426
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
427
				}
428
429
				// Make sure Markdown for posts gets turned back on
430
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
431
					update_option( 'wpcom_publish_posts_with_markdown', true );
432
				}
433
434
				if ( did_action( 'wp_loaded' ) ) {
435
					self::upgrade_on_load();
436
				} else {
437
					add_action(
438
						'wp_loaded',
439
						array( __CLASS__, 'upgrade_on_load' )
440
					);
441
				}
442
			}
443
		}
444
	}
445
446
	/**
447
	 * Runs upgrade routines that need to have modules loaded.
448
	 */
449
	static function upgrade_on_load() {
450
451
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
452
		// This can happen in case Jetpack has been just upgraded and is
453
		// being initialized late during the page load. In this case we wait
454
		// until the next proper admin page load with Jetpack active.
455
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
456
			delete_transient( self::$plugin_upgrade_lock_key );
457
458
			return;
459
		}
460
461
		Jetpack::maybe_set_version_option();
462
463
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
464
			Jetpack_Widget_Conditions::migrate_post_type_rules();
465
		}
466
467
		if (
468
			class_exists( 'Jetpack_Sitemap_Manager' )
469
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
470
		) {
471
			do_action( 'jetpack_sitemaps_purge_data' );
472
		}
473
474
		// Delete old stats cache
475
		delete_option( 'jetpack_restapi_stats_cache' );
476
477
		delete_transient( self::$plugin_upgrade_lock_key );
478
	}
479
480
	/**
481
	 * Saves all the currently active modules to options.
482
	 * Also fires Action hooks for each newly activated and deactivated module.
483
	 *
484
	 * @param $modules Array Array of active modules to be saved in options.
485
	 *
486
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
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...
487
	 */
488
	static function update_active_modules( $modules ) {
489
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
490
		$active_modules       = Jetpack::get_active_modules();
491
		$new_active_modules   = array_diff( $modules, $current_modules );
492
		$new_inactive_modules = array_diff( $active_modules, $modules );
493
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
494
		$reindexed_modules    = array_values( $new_current_modules );
495
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
496
497
		foreach ( $new_active_modules as $module ) {
498
			/**
499
			 * Fires when a specific module is activated.
500
			 *
501
			 * @since 1.9.0
502
			 *
503
			 * @param string $module Module slug.
504
			 * @param boolean $success whether the module was activated. @since 4.2
505
			 */
506
			do_action( 'jetpack_activate_module', $module, $success );
507
			/**
508
			 * Fires when a module is activated.
509
			 * The dynamic part of the filter, $module, is the module slug.
510
			 *
511
			 * @since 1.9.0
512
			 *
513
			 * @param string $module Module slug.
514
			 */
515
			do_action( "jetpack_activate_module_$module", $module );
516
		}
517
518
		foreach ( $new_inactive_modules as $module ) {
519
			/**
520
			 * Fired after a module has been deactivated.
521
			 *
522
			 * @since 4.2.0
523
			 *
524
			 * @param string $module Module slug.
525
			 * @param boolean $success whether the module was deactivated.
526
			 */
527
			do_action( 'jetpack_deactivate_module', $module, $success );
528
			/**
529
			 * Fires when a module is deactivated.
530
			 * The dynamic part of the filter, $module, is the module slug.
531
			 *
532
			 * @since 1.9.0
533
			 *
534
			 * @param string $module Module slug.
535
			 */
536
			do_action( "jetpack_deactivate_module_$module", $module );
537
		}
538
539
		return $success;
540
	}
541
542
	static function delete_active_modules() {
543
		self::update_active_modules( array() );
544
	}
545
546
	/**
547
	 * Constructor.  Initializes WordPress hooks
548
	 */
549
	private function __construct() {
550
		/*
551
		 * Check for and alert any deprecated hooks
552
		 */
553
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
554
555
		/*
556
		 * Enable enhanced handling of previewing sites in Calypso
557
		 */
558
		if ( Jetpack::is_active() ) {
559
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
560
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
561
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
562
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
563
		}
564
565
		if ( self::jetpack_tos_agreed() ) {
566
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
567
			add_action( 'init', array( $tracking, 'init' ) );
568
		}
569
570
571
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
572
			return function() {
573
				return wp_generate_password( 32, false );
574
			};
575
		} );
576
577
		$this->connection_manager = new Connection_Manager();
578
		$this->connection_manager->init();
579
580
		/*
581
		 * Load things that should only be in Network Admin.
582
		 *
583
		 * For now blow away everything else until a more full
584
		 * understanding of what is needed at the network level is
585
		 * available
586
		 */
587
		if ( is_multisite() ) {
588
			$network = Jetpack_Network::init();
589
			$network->set_connection( $this->connection_manager );
590
		}
591
592
		add_filter(
593
			'jetpack_signature_check_token',
594
			array( __CLASS__, 'verify_onboarding_token' ),
595
			10,
596
			3
597
		);
598
599
		/**
600
		 * Prepare Gutenberg Editor functionality
601
		 */
602
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
603
		Jetpack_Gutenberg::init();
604
		Jetpack_Gutenberg::load_independent_blocks();
605
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
606
607
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
608
609
		// Unlink user before deleting the user from WP.com.
610
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
611
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
612
613
		// Initialize remote file upload request handlers.
614
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
615
		$is_jetpack_xmlrpc_request = isset( $_GET['for'] ) && 'jetpack' === $_GET['for'] && Constants::get_constant( 'XMLRPC_REQUEST' );
616 View Code Duplication
		if (
617
			! $is_jetpack_xmlrpc_request
618
			&& is_admin()
619
			&& isset( $_POST['action'] ) // phpcs:ignore WordPress.Security.NonceVerification
620
			&& (
621
				'jetpack_upload_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
622
				|| 'jetpack_update_file' === $_POST['action']  // phpcs:ignore WordPress.Security.NonceVerification
623
			)
624
		) {
625
			$this->add_remote_request_handlers();
626
		}
627
628
		if ( Jetpack::is_active() ) {
629
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
630
631
			Jetpack_Heartbeat::init();
632
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
633
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
634
				Jetpack_Search_Performance_Logger::init();
635
			}
636
		}
637
638
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
639
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
640
641
		add_action( 'admin_init', array( $this, 'admin_init' ) );
642
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
643
644
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
645
646
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
647
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
648
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
649
650
		// returns HTTPS support status
651
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
652
653
		// JITM AJAX callback function
654
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
655
656
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
657
658
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
659
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
660
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
661
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
662
663
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
664
665
		/**
666
		 * These actions run checks to load additional files.
667
		 * They check for external files or plugins, so they need to run as late as possible.
668
		 */
669
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
670
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
671
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
672
673
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
674
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
675
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
676
677
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
678
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
679
680
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
681
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
682
683
		// A filter to control all just in time messages
684
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
685
686
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
687
688
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
689
		// We should make sure to only do this for front end links.
690
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
691
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
692
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
693
694
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
695
			//so they point moderation links on emails to Calypso
696
			jetpack_require_lib( 'functions.wp-notify' );
697
		}
698
699
		// Hide edit post link if mobile app.
700
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
701
			add_filter( 'edit_post_link', '__return_empty_string' );
702
		}
703
704
		// Update the Jetpack plan from API on heartbeats
705
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
706
707
		/**
708
		 * This is the hack to concatenate all css files into one.
709
		 * For description and reasoning see the implode_frontend_css method
710
		 *
711
		 * Super late priority so we catch all the registered styles
712
		 */
713
		if( !is_admin() ) {
714
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
715
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
716
		}
717
718
719
		/**
720
		 * These are sync actions that we need to keep track of for jitms
721
		 */
722
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
723
724
		// Actually push the stats on shutdown.
725
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
726
			add_action( 'shutdown', array( $this, 'push_stats' ) );
727
		}
728
729
		/*
730
		 * Load some scripts asynchronously.
731
		 */
732
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
733
	}
734
735
	/**
736
	 * Sets up the XMLRPC request handlers.
737
	 *
738
	 * @deprecated since 7.7.0
739
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
740
	 *
741
	 * @param Array                 $request_params Incoming request parameters.
742
	 * @param Boolean               $is_active      Whether the connection is currently active.
743
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
744
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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

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

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

Loading history...
745
	 */
746
	public function setup_xmlrpc_handlers(
747
		$request_params,
748
		$is_active,
749
		$is_signed,
750
		Jetpack_XMLRPC_Server $xmlrpc_server = null
751
	) {
752
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
753
		return $this->connection_manager->setup_xmlrpc_handlers(
754
			$request_params,
755
			$is_active,
756
			$is_signed,
757
			$xmlrpc_server
758
		);
759
	}
760
761
	/**
762
	 * Initialize REST API registration connector.
763
	 *
764
	 * @deprecated since 7.7.0
765
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
766
	 */
767
	public function initialize_rest_api_registration_connector() {
768
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
769
		$this->connection_manager->initialize_rest_api_registration_connector();
770
	}
771
772
	/**
773
	 * This is ported over from the manage module, which has been deprecated and baked in here.
774
	 *
775
	 * @param $domains
776
	 */
777
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
778
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
779
	}
780
781
	/**
782
	 * Return $domains, with 'wordpress.com' appended.
783
	 * This is ported over from the manage module, which has been deprecated and baked in here.
784
	 *
785
	 * @param $domains
786
	 * @return array
787
	 */
788
	function allow_wpcom_domain( $domains ) {
789
		if ( empty( $domains ) ) {
790
			$domains = array();
791
		}
792
		$domains[] = 'wordpress.com';
793
		return array_unique( $domains );
794
	}
795
796
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
797
		$post = get_post( $post_id );
798
799
		if ( empty( $post ) ) {
800
			return $default_url;
801
		}
802
803
		$post_type = $post->post_type;
804
805
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
806
		// https://en.support.wordpress.com/custom-post-types/
807
		$allowed_post_types = array(
808
			'post' => 'post',
809
			'page' => 'page',
810
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
811
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
812
		);
813
814
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
815
			return $default_url;
816
		}
817
818
		$path_prefix = $allowed_post_types[ $post_type ];
819
820
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
821
822
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
823
	}
824
825
	function point_edit_comment_links_to_calypso( $url ) {
826
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
827
		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...
828
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
829
			Jetpack::build_raw_urls( get_home_url() ),
830
			$query_args['amp;c']
831
		) );
832
	}
833
834
	function jetpack_track_last_sync_callback( $params ) {
835
		/**
836
		 * Filter to turn off jitm caching
837
		 *
838
		 * @since 5.4.0
839
		 *
840
		 * @param bool false Whether to cache just in time messages
841
		 */
842
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
843
			return $params;
844
		}
845
846
		if ( is_array( $params ) && isset( $params[0] ) ) {
847
			$option = $params[0];
848
			if ( 'active_plugins' === $option ) {
849
				// use the cache if we can, but not terribly important if it gets evicted
850
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
851
			}
852
		}
853
854
		return $params;
855
	}
856
857
	function jetpack_connection_banner_callback() {
858
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
859
860
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
861
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
862
			wp_send_json_success();
863
		}
864
865
		wp_die();
866
	}
867
868
	/**
869
	 * Removes all XML-RPC methods that are not `jetpack.*`.
870
	 * Only used in our alternate XML-RPC endpoint, where we want to
871
	 * ensure that Core and other plugins' methods are not exposed.
872
	 *
873
	 * @deprecated since 7.7.0
874
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
875
	 *
876
	 * @param array $methods A list of registered WordPress XMLRPC methods.
877
	 * @return array Filtered $methods
878
	 */
879
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
880
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
881
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
882
	}
883
884
	/**
885
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
886
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
887
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
888
	 * which is accessible via a different URI. Most of the below is copied directly
889
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
890
	 *
891
	 * @deprecated since 7.7.0
892
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
893
	 */
894
	public function alternate_xmlrpc() {
895
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
896
		$this->connection_manager->alternate_xmlrpc();
897
	}
898
899
	/**
900
	 * The callback for the JITM ajax requests.
901
	 */
902
	function jetpack_jitm_ajax_callback() {
903
		// Check for nonce
904
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
905
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
906
		}
907
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
908
			$module_slug = $_REQUEST['jitmModule'];
909
			Jetpack::log( 'activate', $module_slug );
910
			Jetpack::activate_module( $module_slug, false, false );
911
			Jetpack::state( 'message', 'no_message' );
912
913
			//A Jetpack module is being activated through a JITM, track it
914
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
915
			$this->do_stats( 'server_side' );
916
917
			wp_send_json_success();
918
		}
919
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
920
			// get the hide_jitm options array
921
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
922
			$module_slug = $_REQUEST['jitmModule'];
923
924
			if( ! $jetpack_hide_jitm ) {
925
				$jetpack_hide_jitm = array(
926
					$module_slug => 'hide'
927
				);
928
			} else {
929
				$jetpack_hide_jitm[$module_slug] = 'hide';
930
			}
931
932
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
933
934
			//jitm is being dismissed forever, track it
935
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
936
			$this->do_stats( 'server_side' );
937
938
			wp_send_json_success();
939
		}
940 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
941
			$module_slug = $_REQUEST['jitmModule'];
942
943
			// User went to WordPress.com, track this
944
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
945
			$this->do_stats( 'server_side' );
946
947
			wp_send_json_success();
948
		}
949 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
950
			$track = $_REQUEST['jitmModule'];
951
952
			// User is viewing JITM, track it.
953
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
954
			$this->do_stats( 'server_side' );
955
956
			wp_send_json_success();
957
		}
958
	}
959
960
	/**
961
	 * If there are any stats that need to be pushed, but haven't been, push them now.
962
	 */
963
	function push_stats() {
964
		if ( ! empty( $this->stats ) ) {
965
			$this->do_stats( 'server_side' );
966
		}
967
	}
968
969
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
970
		switch( $cap ) {
971
			case 'jetpack_connect' :
972
			case 'jetpack_reconnect' :
973
				if ( Jetpack::is_development_mode() ) {
974
					$caps = array( 'do_not_allow' );
975
					break;
976
				}
977
				/**
978
				 * Pass through. If it's not development mode, these should match disconnect.
979
				 * Let users disconnect if it's development mode, just in case things glitch.
980
				 */
981
			case 'jetpack_disconnect' :
982
				/**
983
				 * In multisite, can individual site admins manage their own connection?
984
				 *
985
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
986
				 */
987
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
988
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
989
						/**
990
						 * We need to update the option name -- it's terribly unclear which
991
						 * direction the override goes.
992
						 *
993
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
994
						 */
995
						$caps = array( 'do_not_allow' );
996
						break;
997
					}
998
				}
999
1000
				$caps = array( 'manage_options' );
1001
				break;
1002
			case 'jetpack_manage_modules' :
1003
			case 'jetpack_activate_modules' :
1004
			case 'jetpack_deactivate_modules' :
1005
				$caps = array( 'manage_options' );
1006
				break;
1007
			case 'jetpack_configure_modules' :
1008
				$caps = array( 'manage_options' );
1009
				break;
1010
			case 'jetpack_manage_autoupdates' :
1011
				$caps = array(
1012
					'manage_options',
1013
					'update_plugins',
1014
				);
1015
				break;
1016
			case 'jetpack_network_admin_page':
1017
			case 'jetpack_network_settings_page':
1018
				$caps = array( 'manage_network_plugins' );
1019
				break;
1020
			case 'jetpack_network_sites_page':
1021
				$caps = array( 'manage_sites' );
1022
				break;
1023
			case 'jetpack_admin_page' :
1024
				if ( Jetpack::is_development_mode() ) {
1025
					$caps = array( 'manage_options' );
1026
					break;
1027
				} else {
1028
					$caps = array( 'read' );
1029
				}
1030
				break;
1031
			case 'jetpack_connect_user' :
1032
				if ( Jetpack::is_development_mode() ) {
1033
					$caps = array( 'do_not_allow' );
1034
					break;
1035
				}
1036
				$caps = array( 'read' );
1037
				break;
1038
		}
1039
		return $caps;
1040
	}
1041
1042
	/**
1043
	 * Require a Jetpack authentication.
1044
	 *
1045
	 * @deprecated since 7.7.0
1046
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1047
	 */
1048
	public function require_jetpack_authentication() {
1049
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1050
		$this->connection_manager->require_jetpack_authentication();
1051
	}
1052
1053
	/**
1054
	 * Load language files
1055
	 * @action plugins_loaded
1056
	 */
1057
	public static function plugin_textdomain() {
1058
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1059
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1060
	}
1061
1062
	/**
1063
	 * Register assets for use in various modules and the Jetpack admin page.
1064
	 *
1065
	 * @uses wp_script_is, wp_register_script, plugins_url
1066
	 * @action wp_loaded
1067
	 * @return null
1068
	 */
1069
	public function register_assets() {
1070
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1071
			wp_register_script(
1072
				'spin',
1073
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1074
				false,
1075
				'1.3'
1076
			);
1077
		}
1078
1079 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1080
			wp_register_script(
1081
				'jquery.spin',
1082
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1083
				array( 'jquery', 'spin' ),
1084
				'1.3'
1085
			);
1086
		}
1087
1088 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1089
			wp_register_script(
1090
				'jetpack-gallery-settings',
1091
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1092
				array( 'media-views' ),
1093
				'20121225'
1094
			);
1095
		}
1096
1097 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1098
			wp_register_script(
1099
				'jetpack-twitter-timeline',
1100
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1101
				array( 'jquery' ),
1102
				'4.0.0',
1103
				true
1104
			);
1105
		}
1106
1107
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1108
			wp_register_script(
1109
				'jetpack-facebook-embed',
1110
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1111
				array( 'jquery' ),
1112
				null,
1113
				true
1114
			);
1115
1116
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1117
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1118
			if ( ! is_numeric( $fb_app_id ) ) {
1119
				$fb_app_id = '';
1120
			}
1121
			wp_localize_script(
1122
				'jetpack-facebook-embed',
1123
				'jpfbembed',
1124
				array(
1125
					'appid' => $fb_app_id,
1126
					'locale' => $this->get_locale(),
1127
				)
1128
			);
1129
		}
1130
1131
		/**
1132
		 * As jetpack_register_genericons is by default fired off a hook,
1133
		 * the hook may have already fired by this point.
1134
		 * So, let's just trigger it manually.
1135
		 */
1136
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1137
		jetpack_register_genericons();
1138
1139
		/**
1140
		 * Register the social logos
1141
		 */
1142
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1143
		jetpack_register_social_logos();
1144
1145 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1146
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1147
	}
1148
1149
	/**
1150
	 * Guess locale from language code.
1151
	 *
1152
	 * @param string $lang Language code.
1153
	 * @return string|bool
1154
	 */
1155 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1156
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1157
			return 'en_US';
1158
		}
1159
1160
		if ( ! class_exists( 'GP_Locales' ) ) {
1161
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1162
				return false;
1163
			}
1164
1165
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1166
		}
1167
1168
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1169
			// WP.com: get_locale() returns 'it'
1170
			$locale = GP_Locales::by_slug( $lang );
1171
		} else {
1172
			// Jetpack: get_locale() returns 'it_IT';
1173
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1174
		}
1175
1176
		if ( ! $locale ) {
1177
			return false;
1178
		}
1179
1180
		if ( empty( $locale->facebook_locale ) ) {
1181
			if ( empty( $locale->wp_locale ) ) {
1182
				return false;
1183
			} else {
1184
				// Facebook SDK is smart enough to fall back to en_US if a
1185
				// locale isn't supported. Since supported Facebook locales
1186
				// can fall out of sync, we'll attempt to use the known
1187
				// wp_locale value and rely on said fallback.
1188
				return $locale->wp_locale;
1189
			}
1190
		}
1191
1192
		return $locale->facebook_locale;
1193
	}
1194
1195
	/**
1196
	 * Get the locale.
1197
	 *
1198
	 * @return string|bool
1199
	 */
1200
	function get_locale() {
1201
		$locale = $this->guess_locale_from_lang( get_locale() );
1202
1203
		if ( ! $locale ) {
1204
			$locale = 'en_US';
1205
		}
1206
1207
		return $locale;
1208
	}
1209
1210
	/**
1211
	 * Device Pixels support
1212
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1213
	 */
1214
	function devicepx() {
1215
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1216
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1217
		}
1218
	}
1219
1220
	/**
1221
	 * Return the network_site_url so that .com knows what network this site is a part of.
1222
	 * @param  bool $option
1223
	 * @return string
1224
	 */
1225
	public function jetpack_main_network_site_option( $option ) {
1226
		return network_site_url();
1227
	}
1228
	/**
1229
	 * Network Name.
1230
	 */
1231
	static function network_name( $option = null ) {
1232
		global $current_site;
1233
		return $current_site->site_name;
1234
	}
1235
	/**
1236
	 * Does the network allow new user and site registrations.
1237
	 * @return string
1238
	 */
1239
	static function network_allow_new_registrations( $option = null ) {
1240
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1241
	}
1242
	/**
1243
	 * Does the network allow admins to add new users.
1244
	 * @return boolian
1245
	 */
1246
	static function network_add_new_users( $option = null ) {
1247
		return (bool) get_site_option( 'add_new_users' );
1248
	}
1249
	/**
1250
	 * File upload psace left per site in MB.
1251
	 *  -1 means NO LIMIT.
1252
	 * @return number
1253
	 */
1254
	static function network_site_upload_space( $option = null ) {
1255
		// value in MB
1256
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1257
	}
1258
1259
	/**
1260
	 * Network allowed file types.
1261
	 * @return string
1262
	 */
1263
	static function network_upload_file_types( $option = null ) {
1264
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1265
	}
1266
1267
	/**
1268
	 * Maximum file upload size set by the network.
1269
	 * @return number
1270
	 */
1271
	static function network_max_upload_file_size( $option = null ) {
1272
		// value in KB
1273
		return get_site_option( 'fileupload_maxk', 300 );
1274
	}
1275
1276
	/**
1277
	 * Lets us know if a site allows admins to manage the network.
1278
	 * @return array
1279
	 */
1280
	static function network_enable_administration_menus( $option = null ) {
1281
		return get_site_option( 'menu_items' );
1282
	}
1283
1284
	/**
1285
	 * If a user has been promoted to or demoted from admin, we need to clear the
1286
	 * jetpack_other_linked_admins transient.
1287
	 *
1288
	 * @since 4.3.2
1289
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1290
	 *
1291
	 * @param int    $user_id   The user ID whose role changed.
1292
	 * @param string $role      The new role.
1293
	 * @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...
1294
	 */
1295
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1296
		if ( 'administrator' == $role
1297
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1298
			|| is_null( $old_roles )
1299
		) {
1300
			delete_transient( 'jetpack_other_linked_admins' );
1301
		}
1302
	}
1303
1304
	/**
1305
	 * Checks to see if there are any other users available to become primary
1306
	 * Users must both:
1307
	 * - Be linked to wpcom
1308
	 * - Be an admin
1309
	 *
1310
	 * @return mixed False if no other users are linked, Int if there are.
1311
	 */
1312
	static function get_other_linked_admins() {
1313
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1314
1315
		if ( false === $other_linked_users ) {
1316
			$admins = get_users( array( 'role' => 'administrator' ) );
1317
			if ( count( $admins ) > 1 ) {
1318
				$available = array();
1319
				foreach ( $admins as $admin ) {
1320
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1321
						$available[] = $admin->ID;
1322
					}
1323
				}
1324
1325
				$count_connected_admins = count( $available );
1326
				if ( count( $available ) > 1 ) {
1327
					$other_linked_users = $count_connected_admins;
1328
				} else {
1329
					$other_linked_users = 0;
1330
				}
1331
			} else {
1332
				$other_linked_users = 0;
1333
			}
1334
1335
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1336
		}
1337
1338
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1339
	}
1340
1341
	/**
1342
	 * Return whether we are dealing with a multi network setup or not.
1343
	 * The reason we are type casting this is because we want to avoid the situation where
1344
	 * the result is false since when is_main_network_option return false it cases
1345
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1346
	 * database which could be set to anything as opposed to what this function returns.
1347
	 * @param  bool  $option
1348
	 *
1349
	 * @return boolean
1350
	 */
1351
	public function is_main_network_option( $option ) {
1352
		// return '1' or ''
1353
		return (string) (bool) Jetpack::is_multi_network();
1354
	}
1355
1356
	/**
1357
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1358
	 *
1359
	 * @param  string  $option
1360
	 * @return boolean
1361
	 */
1362
	public function is_multisite( $option ) {
1363
		return (string) (bool) is_multisite();
1364
	}
1365
1366
	/**
1367
	 * Implemented since there is no core is multi network function
1368
	 * Right now there is no way to tell if we which network is the dominant network on the system
1369
	 *
1370
	 * @since  3.3
1371
	 * @return boolean
1372
	 */
1373 View Code Duplication
	public static function is_multi_network() {
1374
		global  $wpdb;
1375
1376
		// if we don't have a multi site setup no need to do any more
1377
		if ( ! is_multisite() ) {
1378
			return false;
1379
		}
1380
1381
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1382
		if ( $num_sites > 1 ) {
1383
			return true;
1384
		} else {
1385
			return false;
1386
		}
1387
	}
1388
1389
	/**
1390
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1391
	 * @return null
1392
	 */
1393
	function update_jetpack_main_network_site_option() {
1394
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1395
	}
1396
	/**
1397
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1398
	 *
1399
	 */
1400
	function update_jetpack_network_settings() {
1401
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1402
		// Only sync this info for the main network site.
1403
	}
1404
1405
	/**
1406
	 * Get back if the current site is single user site.
1407
	 *
1408
	 * @return bool
1409
	 */
1410 View Code Duplication
	public static function is_single_user_site() {
1411
		global $wpdb;
1412
1413
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1414
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1415
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1416
		}
1417
		return 1 === (int) $some_users;
1418
	}
1419
1420
	/**
1421
	 * Returns true if the site has file write access false otherwise.
1422
	 * @return string ( '1' | '0' )
1423
	 **/
1424
	public static function file_system_write_access() {
1425
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1426
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1427
		}
1428
1429
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1430
1431
		$filesystem_method = get_filesystem_method();
1432
		if ( $filesystem_method === 'direct' ) {
1433
			return 1;
1434
		}
1435
1436
		ob_start();
1437
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1438
		ob_end_clean();
1439
		if ( $filesystem_credentials_are_stored ) {
1440
			return 1;
1441
		}
1442
		return 0;
1443
	}
1444
1445
	/**
1446
	 * Finds out if a site is using a version control system.
1447
	 * @return string ( '1' | '0' )
1448
	 **/
1449
	public static function is_version_controlled() {
1450
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1451
		return (string) (int) Functions::is_version_controlled();
1452
	}
1453
1454
	/**
1455
	 * Determines whether the current theme supports featured images or not.
1456
	 * @return string ( '1' | '0' )
1457
	 */
1458
	public static function featured_images_enabled() {
1459
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1460
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1461
	}
1462
1463
	/**
1464
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1465
	 *
1466
	 * @deprecated 4.7 use get_avatar_url instead.
1467
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1468
	 * @param int $size Size of the avatar image
1469
	 * @param string $default URL to a default image to use if no avatar is available
1470
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1471
	 *
1472
	 * @return array
1473
	 */
1474
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1475
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1476
		return get_avatar_url( $id_or_email, array(
1477
			'size' => $size,
1478
			'default' => $default,
1479
			'force_default' => $force_display,
1480
		) );
1481
	}
1482
1483
	/**
1484
	 * jetpack_updates is saved in the following schema:
1485
	 *
1486
	 * array (
1487
	 *      'plugins'                       => (int) Number of plugin updates available.
1488
	 *      'themes'                        => (int) Number of theme updates available.
1489
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1490
	 *      'translations'                  => (int) Number of translation updates available.
1491
	 *      'total'                         => (int) Total of all available updates.
1492
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1493
	 * )
1494
	 * @return array
1495
	 */
1496
	public static function get_updates() {
1497
		$update_data = wp_get_update_data();
1498
1499
		// Stores the individual update counts as well as the total count.
1500
		if ( isset( $update_data['counts'] ) ) {
1501
			$updates = $update_data['counts'];
1502
		}
1503
1504
		// If we need to update WordPress core, let's find the latest version number.
1505 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1506
			$cur = get_preferred_from_update_core();
1507
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1508
				$updates['wp_update_version'] = $cur->current;
1509
			}
1510
		}
1511
		return isset( $updates ) ? $updates : array();
1512
	}
1513
1514
	public static function get_update_details() {
1515
		$update_details = array(
1516
			'update_core' => get_site_transient( 'update_core' ),
1517
			'update_plugins' => get_site_transient( 'update_plugins' ),
1518
			'update_themes' => get_site_transient( 'update_themes' ),
1519
		);
1520
		return $update_details;
1521
	}
1522
1523
	public static function refresh_update_data() {
1524
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1525
1526
	}
1527
1528
	public static function refresh_theme_data() {
1529
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1530
	}
1531
1532
	/**
1533
	 * Is Jetpack active?
1534
	 */
1535
	public static function is_active() {
1536
		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...
1537
	}
1538
1539
	/**
1540
	 * Make an API call to WordPress.com for plan status
1541
	 *
1542
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1543
	 *
1544
	 * @return bool True if plan is updated, false if no update
1545
	 */
1546
	public static function refresh_active_plan_from_wpcom() {
1547
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1548
		return Jetpack_Plan::refresh_from_wpcom();
1549
	}
1550
1551
	/**
1552
	 * Get the plan that this Jetpack site is currently using
1553
	 *
1554
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1555
	 * @return array Active Jetpack plan details.
1556
	 */
1557
	public static function get_active_plan() {
1558
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1559
		return Jetpack_Plan::get();
1560
	}
1561
1562
	/**
1563
	 * Determine whether the active plan supports a particular feature
1564
	 *
1565
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1566
	 * @return bool True if plan supports feature, false if not.
1567
	 */
1568
	public static function active_plan_supports( $feature ) {
1569
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1570
		return Jetpack_Plan::supports( $feature );
1571
	}
1572
1573
	/**
1574
	 * Is Jetpack in development (offline) mode?
1575
	 */
1576 View Code Duplication
	public static function is_development_mode() {
1577
		$development_mode = false;
1578
1579
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1580
			$development_mode = JETPACK_DEV_DEBUG;
1581
		} elseif ( $site_url = site_url() ) {
1582
			$development_mode = false === strpos( $site_url, '.' );
1583
		}
1584
1585
		/**
1586
		 * Filters Jetpack's development mode.
1587
		 *
1588
		 * @see https://jetpack.com/support/development-mode/
1589
		 *
1590
		 * @since 2.2.1
1591
		 *
1592
		 * @param bool $development_mode Is Jetpack's development mode active.
1593
		 */
1594
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1595
		return $development_mode;
1596
	}
1597
1598
	/**
1599
	 * Whether the site is currently onboarding or not.
1600
	 * A site is considered as being onboarded if it currently has an onboarding token.
1601
	 *
1602
	 * @since 5.8
1603
	 *
1604
	 * @access public
1605
	 * @static
1606
	 *
1607
	 * @return bool True if the site is currently onboarding, false otherwise
1608
	 */
1609
	public static function is_onboarding() {
1610
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1611
	}
1612
1613
	/**
1614
	 * Determines reason for Jetpack development mode.
1615
	 */
1616
	public static function development_mode_trigger_text() {
1617
		if ( ! Jetpack::is_development_mode() ) {
1618
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1619
		}
1620
1621
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1622
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1623
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1624
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1625
		} else {
1626
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1627
		}
1628
1629
		return $notice;
1630
1631
	}
1632
	/**
1633
	* Get Jetpack development mode notice text and notice class.
1634
	*
1635
	* Mirrors the checks made in Jetpack::is_development_mode
1636
	*
1637
	*/
1638
	public static function show_development_mode_notice() {
1639 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1640
			$notice = sprintf(
1641
			/* translators: %s is a URL */
1642
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1643
				'https://jetpack.com/support/development-mode/'
1644
			);
1645
1646
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1647
1648
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1649
		}
1650
1651
		// Throw up a notice if using a development version and as for feedback.
1652
		if ( Jetpack::is_development_version() ) {
1653
			/* translators: %s is a URL */
1654
			$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/' );
1655
1656
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1657
		}
1658
		// Throw up a notice if using staging mode
1659
		if ( Jetpack::is_staging_site() ) {
1660
			/* translators: %s is a URL */
1661
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1662
1663
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1664
		}
1665
	}
1666
1667
	/**
1668
	 * Whether Jetpack's version maps to a public release, or a development version.
1669
	 */
1670
	public static function is_development_version() {
1671
		/**
1672
		 * Allows filtering whether this is a development version of Jetpack.
1673
		 *
1674
		 * This filter is especially useful for tests.
1675
		 *
1676
		 * @since 4.3.0
1677
		 *
1678
		 * @param bool $development_version Is this a develoment version of Jetpack?
1679
		 */
1680
		return (bool) apply_filters(
1681
			'jetpack_development_version',
1682
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1683
		);
1684
	}
1685
1686
	/**
1687
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1688
	 */
1689
	public static function is_user_connected( $user_id = false ) {
1690
		return self::connection()->is_user_connected( $user_id );
1691
	}
1692
1693
	/**
1694
	 * Get the wpcom user data of the current|specified connected user.
1695
	 */
1696 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1697
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1698
		if ( ! $user_id ) {
1699
			$user_id = get_current_user_id();
1700
		}
1701
1702
		$transient_key = "jetpack_connected_user_data_$user_id";
1703
1704
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1705
			return $cached_user_data;
1706
		}
1707
1708
		Jetpack::load_xml_rpc_client();
1709
		$xml = new Jetpack_IXR_Client( array(
1710
			'user_id' => $user_id,
1711
		) );
1712
		$xml->query( 'wpcom.getUser' );
1713
		if ( ! $xml->isError() ) {
1714
			$user_data = $xml->getResponse();
1715
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1716
			return $user_data;
1717
		}
1718
1719
		return false;
1720
	}
1721
1722
	/**
1723
	 * Get the wpcom email of the current|specified connected user.
1724
	 */
1725 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1726
		if ( ! $user_id ) {
1727
			$user_id = get_current_user_id();
1728
		}
1729
		Jetpack::load_xml_rpc_client();
1730
		$xml = new Jetpack_IXR_Client( array(
1731
			'user_id' => $user_id,
1732
		) );
1733
		$xml->query( 'wpcom.getUserEmail' );
1734
		if ( ! $xml->isError() ) {
1735
			return $xml->getResponse();
1736
		}
1737
		return false;
1738
	}
1739
1740
	/**
1741
	 * Get the wpcom email of the master user.
1742
	 */
1743
	public static function get_master_user_email() {
1744
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1745
		if ( $master_user_id ) {
1746
			return self::get_connected_user_email( $master_user_id );
1747
		}
1748
		return '';
1749
	}
1750
1751
	/**
1752
	 * Whether the current user is the connection owner.
1753
	 *
1754
	 * @deprecated since 7.7
1755
	 *
1756
	 * @return bool Whether the current user is the connection owner.
1757
	 */
1758
	public function current_user_is_connection_owner() {
1759
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1760
		return self::connection()->is_connection_owner();
1761
	}
1762
1763
	/**
1764
	 * Gets current user IP address.
1765
	 *
1766
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1767
	 *
1768
	 * @return string                  Current user IP address.
1769
	 */
1770
	public static function current_user_ip( $check_all_headers = false ) {
1771
		if ( $check_all_headers ) {
1772
			foreach ( array(
1773
				'HTTP_CF_CONNECTING_IP',
1774
				'HTTP_CLIENT_IP',
1775
				'HTTP_X_FORWARDED_FOR',
1776
				'HTTP_X_FORWARDED',
1777
				'HTTP_X_CLUSTER_CLIENT_IP',
1778
				'HTTP_FORWARDED_FOR',
1779
				'HTTP_FORWARDED',
1780
				'HTTP_VIA',
1781
			) as $key ) {
1782
				if ( ! empty( $_SERVER[ $key ] ) ) {
1783
					return $_SERVER[ $key ];
1784
				}
1785
			}
1786
		}
1787
1788
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1789
	}
1790
1791
	/**
1792
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1793
	 */
1794
	function extra_oembed_providers() {
1795
		// Cloudup: https://dev.cloudup.com/#oembed
1796
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1797
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1798
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1799
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1800
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1801
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1802
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1803
	}
1804
1805
	/**
1806
	 * Synchronize connected user role changes
1807
	 */
1808
	function user_role_change( $user_id ) {
1809
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1810
		Users::user_role_change( $user_id );
1811
	}
1812
1813
	/**
1814
	 * Loads the currently active modules.
1815
	 */
1816
	public static function load_modules() {
1817
		if (
1818
			! self::is_active()
1819
			&& ! self::is_development_mode()
1820
			&& ! self::is_onboarding()
1821
			&& (
1822
				! is_multisite()
1823
				|| ! get_site_option( 'jetpack_protect_active' )
1824
			)
1825
		) {
1826
			return;
1827
		}
1828
1829
		$version = Jetpack_Options::get_option( 'version' );
1830 View Code Duplication
		if ( ! $version ) {
1831
			$version = $old_version = JETPACK__VERSION . ':' . time();
1832
			/** This action is documented in class.jetpack.php */
1833
			do_action( 'updating_jetpack_version', $version, false );
1834
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1835
		}
1836
		list( $version ) = explode( ':', $version );
1837
1838
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1839
1840
		$modules_data = array();
1841
1842
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1843
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1844
			$updated_modules = array();
1845
			foreach ( $modules as $module ) {
1846
				$modules_data[ $module ] = Jetpack::get_module( $module );
1847
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1848
					continue;
1849
				}
1850
1851
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1852
					continue;
1853
				}
1854
1855
				$updated_modules[] = $module;
1856
			}
1857
1858
			$modules = array_diff( $modules, $updated_modules );
1859
		}
1860
1861
		$is_development_mode = Jetpack::is_development_mode();
1862
1863
		foreach ( $modules as $index => $module ) {
1864
			// If we're in dev mode, disable modules requiring a connection
1865
			if ( $is_development_mode ) {
1866
				// Prime the pump if we need to
1867
				if ( empty( $modules_data[ $module ] ) ) {
1868
					$modules_data[ $module ] = Jetpack::get_module( $module );
1869
				}
1870
				// If the module requires a connection, but we're in local mode, don't include it.
1871
				if ( $modules_data[ $module ]['requires_connection'] ) {
1872
					continue;
1873
				}
1874
			}
1875
1876
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1877
				continue;
1878
			}
1879
1880
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1881
				unset( $modules[ $index ] );
1882
				self::update_active_modules( array_values( $modules ) );
1883
				continue;
1884
			}
1885
1886
			/**
1887
			 * Fires when a specific module is loaded.
1888
			 * The dynamic part of the hook, $module, is the module slug.
1889
			 *
1890
			 * @since 1.1.0
1891
			 */
1892
			do_action( 'jetpack_module_loaded_' . $module );
1893
		}
1894
1895
		/**
1896
		 * Fires when all the modules are loaded.
1897
		 *
1898
		 * @since 1.1.0
1899
		 */
1900
		do_action( 'jetpack_modules_loaded' );
1901
1902
		// 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.
1903
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1904
	}
1905
1906
	/**
1907
	 * Check if Jetpack's REST API compat file should be included
1908
	 * @action plugins_loaded
1909
	 * @return null
1910
	 */
1911
	public function check_rest_api_compat() {
1912
		/**
1913
		 * Filters the list of REST API compat files to be included.
1914
		 *
1915
		 * @since 2.2.5
1916
		 *
1917
		 * @param array $args Array of REST API compat files to include.
1918
		 */
1919
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1920
1921
		if ( function_exists( 'bbpress' ) )
1922
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1923
1924
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1925
			require_once $_jetpack_rest_api_compat_include;
1926
	}
1927
1928
	/**
1929
	 * Gets all plugins currently active in values, regardless of whether they're
1930
	 * traditionally activated or network activated.
1931
	 *
1932
	 * @todo Store the result in core's object cache maybe?
1933
	 */
1934
	public static function get_active_plugins() {
1935
		$active_plugins = (array) get_option( 'active_plugins', array() );
1936
1937
		if ( is_multisite() ) {
1938
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1939
			// whereas active_plugins stores them in the values.
1940
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1941
			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...
1942
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1943
			}
1944
		}
1945
1946
		sort( $active_plugins );
1947
1948
		return array_unique( $active_plugins );
1949
	}
1950
1951
	/**
1952
	 * Gets and parses additional plugin data to send with the heartbeat data
1953
	 *
1954
	 * @since 3.8.1
1955
	 *
1956
	 * @return array Array of plugin data
1957
	 */
1958
	public static function get_parsed_plugin_data() {
1959
		if ( ! function_exists( 'get_plugins' ) ) {
1960
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1961
		}
1962
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1963
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1964
		$active_plugins = Jetpack::get_active_plugins();
1965
1966
		$plugins = array();
1967
		foreach ( $all_plugins as $path => $plugin_data ) {
1968
			$plugins[ $path ] = array(
1969
					'is_active' => in_array( $path, $active_plugins ),
1970
					'file'      => $path,
1971
					'name'      => $plugin_data['Name'],
1972
					'version'   => $plugin_data['Version'],
1973
					'author'    => $plugin_data['Author'],
1974
			);
1975
		}
1976
1977
		return $plugins;
1978
	}
1979
1980
	/**
1981
	 * Gets and parses theme data to send with the heartbeat data
1982
	 *
1983
	 * @since 3.8.1
1984
	 *
1985
	 * @return array Array of theme data
1986
	 */
1987
	public static function get_parsed_theme_data() {
1988
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1989
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1990
1991
		$themes = array();
1992
		foreach ( $all_themes as $slug => $theme_data ) {
1993
			$theme_headers = array();
1994
			foreach ( $header_keys as $header_key ) {
1995
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1996
			}
1997
1998
			$themes[ $slug ] = array(
1999
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2000
					'slug' => $slug,
2001
					'theme_root' => $theme_data->get_theme_root_uri(),
2002
					'parent' => $theme_data->parent(),
2003
					'headers' => $theme_headers
2004
			);
2005
		}
2006
2007
		return $themes;
2008
	}
2009
2010
	/**
2011
	 * Checks whether a specific plugin is active.
2012
	 *
2013
	 * We don't want to store these in a static variable, in case
2014
	 * there are switch_to_blog() calls involved.
2015
	 */
2016
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2017
		return in_array( $plugin, self::get_active_plugins() );
2018
	}
2019
2020
	/**
2021
	 * Check if Jetpack's Open Graph tags should be used.
2022
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2023
	 *
2024
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2025
	 * @action plugins_loaded
2026
	 * @return null
2027
	 */
2028
	public function check_open_graph() {
2029
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2030
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2031
		}
2032
2033
		$active_plugins = self::get_active_plugins();
2034
2035
		if ( ! empty( $active_plugins ) ) {
2036
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2037
				if ( in_array( $plugin, $active_plugins ) ) {
2038
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2039
					break;
2040
				}
2041
			}
2042
		}
2043
2044
		/**
2045
		 * Allow the addition of Open Graph Meta Tags to all pages.
2046
		 *
2047
		 * @since 2.0.3
2048
		 *
2049
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2050
		 */
2051
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2052
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2053
		}
2054
	}
2055
2056
	/**
2057
	 * Check if Jetpack's Twitter tags should be used.
2058
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2059
	 *
2060
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2061
	 * @action plugins_loaded
2062
	 * @return null
2063
	 */
2064
	public function check_twitter_tags() {
2065
2066
		$active_plugins = self::get_active_plugins();
2067
2068
		if ( ! empty( $active_plugins ) ) {
2069
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2070
				if ( in_array( $plugin, $active_plugins ) ) {
2071
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2072
					break;
2073
				}
2074
			}
2075
		}
2076
2077
		/**
2078
		 * Allow Twitter Card Meta tags to be disabled.
2079
		 *
2080
		 * @since 2.6.0
2081
		 *
2082
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2083
		 */
2084
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2085
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2086
		}
2087
	}
2088
2089
	/**
2090
	 * Allows plugins to submit security reports.
2091
 	 *
2092
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2093
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2094
	 * @param array   $args         See definitions above
2095
	 */
2096
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2097
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2098
	}
2099
2100
/* Jetpack Options API */
2101
2102
	public static function get_option_names( $type = 'compact' ) {
2103
		return Jetpack_Options::get_option_names( $type );
2104
	}
2105
2106
	/**
2107
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2108
 	 *
2109
	 * @param string $name    Option name
2110
	 * @param mixed  $default (optional)
2111
	 */
2112
	public static function get_option( $name, $default = false ) {
2113
		return Jetpack_Options::get_option( $name, $default );
2114
	}
2115
2116
	/**
2117
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2118
 	 *
2119
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2120
	 * @param string $name  Option name
2121
	 * @param mixed  $value Option value
2122
	 */
2123
	public static function update_option( $name, $value ) {
2124
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2125
		return Jetpack_Options::update_option( $name, $value );
2126
	}
2127
2128
	/**
2129
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2130
 	 *
2131
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2132
	 * @param array $array array( option name => option value, ... )
2133
	 */
2134
	public static function update_options( $array ) {
2135
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2136
		return Jetpack_Options::update_options( $array );
2137
	}
2138
2139
	/**
2140
	 * Deletes the given option.  May be passed multiple option names as an array.
2141
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2142
	 *
2143
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2144
	 * @param string|array $names
2145
	 */
2146
	public static function delete_option( $names ) {
2147
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2148
		return Jetpack_Options::delete_option( $names );
2149
	}
2150
2151
	/**
2152
	 * Enters a user token into the user_tokens option
2153
	 *
2154
	 * @param int $user_id
2155
	 * @param string $token
2156
	 * return bool
2157
	 */
2158
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2159
		// not designed for concurrent updates
2160
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2161
		if ( ! is_array( $user_tokens ) )
2162
			$user_tokens = array();
2163
		$user_tokens[$user_id] = $token;
2164
		if ( $is_master_user ) {
2165
			$master_user = $user_id;
2166
			$options     = compact( 'user_tokens', 'master_user' );
2167
		} else {
2168
			$options = compact( 'user_tokens' );
2169
		}
2170
		return Jetpack_Options::update_options( $options );
2171
	}
2172
2173
	/**
2174
	 * Returns an array of all PHP files in the specified absolute path.
2175
	 * Equivalent to glob( "$absolute_path/*.php" ).
2176
	 *
2177
	 * @param string $absolute_path The absolute path of the directory to search.
2178
	 * @return array Array of absolute paths to the PHP files.
2179
	 */
2180
	public static function glob_php( $absolute_path ) {
2181
		if ( function_exists( 'glob' ) ) {
2182
			return glob( "$absolute_path/*.php" );
2183
		}
2184
2185
		$absolute_path = untrailingslashit( $absolute_path );
2186
		$files = array();
2187
		if ( ! $dir = @opendir( $absolute_path ) ) {
2188
			return $files;
2189
		}
2190
2191
		while ( false !== $file = readdir( $dir ) ) {
2192
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2193
				continue;
2194
			}
2195
2196
			$file = "$absolute_path/$file";
2197
2198
			if ( ! is_file( $file ) ) {
2199
				continue;
2200
			}
2201
2202
			$files[] = $file;
2203
		}
2204
2205
		closedir( $dir );
2206
2207
		return $files;
2208
	}
2209
2210
	public static function activate_new_modules( $redirect = false ) {
2211
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2212
			return;
2213
		}
2214
2215
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2216 View Code Duplication
		if ( ! $jetpack_old_version ) {
2217
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2218
			/** This action is documented in class.jetpack.php */
2219
			do_action( 'updating_jetpack_version', $version, false );
2220
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2221
		}
2222
2223
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2224
2225
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2226
			return;
2227
		}
2228
2229
		$active_modules     = Jetpack::get_active_modules();
2230
		$reactivate_modules = array();
2231
		foreach ( $active_modules as $active_module ) {
2232
			$module = Jetpack::get_module( $active_module );
2233
			if ( ! isset( $module['changed'] ) ) {
2234
				continue;
2235
			}
2236
2237
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2238
				continue;
2239
			}
2240
2241
			$reactivate_modules[] = $active_module;
2242
			Jetpack::deactivate_module( $active_module );
2243
		}
2244
2245
		$new_version = JETPACK__VERSION . ':' . time();
2246
		/** This action is documented in class.jetpack.php */
2247
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2248
		Jetpack_Options::update_options(
2249
			array(
2250
				'version'     => $new_version,
2251
				'old_version' => $jetpack_old_version,
2252
			)
2253
		);
2254
2255
		Jetpack::state( 'message', 'modules_activated' );
2256
		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...
2257
2258
		if ( $redirect ) {
2259
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2260
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2261
				$page = $_GET['page'];
2262
			}
2263
2264
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2265
			exit;
2266
		}
2267
	}
2268
2269
	/**
2270
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2271
	 * Make sure to tuck away module "library" files in a sub-directory.
2272
	 */
2273
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2274
		static $modules = null;
2275
2276
		if ( ! isset( $modules ) ) {
2277
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2278
			// Use the cache if we're on the front-end and it's available...
2279
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2280
				$modules = $available_modules_option[ JETPACK__VERSION ];
2281
			} else {
2282
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2283
2284
				$modules = array();
2285
2286
				foreach ( $files as $file ) {
2287
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2288
						continue;
2289
					}
2290
2291
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2292
				}
2293
2294
				Jetpack_Options::update_option( 'available_modules', array(
2295
					JETPACK__VERSION => $modules,
2296
				) );
2297
			}
2298
		}
2299
2300
		/**
2301
		 * Filters the array of modules available to be activated.
2302
		 *
2303
		 * @since 2.4.0
2304
		 *
2305
		 * @param array $modules Array of available modules.
2306
		 * @param string $min_version Minimum version number required to use modules.
2307
		 * @param string $max_version Maximum version number required to use modules.
2308
		 */
2309
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2310
2311
		if ( ! $min_version && ! $max_version ) {
2312
			return array_keys( $mods );
2313
		}
2314
2315
		$r = array();
2316
		foreach ( $mods as $slug => $introduced ) {
2317
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2318
				continue;
2319
			}
2320
2321
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2322
				continue;
2323
			}
2324
2325
			$r[] = $slug;
2326
		}
2327
2328
		return $r;
2329
	}
2330
2331
	/**
2332
	 * Default modules loaded on activation.
2333
	 */
2334
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2335
		$return = array();
2336
2337
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2338
			$module_data = Jetpack::get_module( $module );
2339
2340
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2341
				case 'yes' :
2342
					$return[] = $module;
2343
					break;
2344
				case 'public' :
2345
					if ( Jetpack_Options::get_option( 'public' ) ) {
2346
						$return[] = $module;
2347
					}
2348
					break;
2349
				case 'no' :
2350
				default :
2351
					break;
2352
			}
2353
		}
2354
		/**
2355
		 * Filters the array of default modules.
2356
		 *
2357
		 * @since 2.5.0
2358
		 *
2359
		 * @param array $return Array of default modules.
2360
		 * @param string $min_version Minimum version number required to use modules.
2361
		 * @param string $max_version Maximum version number required to use modules.
2362
		 */
2363
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2364
	}
2365
2366
	/**
2367
	 * Checks activated modules during auto-activation to determine
2368
	 * if any of those modules are being deprecated.  If so, close
2369
	 * them out, and add any replacement modules.
2370
	 *
2371
	 * Runs at priority 99 by default.
2372
	 *
2373
	 * This is run late, so that it can still activate a module if
2374
	 * the new module is a replacement for another that the user
2375
	 * currently has active, even if something at the normal priority
2376
	 * would kibosh everything.
2377
	 *
2378
	 * @since 2.6
2379
	 * @uses jetpack_get_default_modules filter
2380
	 * @param array $modules
2381
	 * @return array
2382
	 */
2383
	function handle_deprecated_modules( $modules ) {
2384
		$deprecated_modules = array(
2385
			'debug'            => null,  // Closed out and moved to the debugger library.
2386
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2387
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2388
		);
2389
2390
		// Don't activate SSO if they never completed activating WPCC.
2391
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2392
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2393
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2394
				$deprecated_modules['wpcc'] = null;
2395
			}
2396
		}
2397
2398
		foreach ( $deprecated_modules as $module => $replacement ) {
2399
			if ( Jetpack::is_module_active( $module ) ) {
2400
				self::deactivate_module( $module );
2401
				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...
2402
					$modules[] = $replacement;
2403
				}
2404
			}
2405
		}
2406
2407
		return array_unique( $modules );
2408
	}
2409
2410
	/**
2411
	 * Checks activated plugins during auto-activation to determine
2412
	 * if any of those plugins are in the list with a corresponding module
2413
	 * that is not compatible with the plugin. The module will not be allowed
2414
	 * to auto-activate.
2415
	 *
2416
	 * @since 2.6
2417
	 * @uses jetpack_get_default_modules filter
2418
	 * @param array $modules
2419
	 * @return array
2420
	 */
2421
	function filter_default_modules( $modules ) {
2422
2423
		$active_plugins = self::get_active_plugins();
2424
2425
		if ( ! empty( $active_plugins ) ) {
2426
2427
			// For each module we'd like to auto-activate...
2428
			foreach ( $modules as $key => $module ) {
2429
				// If there are potential conflicts for it...
2430
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2431
					// For each potential conflict...
2432
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2433
						// If that conflicting plugin is active...
2434
						if ( in_array( $plugin, $active_plugins ) ) {
2435
							// Remove that item from being auto-activated.
2436
							unset( $modules[ $key ] );
2437
						}
2438
					}
2439
				}
2440
			}
2441
		}
2442
2443
		return $modules;
2444
	}
2445
2446
	/**
2447
	 * Extract a module's slug from its full path.
2448
	 */
2449
	public static function get_module_slug( $file ) {
2450
		return str_replace( '.php', '', basename( $file ) );
2451
	}
2452
2453
	/**
2454
	 * Generate a module's path from its slug.
2455
	 */
2456
	public static function get_module_path( $slug ) {
2457
		/**
2458
		 * Filters the path of a modules.
2459
		 *
2460
		 * @since 7.4.0
2461
		 *
2462
		 * @param array $return The absolute path to a module's root php file
2463
		 * @param string $slug The module slug
2464
		 */
2465
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2466
	}
2467
2468
	/**
2469
	 * Load module data from module file. Headers differ from WordPress
2470
	 * plugin headers to avoid them being identified as standalone
2471
	 * plugins on the WordPress plugins page.
2472
	 */
2473
	public static function get_module( $module ) {
2474
		$headers = array(
2475
			'name'                      => 'Module Name',
2476
			'description'               => 'Module Description',
2477
			'sort'                      => 'Sort Order',
2478
			'recommendation_order'      => 'Recommendation Order',
2479
			'introduced'                => 'First Introduced',
2480
			'changed'                   => 'Major Changes In',
2481
			'deactivate'                => 'Deactivate',
2482
			'free'                      => 'Free',
2483
			'requires_connection'       => 'Requires Connection',
2484
			'auto_activate'             => 'Auto Activate',
2485
			'module_tags'               => 'Module Tags',
2486
			'feature'                   => 'Feature',
2487
			'additional_search_queries' => 'Additional Search Queries',
2488
			'plan_classes'              => 'Plans',
2489
		);
2490
2491
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2492
2493
		$mod = Jetpack::get_file_data( $file, $headers );
2494
		if ( empty( $mod['name'] ) ) {
2495
			return false;
2496
		}
2497
2498
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2499
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2500
		$mod['deactivate']              = empty( $mod['deactivate'] );
2501
		$mod['free']                    = empty( $mod['free'] );
2502
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2503
2504
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2505
			$mod['auto_activate'] = 'No';
2506
		} else {
2507
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2508
		}
2509
2510
		if ( $mod['module_tags'] ) {
2511
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2512
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2513
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2514
		} else {
2515
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2516
		}
2517
2518 View Code Duplication
		if ( $mod['plan_classes'] ) {
2519
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2520
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2521
		} else {
2522
			$mod['plan_classes'] = array( 'free' );
2523
		}
2524
2525 View Code Duplication
		if ( $mod['feature'] ) {
2526
			$mod['feature'] = explode( ',', $mod['feature'] );
2527
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2528
		} else {
2529
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2530
		}
2531
2532
		/**
2533
		 * Filters the feature array on a module.
2534
		 *
2535
		 * This filter allows you to control where each module is filtered: Recommended,
2536
		 * and the default "Other" listing.
2537
		 *
2538
		 * @since 3.5.0
2539
		 *
2540
		 * @param array   $mod['feature'] The areas to feature this module:
2541
		 *     'Recommended' shows on the main Jetpack admin screen.
2542
		 *     'Other' should be the default if no other value is in the array.
2543
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2544
		 * @param array   $mod All the currently assembled module data.
2545
		 */
2546
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2547
2548
		/**
2549
		 * Filter the returned data about a module.
2550
		 *
2551
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2552
		 * so please be careful.
2553
		 *
2554
		 * @since 3.6.0
2555
		 *
2556
		 * @param array   $mod    The details of the requested module.
2557
		 * @param string  $module The slug of the module, e.g. sharedaddy
2558
		 * @param string  $file   The path to the module source file.
2559
		 */
2560
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2561
	}
2562
2563
	/**
2564
	 * Like core's get_file_data implementation, but caches the result.
2565
	 */
2566
	public static function get_file_data( $file, $headers ) {
2567
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2568
		$file_name = basename( $file );
2569
2570
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2571
2572
		$file_data_option = get_transient( $cache_key );
2573
2574
		if ( false === $file_data_option ) {
2575
			$file_data_option = array();
2576
		}
2577
2578
		$key           = md5( $file_name . serialize( $headers ) );
2579
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2580
2581
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2582
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2583
			return $file_data_option[ $key ];
2584
		}
2585
2586
		$data = get_file_data( $file, $headers );
2587
2588
		$file_data_option[ $key ] = $data;
2589
2590
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2591
2592
		return $data;
2593
	}
2594
2595
2596
	/**
2597
	 * Return translated module tag.
2598
	 *
2599
	 * @param string $tag Tag as it appears in each module heading.
2600
	 *
2601
	 * @return mixed
2602
	 */
2603
	public static function translate_module_tag( $tag ) {
2604
		return jetpack_get_module_i18n_tag( $tag );
2605
	}
2606
2607
	/**
2608
	 * Get i18n strings as a JSON-encoded string
2609
	 *
2610
	 * @return string The locale as JSON
2611
	 */
2612
	public static function get_i18n_data_json() {
2613
2614
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2615
		// JSON files with the file they should be included for. This is an md5
2616
		// of '_inc/build/admin.js'.
2617
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2618
2619
		$i18n_json =
2620
				   JETPACK__PLUGIN_DIR
2621
				   . 'languages/json/jetpack-'
2622
				   . get_user_locale()
2623
				   . '-'
2624
				   . $path_md5
2625
				   . '.json';
2626
2627
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2628
			$locale_data = @file_get_contents( $i18n_json );
2629
			if ( $locale_data ) {
2630
				return $locale_data;
2631
			}
2632
		}
2633
2634
		// Return valid empty Jed locale
2635
		return '{ "locale_data": { "messages": { "": {} } } }';
2636
	}
2637
2638
	/**
2639
	 * Add locale data setup to wp-i18n
2640
	 *
2641
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2642
	 *
2643
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2644
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2645
	 *
2646
	 * This method provides a safe way to request the setup multiple times but add the script at
2647
	 * most once.
2648
	 *
2649
	 * @since 6.7.0
2650
	 *
2651
	 * @return void
2652
	 */
2653
	public static function setup_wp_i18n_locale_data() {
2654
		static $script_added = false;
2655
		if ( ! $script_added ) {
2656
			$script_added = true;
2657
			wp_add_inline_script(
2658
				'wp-i18n',
2659
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2660
			);
2661
		}
2662
	}
2663
2664
	/**
2665
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2666
	 *
2667
	 * @since 3.9.2
2668
	 *
2669
	 * @param array $modules
2670
	 *
2671
	 * @return string|void
2672
	 */
2673
	public static function get_translated_modules( $modules ) {
2674
		foreach ( $modules as $index => $module ) {
2675
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2676
			if ( isset( $module['name'] ) ) {
2677
				$modules[ $index ]['name'] = $i18n_module['name'];
2678
			}
2679
			if ( isset( $module['description'] ) ) {
2680
				$modules[ $index ]['description'] = $i18n_module['description'];
2681
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2682
			}
2683
		}
2684
		return $modules;
2685
	}
2686
2687
	/**
2688
	 * Get a list of activated modules as an array of module slugs.
2689
	 */
2690
	public static function get_active_modules() {
2691
		$active = Jetpack_Options::get_option( 'active_modules' );
2692
2693
		if ( ! is_array( $active ) ) {
2694
			$active = array();
2695
		}
2696
2697
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2698
			$active[] = 'vaultpress';
2699
		} else {
2700
			$active = array_diff( $active, array( 'vaultpress' ) );
2701
		}
2702
2703
		//If protect is active on the main site of a multisite, it should be active on all sites.
2704
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2705
			$active[] = 'protect';
2706
		}
2707
2708
		/**
2709
		 * Allow filtering of the active modules.
2710
		 *
2711
		 * Gives theme and plugin developers the power to alter the modules that
2712
		 * are activated on the fly.
2713
		 *
2714
		 * @since 5.8.0
2715
		 *
2716
		 * @param array $active Array of active module slugs.
2717
		 */
2718
		$active = apply_filters( 'jetpack_active_modules', $active );
2719
2720
		return array_unique( $active );
2721
	}
2722
2723
	/**
2724
	 * Check whether or not a Jetpack module is active.
2725
	 *
2726
	 * @param string $module The slug of a Jetpack module.
2727
	 * @return bool
2728
	 *
2729
	 * @static
2730
	 */
2731
	public static function is_module_active( $module ) {
2732
		return in_array( $module, self::get_active_modules() );
2733
	}
2734
2735
	public static function is_module( $module ) {
2736
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2737
	}
2738
2739
	/**
2740
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2741
	 *
2742
	 * @param bool $catch True to start catching, False to stop.
2743
	 *
2744
	 * @static
2745
	 */
2746
	public static function catch_errors( $catch ) {
2747
		static $display_errors, $error_reporting;
2748
2749
		if ( $catch ) {
2750
			$display_errors  = @ini_set( 'display_errors', 1 );
2751
			$error_reporting = @error_reporting( E_ALL );
2752
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2753
		} else {
2754
			@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...
2755
			@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...
2756
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2757
		}
2758
	}
2759
2760
	/**
2761
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2762
	 */
2763
	public static function catch_errors_on_shutdown() {
2764
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2765
	}
2766
2767
	/**
2768
	 * Rewrite any string to make paths easier to read.
2769
	 *
2770
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2771
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2772
	 *
2773
	 * @param $string
2774
	 * @return mixed
2775
	 */
2776
	public static function alias_directories( $string ) {
2777
		// ABSPATH has a trailing slash.
2778
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2779
		// WP_CONTENT_DIR does not have a trailing slash.
2780
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2781
2782
		return $string;
2783
	}
2784
2785
	public static function activate_default_modules(
2786
		$min_version = false,
2787
		$max_version = false,
2788
		$other_modules = array(),
2789
		$redirect = true,
2790
		$send_state_messages = true
2791
	) {
2792
		$jetpack = Jetpack::init();
2793
2794
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2795
		$modules = array_merge( $other_modules, $modules );
2796
2797
		// Look for standalone plugins and disable if active.
2798
2799
		$to_deactivate = array();
2800
		foreach ( $modules as $module ) {
2801
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2802
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2803
			}
2804
		}
2805
2806
		$deactivated = array();
2807
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2808
			list( $probable_file, $probable_title ) = $deactivate_me;
2809
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2810
				$deactivated[] = $module;
2811
			}
2812
		}
2813
2814
		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...
2815
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2816
2817
			$url = add_query_arg(
2818
				array(
2819
					'action'   => 'activate_default_modules',
2820
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2821
				),
2822
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2823
			);
2824
			wp_safe_redirect( $url );
2825
			exit;
2826
		}
2827
2828
		/**
2829
		 * Fires before default modules are activated.
2830
		 *
2831
		 * @since 1.9.0
2832
		 *
2833
		 * @param string $min_version Minimum version number required to use modules.
2834
		 * @param string $max_version Maximum version number required to use modules.
2835
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2836
		 */
2837
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2838
2839
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2840
		if ( $send_state_messages ) {
2841
			Jetpack::restate();
2842
			Jetpack::catch_errors( true );
2843
		}
2844
2845
		$active = Jetpack::get_active_modules();
2846
2847
		foreach ( $modules as $module ) {
2848
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2849
				$active[] = $module;
2850
				self::update_active_modules( $active );
2851
				continue;
2852
			}
2853
2854
			if ( $send_state_messages && in_array( $module, $active ) ) {
2855
				$module_info = Jetpack::get_module( $module );
2856 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2857
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2858
					if ( $active_state = Jetpack::state( $state ) ) {
2859
						$active_state = explode( ',', $active_state );
2860
					} else {
2861
						$active_state = array();
2862
					}
2863
					$active_state[] = $module;
2864
					Jetpack::state( $state, implode( ',', $active_state ) );
2865
				}
2866
				continue;
2867
			}
2868
2869
			$file = Jetpack::get_module_path( $module );
2870
			if ( ! file_exists( $file ) ) {
2871
				continue;
2872
			}
2873
2874
			// we'll override this later if the plugin can be included without fatal error
2875
			if ( $redirect ) {
2876
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2877
			}
2878
2879
			if ( $send_state_messages ) {
2880
				Jetpack::state( 'error', 'module_activation_failed' );
2881
				Jetpack::state( 'module', $module );
2882
			}
2883
2884
			ob_start();
2885
			require_once $file;
2886
2887
			$active[] = $module;
2888
2889 View Code Duplication
			if ( $send_state_messages ) {
2890
2891
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2892
				if ( $active_state = Jetpack::state( $state ) ) {
2893
					$active_state = explode( ',', $active_state );
2894
				} else {
2895
					$active_state = array();
2896
				}
2897
				$active_state[] = $module;
2898
				Jetpack::state( $state, implode( ',', $active_state ) );
2899
			}
2900
2901
			Jetpack::update_active_modules( $active );
2902
2903
			ob_end_clean();
2904
		}
2905
2906
		if ( $send_state_messages ) {
2907
			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...
2908
			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...
2909
		}
2910
2911
		Jetpack::catch_errors( false );
2912
		/**
2913
		 * Fires when default modules are activated.
2914
		 *
2915
		 * @since 1.9.0
2916
		 *
2917
		 * @param string $min_version Minimum version number required to use modules.
2918
		 * @param string $max_version Maximum version number required to use modules.
2919
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2920
		 */
2921
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2922
	}
2923
2924
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2925
		/**
2926
		 * Fires before a module is activated.
2927
		 *
2928
		 * @since 2.6.0
2929
		 *
2930
		 * @param string $module Module slug.
2931
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2932
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2933
		 */
2934
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2935
2936
		$jetpack = Jetpack::init();
2937
2938
		if ( ! strlen( $module ) )
2939
			return false;
2940
2941
		if ( ! Jetpack::is_module( $module ) )
2942
			return false;
2943
2944
		// If it's already active, then don't do it again
2945
		$active = Jetpack::get_active_modules();
2946
		foreach ( $active as $act ) {
2947
			if ( $act == $module )
2948
				return true;
2949
		}
2950
2951
		$module_data = Jetpack::get_module( $module );
2952
2953
		if ( ! Jetpack::is_active() ) {
2954
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2955
				return false;
2956
2957
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2958
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2959
				return false;
2960
		}
2961
2962
		// Check and see if the old plugin is active
2963
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2964
			// Deactivate the old plugin
2965
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2966
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2967
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2968
				Jetpack::state( 'deactivated_plugins', $module );
2969
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2970
				exit;
2971
			}
2972
		}
2973
2974
		// Protect won't work with mis-configured IPs
2975
		if ( 'protect' === $module ) {
2976
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2977
			if ( ! jetpack_protect_get_ip() ) {
2978
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2979
				return false;
2980
			}
2981
		}
2982
2983
		if ( ! Jetpack_Plan::supports( $module ) ) {
2984
			return false;
2985
		}
2986
2987
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2988
		Jetpack::state( 'module', $module );
2989
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2990
2991
		Jetpack::catch_errors( true );
2992
		ob_start();
2993
		require Jetpack::get_module_path( $module );
2994
		/** This action is documented in class.jetpack.php */
2995
		do_action( 'jetpack_activate_module', $module );
2996
		$active[] = $module;
2997
		Jetpack::update_active_modules( $active );
2998
2999
		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...
3000
		ob_end_clean();
3001
		Jetpack::catch_errors( false );
3002
3003
		if ( $redirect ) {
3004
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3005
		}
3006
		if ( $exit ) {
3007
			exit;
3008
		}
3009
		return true;
3010
	}
3011
3012
	function activate_module_actions( $module ) {
3013
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3014
	}
3015
3016
	public static function deactivate_module( $module ) {
3017
		/**
3018
		 * Fires when a module is deactivated.
3019
		 *
3020
		 * @since 1.9.0
3021
		 *
3022
		 * @param string $module Module slug.
3023
		 */
3024
		do_action( 'jetpack_pre_deactivate_module', $module );
3025
3026
		$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...
3027
3028
		$active = Jetpack::get_active_modules();
3029
		$new    = array_filter( array_diff( $active, (array) $module ) );
3030
3031
		return self::update_active_modules( $new );
3032
	}
3033
3034
	public static function enable_module_configurable( $module ) {
3035
		$module = Jetpack::get_module_slug( $module );
3036
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3037
	}
3038
3039
	/**
3040
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3041
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3042
	 *
3043
	 * @param string $module Module slug
3044
	 * @return string $url module configuration URL
3045
	 */
3046
	public static function module_configuration_url( $module ) {
3047
		$module = Jetpack::get_module_slug( $module );
3048
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3049
		/**
3050
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3051
		 *
3052
		 * @since 6.9.0
3053
		 *
3054
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3055
		 */
3056
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3057
3058
		return $url;
3059
	}
3060
3061
/* Installation */
3062
	public static function bail_on_activation( $message, $deactivate = true ) {
3063
?>
3064
<!doctype html>
3065
<html>
3066
<head>
3067
<meta charset="<?php bloginfo( 'charset' ); ?>">
3068
<style>
3069
* {
3070
	text-align: center;
3071
	margin: 0;
3072
	padding: 0;
3073
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3074
}
3075
p {
3076
	margin-top: 1em;
3077
	font-size: 18px;
3078
}
3079
</style>
3080
<body>
3081
<p><?php echo esc_html( $message ); ?></p>
3082
</body>
3083
</html>
3084
<?php
3085
		if ( $deactivate ) {
3086
			$plugins = get_option( 'active_plugins' );
3087
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3088
			$update  = false;
3089
			foreach ( $plugins as $i => $plugin ) {
3090
				if ( $plugin === $jetpack ) {
3091
					$plugins[$i] = false;
3092
					$update = true;
3093
				}
3094
			}
3095
3096
			if ( $update ) {
3097
				update_option( 'active_plugins', array_filter( $plugins ) );
3098
			}
3099
		}
3100
		exit;
3101
	}
3102
3103
	/**
3104
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3105
	 * @static
3106
	 */
3107
	public static function plugin_activation( $network_wide ) {
3108
		Jetpack_Options::update_option( 'activated', 1 );
3109
3110
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3111
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3112
		}
3113
3114
		if ( $network_wide )
3115
			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...
3116
3117
		// For firing one-off events (notices) immediately after activation
3118
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3119
3120
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3121
3122
		Jetpack::plugin_initialize();
3123
	}
3124
3125
	public static function get_activation_source( $referer_url ) {
3126
3127
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3128
			return array( 'wp-cli', null );
3129
		}
3130
3131
		$referer = parse_url( $referer_url );
3132
3133
		$source_type = 'unknown';
3134
		$source_query = null;
3135
3136
		if ( ! is_array( $referer ) ) {
3137
			return array( $source_type, $source_query );
3138
		}
3139
3140
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3141
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3142
3143
		if ( isset( $referer['query'] ) ) {
3144
			parse_str( $referer['query'], $query_parts );
3145
		} else {
3146
			$query_parts = array();
3147
		}
3148
3149
		if ( $plugins_path === $referer['path'] ) {
3150
			$source_type = 'list';
3151
		} elseif ( $plugins_install_path === $referer['path'] ) {
3152
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3153
			switch( $tab ) {
3154
				case 'popular':
3155
					$source_type = 'popular';
3156
					break;
3157
				case 'recommended':
3158
					$source_type = 'recommended';
3159
					break;
3160
				case 'favorites':
3161
					$source_type = 'favorites';
3162
					break;
3163
				case 'search':
3164
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3165
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3166
					break;
3167
				default:
3168
					$source_type = 'featured';
3169
			}
3170
		}
3171
3172
		return array( $source_type, $source_query );
3173
	}
3174
3175
	/**
3176
	 * Runs before bumping version numbers up to a new version
3177
	 * @param  string $version    Version:timestamp
3178
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3179
	 * @return null              [description]
3180
	 */
3181
	public static function do_version_bump( $version, $old_version ) {
3182
		if ( ! $old_version ) { // For new sites
3183
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3184
		}
3185
	}
3186
3187
	/**
3188
	 * Sets the internal version number and activation state.
3189
	 * @static
3190
	 */
3191
	public static function plugin_initialize() {
3192
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3193
			Jetpack_Options::update_option( 'activated', 2 );
3194
		}
3195
3196 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3197
			$version = $old_version = JETPACK__VERSION . ':' . time();
3198
			/** This action is documented in class.jetpack.php */
3199
			do_action( 'updating_jetpack_version', $version, false );
3200
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3201
		}
3202
3203
		Jetpack::load_modules();
3204
3205
		Jetpack_Options::delete_option( 'do_activate' );
3206
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3207
	}
3208
3209
	/**
3210
	 * Removes all connection options
3211
	 * @static
3212
	 */
3213
	public static function plugin_deactivation( ) {
3214
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3215
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3216
			Jetpack_Network::init()->deactivate();
3217
		} else {
3218
			Jetpack::disconnect( false );
3219
			//Jetpack_Heartbeat::init()->deactivate();
3220
		}
3221
	}
3222
3223
	/**
3224
	 * Disconnects from the Jetpack servers.
3225
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3226
	 * @static
3227
	 */
3228
	public static function disconnect( $update_activated_state = true ) {
3229
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3230
		$connection = self::connection();
3231
		$connection->clean_nonces( true );
3232
3233
		// If the site is in an IDC because sync is not allowed,
3234
		// let's make sure to not disconnect the production site.
3235
		if ( ! self::validate_sync_error_idc_option() ) {
3236
			$tracking = new Tracking();
3237
			$tracking->record_user_event( 'disconnect_site', array() );
3238
			Jetpack::load_xml_rpc_client();
3239
			$xml = new Jetpack_IXR_Client();
3240
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3241
		}
3242
3243
		Jetpack_Options::delete_option(
3244
			array(
3245
				'blog_token',
3246
				'user_token',
3247
				'user_tokens',
3248
				'master_user',
3249
				'time_diff',
3250
				'fallback_no_verify_ssl_certs',
3251
			)
3252
		);
3253
3254
		Jetpack_IDC::clear_all_idc_options();
3255
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3256
3257
		if ( $update_activated_state ) {
3258
			Jetpack_Options::update_option( 'activated', 4 );
3259
		}
3260
3261
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3262
			// Check then record unique disconnection if site has never been disconnected previously
3263
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3264
				$jetpack_unique_connection['disconnected'] = 1;
3265
			} else {
3266
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3267
					//track unique disconnect
3268
					$jetpack = Jetpack::init();
3269
3270
					$jetpack->stat( 'connections', 'unique-disconnect' );
3271
					$jetpack->do_stats( 'server_side' );
3272
				}
3273
				// increment number of times disconnected
3274
				$jetpack_unique_connection['disconnected'] += 1;
3275
			}
3276
3277
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3278
		}
3279
3280
		// Delete cached connected user data
3281
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3282
		delete_transient( $transient_key );
3283
3284
		// Delete all the sync related data. Since it could be taking up space.
3285
		Sender::get_instance()->uninstall();
3286
3287
		// Disable the Heartbeat cron
3288
		Jetpack_Heartbeat::init()->deactivate();
3289
	}
3290
3291
	/**
3292
	 * Unlinks the current user from the linked WordPress.com user.
3293
	 *
3294
	 * @deprecated since 7.7
3295
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3296
	 *
3297
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be integer|null?

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

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

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

Loading history...
3298
	 * @return Boolean Whether the disconnection of the user was successful.
3299
	 */
3300
	public static function unlink_user( $user_id = null ) {
3301
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3302
		return Connection_Manager::disconnect_user( $user_id );
3303
	}
3304
3305
	/**
3306
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3307
	 */
3308
	public static function try_registration() {
3309
		// The user has agreed to the TOS at some point by now.
3310
		Jetpack_Options::update_option( 'tos_agreed', true );
3311
3312
		// Let's get some testing in beta versions and such.
3313
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3314
			// Before attempting to connect, let's make sure that the domains are viable.
3315
			$domains_to_check = array_unique( array(
3316
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3317
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3318
			) );
3319
			foreach ( $domains_to_check as $domain ) {
3320
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Security Bug introduced by
It seems like $domain defined by $domain on line 3319 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...
3321
				if ( is_wp_error( $result ) ) {
3322
					return $result;
3323
				}
3324
			}
3325
		}
3326
3327
		$result = Jetpack::register();
3328
3329
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3330
		if ( ! $result || is_wp_error( $result ) ) {
3331
			return $result;
3332
		} else {
3333
			return true;
3334
		}
3335
	}
3336
3337
	/**
3338
	 * Tracking an internal event log. Try not to put too much chaff in here.
3339
	 *
3340
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3341
	 */
3342
	public static function log( $code, $data = null ) {
3343
		// only grab the latest 200 entries
3344
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3345
3346
		// Append our event to the log
3347
		$log_entry = array(
3348
			'time'    => time(),
3349
			'user_id' => get_current_user_id(),
3350
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3351
			'code'    => $code,
3352
		);
3353
		// Don't bother storing it unless we've got some.
3354
		if ( ! is_null( $data ) ) {
3355
			$log_entry['data'] = $data;
3356
		}
3357
		$log[] = $log_entry;
3358
3359
		// Try add_option first, to make sure it's not autoloaded.
3360
		// @todo: Add an add_option method to Jetpack_Options
3361
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3362
			Jetpack_Options::update_option( 'log', $log );
3363
		}
3364
3365
		/**
3366
		 * Fires when Jetpack logs an internal event.
3367
		 *
3368
		 * @since 3.0.0
3369
		 *
3370
		 * @param array $log_entry {
3371
		 *	Array of details about the log entry.
3372
		 *
3373
		 *	@param string time Time of the event.
3374
		 *	@param int user_id ID of the user who trigerred the event.
3375
		 *	@param int blog_id Jetpack Blog ID.
3376
		 *	@param string code Unique name for the event.
3377
		 *	@param string data Data about the event.
3378
		 * }
3379
		 */
3380
		do_action( 'jetpack_log_entry', $log_entry );
3381
	}
3382
3383
	/**
3384
	 * Get the internal event log.
3385
	 *
3386
	 * @param $event (string) - only return the specific log events
3387
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3388
	 *
3389
	 * @return array of log events || WP_Error for invalid params
3390
	 */
3391
	public static function get_log( $event = false, $num = false ) {
3392
		if ( $event && ! is_string( $event ) ) {
3393
			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...
3394
		}
3395
3396
		if ( $num && ! is_numeric( $num ) ) {
3397
			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...
3398
		}
3399
3400
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3401
3402
		// If nothing set - act as it did before, otherwise let's start customizing the output
3403
		if ( ! $num && ! $event ) {
3404
			return $entire_log;
3405
		} else {
3406
			$entire_log = array_reverse( $entire_log );
3407
		}
3408
3409
		$custom_log_output = array();
3410
3411
		if ( $event ) {
3412
			foreach ( $entire_log as $log_event ) {
3413
				if ( $event == $log_event[ 'code' ] ) {
3414
					$custom_log_output[] = $log_event;
3415
				}
3416
			}
3417
		} else {
3418
			$custom_log_output = $entire_log;
3419
		}
3420
3421
		if ( $num ) {
3422
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3423
		}
3424
3425
		return $custom_log_output;
3426
	}
3427
3428
	/**
3429
	 * Log modification of important settings.
3430
	 */
3431
	public static function log_settings_change( $option, $old_value, $value ) {
3432
		switch( $option ) {
3433
			case 'jetpack_sync_non_public_post_stati':
3434
				self::log( $option, $value );
3435
				break;
3436
		}
3437
	}
3438
3439
	/**
3440
	 * Return stat data for WPCOM sync
3441
	 */
3442
	public static function get_stat_data( $encode = true, $extended = true ) {
3443
		$data = Jetpack_Heartbeat::generate_stats_array();
3444
3445
		if ( $extended ) {
3446
			$additional_data = self::get_additional_stat_data();
3447
			$data = array_merge( $data, $additional_data );
3448
		}
3449
3450
		if ( $encode ) {
3451
			return json_encode( $data );
3452
		}
3453
3454
		return $data;
3455
	}
3456
3457
	/**
3458
	 * Get additional stat data to sync to WPCOM
3459
	 */
3460
	public static function get_additional_stat_data( $prefix = '' ) {
3461
		$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...
3462
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3463
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3464
		$return["{$prefix}site-count"]     = 0;
3465
3466
		if ( function_exists( 'get_blog_count' ) ) {
3467
			$return["{$prefix}site-count"] = get_blog_count();
3468
		}
3469
		return $return;
3470
	}
3471
3472
	private static function get_site_user_count() {
3473
		global $wpdb;
3474
3475
		if ( function_exists( 'wp_is_large_network' ) ) {
3476
			if ( wp_is_large_network( 'users' ) ) {
3477
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3478
			}
3479
		}
3480
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3481
			// It wasn't there, so regenerate the data and save the transient
3482
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3483
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3484
		}
3485
		return $user_count;
3486
	}
3487
3488
	/* Admin Pages */
3489
3490
	function admin_init() {
3491
		// If the plugin is not connected, display a connect message.
3492
		if (
3493
			// the plugin was auto-activated and needs its candy
3494
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3495
		||
3496
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3497
			! Jetpack_Options::get_option( 'activated' )
3498
		) {
3499
			Jetpack::plugin_initialize();
3500
		}
3501
3502
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3503
			Jetpack_Connection_Banner::init();
3504
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3505
			// Upgrade: 1.1 -> 1.1.1
3506
			// Check and see if host can verify the Jetpack servers' SSL certificate
3507
			$args = array();
3508
			$connection = self::connection();
3509
			Client::_wp_remote_request(
3510
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3511
				$args,
3512
				true
3513
			);
3514
		}
3515
3516
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3517
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3518
		}
3519
3520
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3521
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3522
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3523
3524
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3525
			// Artificially throw errors in certain whitelisted cases during plugin activation
3526
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3527
		}
3528
3529
		// Add custom column in wp-admin/users.php to show whether user is linked.
3530
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3531
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3532
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3533
	}
3534
3535
	function admin_body_class( $admin_body_class = '' ) {
3536
		$classes = explode( ' ', trim( $admin_body_class ) );
3537
3538
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3539
3540
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3541
		return " $admin_body_class ";
3542
	}
3543
3544
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3545
		return $admin_body_class . ' jetpack-pagestyles ';
3546
	}
3547
3548
	/**
3549
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3550
	 * This function artificially throws errors for such cases (whitelisted).
3551
	 *
3552
	 * @param string $plugin The activated plugin.
3553
	 */
3554
	function throw_error_on_activate_plugin( $plugin ) {
3555
		$active_modules = Jetpack::get_active_modules();
3556
3557
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3558
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3559
			$throw = false;
3560
3561
			// Try and make sure it really was the stats plugin
3562
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3563
				if ( 'stats.php' == basename( $plugin ) ) {
3564
					$throw = true;
3565
				}
3566
			} else {
3567
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3568
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3569
					$throw = true;
3570
				}
3571
			}
3572
3573
			if ( $throw ) {
3574
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3575
			}
3576
		}
3577
	}
3578
3579
	function intercept_plugin_error_scrape_init() {
3580
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3581
	}
3582
3583
	function intercept_plugin_error_scrape( $action, $result ) {
3584
		if ( ! $result ) {
3585
			return;
3586
		}
3587
3588
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3589
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3590
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3591
			}
3592
		}
3593
	}
3594
3595
	function add_remote_request_handlers() {
3596
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3597
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3598
	}
3599
3600
	function remote_request_handlers() {
3601
		$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...
3602
3603
		switch ( current_filter() ) {
3604
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3605
			$response = $this->upload_handler();
3606
			break;
3607
3608
		case 'wp_ajax_nopriv_jetpack_update_file' :
3609
			$response = $this->upload_handler( true );
3610
			break;
3611
		default :
3612
			$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...
3613
			break;
3614
		}
3615
3616
		if ( ! $response ) {
3617
			$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...
3618
		}
3619
3620
		if ( is_wp_error( $response ) ) {
3621
			$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...
3622
			$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...
3623
			$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...
3624
3625
			if ( ! is_int( $status_code ) ) {
3626
				$status_code = 400;
3627
			}
3628
3629
			status_header( $status_code );
3630
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3631
		}
3632
3633
		status_header( 200 );
3634
		if ( true === $response ) {
3635
			exit;
3636
		}
3637
3638
		die( json_encode( (object) $response ) );
3639
	}
3640
3641
	/**
3642
	 * Uploads a file gotten from the global $_FILES.
3643
	 * If `$update_media_item` is true and `post_id` is defined
3644
	 * the attachment file of the media item (gotten through of the post_id)
3645
	 * will be updated instead of add a new one.
3646
	 *
3647
	 * @param  boolean $update_media_item - update media attachment
3648
	 * @return array - An array describing the uploadind files process
3649
	 */
3650
	function upload_handler( $update_media_item = false ) {
3651
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3652
			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...
3653
		}
3654
3655
		$user = wp_authenticate( '', '' );
3656
		if ( ! $user || is_wp_error( $user ) ) {
3657
			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...
3658
		}
3659
3660
		wp_set_current_user( $user->ID );
3661
3662
		if ( ! current_user_can( 'upload_files' ) ) {
3663
			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...
3664
		}
3665
3666
		if ( empty( $_FILES ) ) {
3667
			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...
3668
		}
3669
3670
		foreach ( array_keys( $_FILES ) as $files_key ) {
3671
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3672
				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...
3673
			}
3674
		}
3675
3676
		$media_keys = array_keys( $_FILES['media'] );
3677
3678
		$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...
3679
		if ( ! $token || is_wp_error( $token ) ) {
3680
			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...
3681
		}
3682
3683
		$uploaded_files = array();
3684
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3685
		unset( $GLOBALS['post'] );
3686
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3687
			$file = array();
3688
			foreach ( $media_keys as $media_key ) {
3689
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3690
			}
3691
3692
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3693
3694
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3695
			if ( $hmac_provided !== $hmac_file ) {
3696
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3697
				continue;
3698
			}
3699
3700
			$_FILES['.jetpack.upload.'] = $file;
3701
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3702
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3703
				$post_id = 0;
3704
			}
3705
3706
			if ( $update_media_item ) {
3707
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3708
					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...
3709
				}
3710
3711
				$media_array = $_FILES['media'];
3712
3713
				$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...
3714
				$file_array['type'] = $media_array['type'][0];
3715
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3716
				$file_array['error'] = $media_array['error'][0];
3717
				$file_array['size'] = $media_array['size'][0];
3718
3719
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3720
3721
				if ( is_wp_error( $edited_media_item ) ) {
3722
					return $edited_media_item;
3723
				}
3724
3725
				$response = (object) array(
3726
					'id'   => (string) $post_id,
3727
					'file' => (string) $edited_media_item->post_title,
3728
					'url'  => (string) wp_get_attachment_url( $post_id ),
3729
					'type' => (string) $edited_media_item->post_mime_type,
3730
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3731
				);
3732
3733
				return (array) array( $response );
3734
			}
3735
3736
			$attachment_id = media_handle_upload(
3737
				'.jetpack.upload.',
3738
				$post_id,
3739
				array(),
3740
				array(
3741
					'action' => 'jetpack_upload_file',
3742
				)
3743
			);
3744
3745
			if ( ! $attachment_id ) {
3746
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3747
			} elseif ( is_wp_error( $attachment_id ) ) {
3748
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3749
			} else {
3750
				$attachment = get_post( $attachment_id );
3751
				$uploaded_files[$index] = (object) array(
3752
					'id'   => (string) $attachment_id,
3753
					'file' => $attachment->post_title,
3754
					'url'  => wp_get_attachment_url( $attachment_id ),
3755
					'type' => $attachment->post_mime_type,
3756
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3757
				);
3758
				// Zip files uploads are not supported unless they are done for installation purposed
3759
				// lets delete them in case something goes wrong in this whole process
3760
				if ( 'application/zip' === $attachment->post_mime_type ) {
3761
					// Schedule a cleanup for 2 hours from now in case of failed install.
3762
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3763
				}
3764
			}
3765
		}
3766
		if ( ! is_null( $global_post ) ) {
3767
			$GLOBALS['post'] = $global_post;
3768
		}
3769
3770
		return $uploaded_files;
3771
	}
3772
3773
	/**
3774
	 * Add help to the Jetpack page
3775
	 *
3776
	 * @since Jetpack (1.2.3)
3777
	 * @return false if not the Jetpack page
3778
	 */
3779
	function admin_help() {
3780
		$current_screen = get_current_screen();
3781
3782
		// Overview
3783
		$current_screen->add_help_tab(
3784
			array(
3785
				'id'		=> 'home',
3786
				'title'		=> __( 'Home', 'jetpack' ),
3787
				'content'	=>
3788
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3789
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3790
					'<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>',
3791
			)
3792
		);
3793
3794
		// Screen Content
3795
		if ( current_user_can( 'manage_options' ) ) {
3796
			$current_screen->add_help_tab(
3797
				array(
3798
					'id'		=> 'settings',
3799
					'title'		=> __( 'Settings', 'jetpack' ),
3800
					'content'	=>
3801
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3802
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3803
						'<ol>' .
3804
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3805
							'<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>' .
3806
						'</ol>' .
3807
						'<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>'
3808
				)
3809
			);
3810
		}
3811
3812
		// Help Sidebar
3813
		$current_screen->set_help_sidebar(
3814
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3815
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3816
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3817
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3818
		);
3819
	}
3820
3821
	function admin_menu_css() {
3822
		wp_enqueue_style( 'jetpack-icons' );
3823
	}
3824
3825
	function admin_menu_order() {
3826
		return true;
3827
	}
3828
3829 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3830
		$jp_menu_order = array();
3831
3832
		foreach ( $menu_order as $index => $item ) {
3833
			if ( $item != 'jetpack' ) {
3834
				$jp_menu_order[] = $item;
3835
			}
3836
3837
			if ( $index == 0 ) {
3838
				$jp_menu_order[] = 'jetpack';
3839
			}
3840
		}
3841
3842
		return $jp_menu_order;
3843
	}
3844
3845
	function admin_banner_styles() {
3846
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3847
3848
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3849
			wp_register_style(
3850
				'jetpack-dops-style',
3851
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3852
				array(),
3853
				JETPACK__VERSION
3854
			);
3855
		}
3856
3857
		wp_enqueue_style(
3858
			'jetpack',
3859
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3860
			array( 'jetpack-dops-style' ),
3861
			 JETPACK__VERSION . '-20121016'
3862
		);
3863
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3864
		wp_style_add_data( 'jetpack', 'suffix', $min );
3865
	}
3866
3867
	function plugin_action_links( $actions ) {
3868
3869
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3870
3871
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3872
			return array_merge(
3873
				$jetpack_home,
3874
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3875
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3876
				$actions
3877
				);
3878
			}
3879
3880
		return array_merge( $jetpack_home, $actions );
3881
	}
3882
3883
	/*
3884
	 * Registration flow:
3885
	 * 1 - ::admin_page_load() action=register
3886
	 * 2 - ::try_registration()
3887
	 * 3 - ::register()
3888
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3889
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3890
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3891
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3892
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3893
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3894
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3895
	 *       jetpack_id, jetpack_secret, jetpack_public
3896
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3897
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3898
	 * 5 - user logs in with WP.com account
3899
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3900
	 *		- Jetpack_Client_Server::authorize()
3901
	 *		- Jetpack_Client_Server::get_token()
3902
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3903
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3904
	 *			- which responds with access_token, token_type, scope
3905
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3906
	 *		- Jetpack::activate_default_modules()
3907
	 *     		- Deactivates deprecated plugins
3908
	 *     		- Activates all default modules
3909
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3910
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3911
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3912
	 *     Done!
3913
	 */
3914
3915
	/**
3916
	 * Handles the page load events for the Jetpack admin page
3917
	 */
3918
	function admin_page_load() {
3919
		$error = false;
3920
3921
		// Make sure we have the right body class to hook stylings for subpages off of.
3922
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3923
3924
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3925
			// Should only be used in intermediate redirects to preserve state across redirects
3926
			Jetpack::restate();
3927
		}
3928
3929
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3930
			// @todo: Add validation against a known whitelist
3931
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3932
			// User clicked in the iframe to link their accounts
3933
			if ( ! Jetpack::is_user_connected() ) {
3934
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3935
3936
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3937
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3938
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3939
3940
				if ( isset( $_GET['notes_iframe'] ) )
3941
					$connect_url .= '&notes_iframe';
3942
				wp_redirect( $connect_url );
3943
				exit;
3944
			} else {
3945
				if ( ! isset( $_GET['calypso_env'] ) ) {
3946
					Jetpack::state( 'message', 'already_authorized' );
3947
					wp_safe_redirect( Jetpack::admin_url() );
3948
					exit;
3949
				} else {
3950
					$connect_url = $this->build_connect_url( true, false, $from );
3951
					$connect_url .= '&already_authorized=true';
3952
					wp_redirect( $connect_url );
3953
					exit;
3954
				}
3955
			}
3956
		}
3957
3958
3959
		if ( isset( $_GET['action'] ) ) {
3960
			switch ( $_GET['action'] ) {
3961
			case 'authorize':
3962
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3963
					Jetpack::state( 'message', 'already_authorized' );
3964
					wp_safe_redirect( Jetpack::admin_url() );
3965
					exit;
3966
				}
3967
				Jetpack::log( 'authorize' );
3968
				$client_server = new Jetpack_Client_Server;
3969
				$client_server->client_authorize();
3970
				exit;
3971
			case 'register' :
3972
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3973
					$error = 'cheatin';
3974
					break;
3975
				}
3976
				check_admin_referer( 'jetpack-register' );
3977
				Jetpack::log( 'register' );
3978
				Jetpack::maybe_set_version_option();
3979
				$registered = Jetpack::try_registration();
3980
				if ( is_wp_error( $registered ) ) {
3981
					$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...
3982
					Jetpack::state( 'error', $error );
3983
					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...
3984
3985
					/**
3986
					 * Jetpack registration Error.
3987
					 *
3988
					 * @since 7.5.0
3989
					 *
3990
					 * @param string|int $error The error code.
3991
					 * @param \WP_Error $registered The error object.
3992
					 */
3993
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3994
					break;
3995
				}
3996
3997
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3998
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3999
4000
				/**
4001
				 * Jetpack registration Success.
4002
				 *
4003
				 * @since 7.5.0
4004
				 *
4005
				 * @param string $from 'from' GET parameter;
4006
				 */
4007
				do_action( 'jetpack_connection_register_success', $from );
4008
4009
				$url = $this->build_connect_url( true, $redirect, $from );
4010
4011
				if ( ! empty( $_GET['onboarding'] ) ) {
4012
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4013
				}
4014
4015
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4016
					$url = add_query_arg( 'auth_approved', 'true', $url );
4017
				}
4018
4019
				wp_redirect( $url );
4020
				exit;
4021
			case 'activate' :
4022
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4023
					$error = 'cheatin';
4024
					break;
4025
				}
4026
4027
				$module = stripslashes( $_GET['module'] );
4028
				check_admin_referer( "jetpack_activate-$module" );
4029
				Jetpack::log( 'activate', $module );
4030
				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...
4031
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4032
				}
4033
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4034
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4035
				exit;
4036
			case 'activate_default_modules' :
4037
				check_admin_referer( 'activate_default_modules' );
4038
				Jetpack::log( 'activate_default_modules' );
4039
				Jetpack::restate();
4040
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4041
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4042
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4043
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4044
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4045
				exit;
4046
			case 'disconnect' :
4047
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4048
					$error = 'cheatin';
4049
					break;
4050
				}
4051
4052
				check_admin_referer( 'jetpack-disconnect' );
4053
				Jetpack::log( 'disconnect' );
4054
				Jetpack::disconnect();
4055
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4056
				exit;
4057
			case 'reconnect' :
4058
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4059
					$error = 'cheatin';
4060
					break;
4061
				}
4062
4063
				check_admin_referer( 'jetpack-reconnect' );
4064
				Jetpack::log( 'reconnect' );
4065
				$this->disconnect();
4066
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4067
				exit;
4068 View Code Duplication
			case 'deactivate' :
4069
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4070
					$error = 'cheatin';
4071
					break;
4072
				}
4073
4074
				$modules = stripslashes( $_GET['module'] );
4075
				check_admin_referer( "jetpack_deactivate-$modules" );
4076
				foreach ( explode( ',', $modules ) as $module ) {
4077
					Jetpack::log( 'deactivate', $module );
4078
					Jetpack::deactivate_module( $module );
4079
					Jetpack::state( 'message', 'module_deactivated' );
4080
				}
4081
				Jetpack::state( 'module', $modules );
4082
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4083
				exit;
4084
			case 'unlink' :
4085
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4086
				check_admin_referer( 'jetpack-unlink' );
4087
				Jetpack::log( 'unlink' );
4088
				Connection_Manager::disconnect_user();
4089
				Jetpack::state( 'message', 'unlinked' );
4090
				if ( 'sub-unlink' == $redirect ) {
4091
					wp_safe_redirect( admin_url() );
4092
				} else {
4093
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4094
				}
4095
				exit;
4096
			case 'onboard' :
4097
				if ( ! current_user_can( 'manage_options' ) ) {
4098
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4099
				} else {
4100
					Jetpack::create_onboarding_token();
4101
					$url = $this->build_connect_url( true );
4102
4103
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4104
						$url = add_query_arg( 'onboarding', $token, $url );
4105
					}
4106
4107
					$calypso_env = $this->get_calypso_env();
4108
					if ( ! empty( $calypso_env ) ) {
4109
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4110
					}
4111
4112
					wp_redirect( $url );
4113
					exit;
4114
				}
4115
				exit;
4116
			default:
4117
				/**
4118
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4119
				 *
4120
				 * @since 2.6.0
4121
				 *
4122
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4123
				 */
4124
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4125
			}
4126
		}
4127
4128
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4129
			self::activate_new_modules( true );
4130
		}
4131
4132
		$message_code = Jetpack::state( 'message' );
4133
		if ( Jetpack::state( 'optin-manage' ) ) {
4134
			$activated_manage = $message_code;
4135
			$message_code = 'jetpack-manage';
4136
		}
4137
4138
		switch ( $message_code ) {
4139
		case 'jetpack-manage':
4140
			$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>';
4141
			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...
4142
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4143
			}
4144
			break;
4145
4146
		}
4147
4148
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4149
4150
		if ( ! empty( $deactivated_plugins ) ) {
4151
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4152
			$deactivated_titles  = array();
4153
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4154
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4155
					continue;
4156
				}
4157
4158
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4159
			}
4160
4161
			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...
4162
				if ( $this->message ) {
4163
					$this->message .= "<br /><br />\n";
4164
				}
4165
4166
				$this->message .= wp_sprintf(
4167
					_n(
4168
						'Jetpack contains the most recent version of the old %l plugin.',
4169
						'Jetpack contains the most recent versions of the old %l plugins.',
4170
						count( $deactivated_titles ),
4171
						'jetpack'
4172
					),
4173
					$deactivated_titles
4174
				);
4175
4176
				$this->message .= "<br />\n";
4177
4178
				$this->message .= _n(
4179
					'The old version has been deactivated and can be removed from your site.',
4180
					'The old versions have been deactivated and can be removed from your site.',
4181
					count( $deactivated_titles ),
4182
					'jetpack'
4183
				);
4184
			}
4185
		}
4186
4187
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4188
4189
		if ( $this->message || $this->error || $this->privacy_checks ) {
4190
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4191
		}
4192
4193
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4194
	}
4195
4196
	function admin_notices() {
4197
4198
		if ( $this->error ) {
4199
?>
4200
<div id="message" class="jetpack-message jetpack-err">
4201
	<div class="squeezer">
4202
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4203
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4204
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4205
<?php	endif; ?>
4206
	</div>
4207
</div>
4208
<?php
4209
		}
4210
4211
		if ( $this->message ) {
4212
?>
4213
<div id="message" class="jetpack-message">
4214
	<div class="squeezer">
4215
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4216
	</div>
4217
</div>
4218
<?php
4219
		}
4220
4221
		if ( $this->privacy_checks ) :
4222
			$module_names = $module_slugs = array();
4223
4224
			$privacy_checks = explode( ',', $this->privacy_checks );
4225
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4226
			foreach ( $privacy_checks as $module_slug ) {
4227
				$module = Jetpack::get_module( $module_slug );
4228
				if ( ! $module ) {
4229
					continue;
4230
				}
4231
4232
				$module_slugs[] = $module_slug;
4233
				$module_names[] = "<strong>{$module['name']}</strong>";
4234
			}
4235
4236
			$module_slugs = join( ',', $module_slugs );
4237
?>
4238
<div id="message" class="jetpack-message jetpack-err">
4239
	<div class="squeezer">
4240
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4241
		<p><?php
4242
			echo wp_kses(
4243
				wptexturize(
4244
					wp_sprintf(
4245
						_nx(
4246
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4247
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4248
							count( $privacy_checks ),
4249
							'%l = list of Jetpack module/feature names',
4250
							'jetpack'
4251
						),
4252
						$module_names
4253
					)
4254
				),
4255
				array( 'strong' => true )
4256
			);
4257
4258
			echo "\n<br />\n";
4259
4260
			echo wp_kses(
4261
				sprintf(
4262
					_nx(
4263
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4264
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4265
						count( $privacy_checks ),
4266
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4267
						'jetpack'
4268
					),
4269
					wp_nonce_url(
4270
						Jetpack::admin_url(
4271
							array(
4272
								'page'   => 'jetpack',
4273
								'action' => 'deactivate',
4274
								'module' => urlencode( $module_slugs ),
4275
							)
4276
						),
4277
						"jetpack_deactivate-$module_slugs"
4278
					),
4279
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4280
				),
4281
				array( 'a' => array( 'href' => true, 'title' => true ) )
4282
			);
4283
		?></p>
4284
	</div>
4285
</div>
4286
<?php endif;
4287
	}
4288
4289
	/**
4290
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4291
	 */
4292
	function stat( $group, $detail ) {
4293
		if ( ! isset( $this->stats[ $group ] ) )
4294
			$this->stats[ $group ] = array();
4295
		$this->stats[ $group ][] = $detail;
4296
	}
4297
4298
	/**
4299
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4300
	 */
4301
	function do_stats( $method = '' ) {
4302
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4303
			foreach ( $this->stats as $group => $stats ) {
4304
				if ( is_array( $stats ) && count( $stats ) ) {
4305
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4306
					if ( 'server_side' === $method ) {
4307
						self::do_server_side_stat( $args );
4308
					} else {
4309
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4310
					}
4311
				}
4312
				unset( $this->stats[ $group ] );
4313
			}
4314
		}
4315
	}
4316
4317
	/**
4318
	 * Runs stats code for a one-off, server-side.
4319
	 *
4320
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4321
	 *
4322
	 * @return bool If it worked.
4323
	 */
4324
	static function do_server_side_stat( $args ) {
4325
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4326
		if ( is_wp_error( $response ) )
4327
			return false;
4328
4329
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4330
			return false;
4331
4332
		return true;
4333
	}
4334
4335
	/**
4336
	 * Builds the stats url.
4337
	 *
4338
	 * @param $args array|string The arguments to append to the URL.
4339
	 *
4340
	 * @return string The URL to be pinged.
4341
	 */
4342
	static function build_stats_url( $args ) {
4343
		$defaults = array(
4344
			'v'    => 'wpcom2',
4345
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4346
		);
4347
		$args     = wp_parse_args( $args, $defaults );
4348
		/**
4349
		 * Filter the URL used as the Stats tracking pixel.
4350
		 *
4351
		 * @since 2.3.2
4352
		 *
4353
		 * @param string $url Base URL used as the Stats tracking pixel.
4354
		 */
4355
		$base_url = apply_filters(
4356
			'jetpack_stats_base_url',
4357
			'https://pixel.wp.com/g.gif'
4358
		);
4359
		$url      = add_query_arg( $args, $base_url );
4360
		return $url;
4361
	}
4362
4363
	/**
4364
	 * Get the role of the current user.
4365
	 *
4366
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4367
	 *
4368
	 * @access public
4369
	 * @static
4370
	 *
4371
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4372
	 */
4373
	public static function translate_current_user_to_role() {
4374
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4375
4376
		$roles = new Roles();
4377
		return $roles->translate_current_user_to_role();
4378
	}
4379
4380
	/**
4381
	 * Get the role of a particular user.
4382
	 *
4383
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4384
	 *
4385
	 * @access public
4386
	 * @static
4387
	 *
4388
	 * @param \WP_User $user User object.
4389
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4390
	 */
4391
	public static function translate_user_to_role( $user ) {
4392
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4393
4394
		$roles = new Roles();
4395
		return $roles->translate_user_to_role( $user );
4396
	}
4397
4398
	/**
4399
	 * Get the minimum capability for a role.
4400
	 *
4401
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4402
	 *
4403
	 * @access public
4404
	 * @static
4405
	 *
4406
	 * @param string $role Role name.
4407
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4408
	 */
4409
	public static function translate_role_to_cap( $role ) {
4410
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4411
4412
		$roles = new Roles();
4413
		return $roles->translate_role_to_cap( $role );
4414
	}
4415
4416
	static function sign_role( $role, $user_id = null ) {
4417
		if ( empty( $user_id ) ) {
4418
			$user_id = (int) get_current_user_id();
4419
		}
4420
4421
		if ( ! $user_id  ) {
4422
			return false;
4423
		}
4424
4425
		$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...
4426
		if ( ! $token || is_wp_error( $token ) ) {
4427
			return false;
4428
		}
4429
4430
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4431
	}
4432
4433
4434
	/**
4435
	 * Builds a URL to the Jetpack connection auth page
4436
	 *
4437
	 * @since 3.9.5
4438
	 *
4439
	 * @param bool $raw If true, URL will not be escaped.
4440
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4441
	 *                              If string, will be a custom redirect.
4442
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4443
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4444
	 *
4445
	 * @return string Connect URL
4446
	 */
4447
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4448
		$site_id = Jetpack_Options::get_option( 'id' );
4449
		$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...
4450
4451
		if ( $register || ! $blog_token || ! $site_id ) {
4452
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4453
4454
			if ( ! empty( $redirect ) ) {
4455
				$url = add_query_arg(
4456
					'redirect',
4457
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4458
					$url
4459
				);
4460
			}
4461
4462
			if( is_network_admin() ) {
4463
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4464
			}
4465
		} else {
4466
4467
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4468
			// because otherwise this logic can get us in to a loop.
4469
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4470
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4471
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4472
4473
				$response = Client::wpcom_json_api_request_as_blog(
4474
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4475
					'1.1'
4476
				);
4477
4478
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4479
4480
					// Generating a register URL instead to refresh the existing token
4481
					return $this->build_connect_url( $raw, $redirect, $from, true );
4482
				}
4483
			}
4484
4485
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4447 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4486
		}
4487
4488
		if ( $from ) {
4489
			$url = add_query_arg( 'from', $from, $url );
4490
		}
4491
4492
		// Ensure that class to get the affiliate code is loaded
4493
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4494
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4495
		}
4496
		// Get affiliate code and add it to the URL
4497
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4498
4499
		$calypso_env = $this->get_calypso_env();
4500
4501
		if ( ! empty( $calypso_env ) ) {
4502
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4503
		}
4504
4505
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4506
	}
4507
4508
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4509
		if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4510
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4511
		}
4512
4513
		$roles       = new Roles();
4514
		$role        = $roles->translate_current_user_to_role();
4515
		$signed_role = self::sign_role( $role );
4516
4517
		$user = wp_get_current_user();
4518
4519
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4520
		$redirect = $redirect
4521
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4522
			: $jetpack_admin_page;
4523
4524
		if( isset( $_REQUEST['is_multisite'] ) ) {
4525
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4526
		}
4527
4528
		$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4529
4530
		/**
4531
		 * Filter the type of authorization.
4532
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4533
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4534
		 *
4535
		 * @since 4.3.3
4536
		 *
4537
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4538
		 */
4539
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4540
4541
4542
		$tracks = new Tracking();
4543
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4544
4545
		$args = urlencode_deep(
4546
			array(
4547
				'response_type' => 'code',
4548
				'client_id'     => Jetpack_Options::get_option( 'id' ),
4549
				'redirect_uri'  => add_query_arg(
4550
					array(
4551
						'action'   => 'authorize',
4552
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4553
						'redirect' => urlencode( $redirect ),
4554
					),
4555
					esc_url( admin_url( 'admin.php?page=jetpack' ) )
4556
				),
4557
				'state'         => $user->ID,
4558
				'scope'         => $signed_role,
4559
				'user_email'    => $user->user_email,
4560
				'user_login'    => $user->user_login,
4561
				'is_active'     => Jetpack::is_active(),
4562
				'jp_version'    => JETPACK__VERSION,
4563
				'auth_type'     => $auth_type,
4564
				'secret'        => $secrets['secret_1'],
4565
				'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4566
				'blogname'      => get_option( 'blogname' ),
4567
				'site_url'      => site_url(),
4568
				'home_url'      => home_url(),
4569
				'site_icon'     => get_site_icon_url(),
4570
				'site_lang'     => get_locale(),
4571
				'_ui'           => $tracks_identity['_ui'],
4572
				'_ut'           => $tracks_identity['_ut'],
4573
				'site_created'  => Jetpack::get_assumed_site_creation_date(),
4574
			)
4575
		);
4576
4577
		self::apply_activation_source_to_args( $args );
4578
4579
		$connection = self::connection();
4580
4581
		$api_url = $iframe ? $connection->api_url( 'authorize_iframe' ) : $connection->api_url( 'authorize' );
4582
4583
		return add_query_arg( $args, $api_url );
4584
	}
4585
4586
	/**
4587
	 * Get our assumed site creation date.
4588
	 * Calculated based on the earlier date of either:
4589
	 * - Earliest admin user registration date.
4590
	 * - Earliest date of post of any post type.
4591
	 *
4592
	 * @since 7.2.0
4593
	 *
4594
	 * @return string Assumed site creation date and time.
4595
	 */
4596 View Code Duplication
	public static function get_assumed_site_creation_date() {
4597
		$earliest_registered_users = get_users( array(
4598
			'role'    => 'administrator',
4599
			'orderby' => 'user_registered',
4600
			'order'   => 'ASC',
4601
			'fields'  => array( 'user_registered' ),
4602
			'number'  => 1,
4603
		) );
4604
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4605
4606
		$earliest_posts = get_posts( array(
4607
			'posts_per_page' => 1,
4608
			'post_type'      => 'any',
4609
			'post_status'    => 'any',
4610
			'orderby'        => 'date',
4611
			'order'          => 'ASC',
4612
		) );
4613
4614
		// If there are no posts at all, we'll count only on user registration date.
4615
		if ( $earliest_posts ) {
4616
			$earliest_post_date = $earliest_posts[0]->post_date;
4617
		} else {
4618
			$earliest_post_date = PHP_INT_MAX;
4619
		}
4620
4621
		return min( $earliest_registration_date, $earliest_post_date );
4622
	}
4623
4624 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4625
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4626
4627
		if ( $activation_source_name ) {
4628
			$args['_as'] = urlencode( $activation_source_name );
4629
		}
4630
4631
		if ( $activation_source_keyword ) {
4632
			$args['_ak'] = urlencode( $activation_source_keyword );
4633
		}
4634
	}
4635
4636
	function build_reconnect_url( $raw = false ) {
4637
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4638
		return $raw ? $url : esc_url( $url );
4639
	}
4640
4641
	public static function admin_url( $args = null ) {
4642
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4643
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4644
		return $url;
4645
	}
4646
4647
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4648
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4649
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4650
	}
4651
4652
	function dismiss_jetpack_notice() {
4653
4654
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4655
			return;
4656
		}
4657
4658
		switch( $_GET['jetpack-notice'] ) {
4659
			case 'dismiss':
4660
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4661
4662
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4663
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4664
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4665
				}
4666
				break;
4667
		}
4668
	}
4669
4670
	public static function sort_modules( $a, $b ) {
4671
		if ( $a['sort'] == $b['sort'] )
4672
			return 0;
4673
4674
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4675
	}
4676
4677
	function ajax_recheck_ssl() {
4678
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4679
		$result = Jetpack::permit_ssl( true );
4680
		wp_send_json( array(
4681
			'enabled' => $result,
4682
			'message' => get_transient( 'jetpack_https_test_message' )
4683
		) );
4684
	}
4685
4686
/* Client API */
4687
4688
	/**
4689
	 * Returns the requested Jetpack API URL
4690
	 *
4691
	 * @deprecated since 7.7
4692
	 * @return string
4693
	 */
4694
	public static function api_url( $relative_url ) {
4695
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4696
		$connection = self::connection();
4697
		return $connection->api_url( $relative_url );
4698
	}
4699
4700
	/**
4701
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4702
	 */
4703
	public static function fix_url_for_bad_hosts( $url ) {
4704
		if ( 0 !== strpos( $url, 'https://' ) ) {
4705
			return $url;
4706
		}
4707
4708
		switch ( JETPACK_CLIENT__HTTPS ) {
4709
			case 'ALWAYS' :
4710
				return $url;
4711
			case 'NEVER' :
4712
				return set_url_scheme( $url, 'http' );
4713
			// default : case 'AUTO' :
4714
		}
4715
4716
		// we now return the unmodified SSL URL by default, as a security precaution
4717
		return $url;
4718
	}
4719
4720
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4721
		// Default to a blog token.
4722
		$token_type = 'blog';
4723
4724
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4725
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4726
			if ( ! empty( $_GET['onboarding'] ) ) {
4727
				$jpo = $_GET;
4728
			} else {
4729
				$jpo = json_decode( $request_data, true );
4730
			}
4731
4732
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4733
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4734
4735
			if (
4736
				isset( $jpo_user )
4737
				&& isset( $jpo_token )
4738
				&& is_email( $jpo_user )
4739
				&& ctype_alnum( $jpo_token )
4740
				&& isset( $_GET['rest_route'] )
4741
				&& self::validate_onboarding_token_action(
4742
					$jpo_token,
4743
					$_GET['rest_route']
4744
				)
4745
			) {
4746
				$jp_user = get_user_by( 'email', $jpo_user );
4747
				if ( is_a( $jp_user, 'WP_User' ) ) {
4748
					wp_set_current_user( $jp_user->ID );
4749
					$user_can = is_multisite()
4750
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4751
						: current_user_can( 'manage_options' );
4752
					if ( $user_can ) {
4753
						$token_type = 'user';
4754
						$token->external_user_id = $jp_user->ID;
4755
					}
4756
				}
4757
			}
4758
4759
			$token_data['type']    = $token_type;
4760
			$token_data['user_id'] = $token->external_user_id;
4761
		}
4762
4763
		return $token_data;
4764
	}
4765
4766
	/**
4767
	 * Create a random secret for validating onboarding payload
4768
	 *
4769
	 * @return string Secret token
4770
	 */
4771
	public static function create_onboarding_token() {
4772
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4773
			$token = wp_generate_password( 32, false );
4774
			Jetpack_Options::update_option( 'onboarding', $token );
4775
		}
4776
4777
		return $token;
4778
	}
4779
4780
	/**
4781
	 * Remove the onboarding token
4782
	 *
4783
	 * @return bool True on success, false on failure
4784
	 */
4785
	public static function invalidate_onboarding_token() {
4786
		return Jetpack_Options::delete_option( 'onboarding' );
4787
	}
4788
4789
	/**
4790
	 * Validate an onboarding token for a specific action
4791
	 *
4792
	 * @return boolean True if token/action pair is accepted, false if not
4793
	 */
4794
	public static function validate_onboarding_token_action( $token, $action ) {
4795
		// Compare tokens, bail if tokens do not match
4796
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4797
			return false;
4798
		}
4799
4800
		// List of valid actions we can take
4801
		$valid_actions = array(
4802
			'/jetpack/v4/settings',
4803
		);
4804
4805
		// Whitelist the action
4806
		if ( ! in_array( $action, $valid_actions ) ) {
4807
			return false;
4808
		}
4809
4810
		return true;
4811
	}
4812
4813
	/**
4814
	 * Checks to see if the URL is using SSL to connect with Jetpack
4815
	 *
4816
	 * @since 2.3.3
4817
	 * @return boolean
4818
	 */
4819
	public static function permit_ssl( $force_recheck = false ) {
4820
		// Do some fancy tests to see if ssl is being supported
4821
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4822
			$message = '';
4823
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4824
				$ssl = 0;
4825
			} else {
4826
				switch ( JETPACK_CLIENT__HTTPS ) {
4827
					case 'NEVER':
4828
						$ssl = 0;
4829
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4830
						break;
4831
					case 'ALWAYS':
4832
					case 'AUTO':
4833
					default:
4834
						$ssl = 1;
4835
						break;
4836
				}
4837
4838
				// If it's not 'NEVER', test to see
4839
				if ( $ssl ) {
4840
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4841
						$ssl = 0;
4842
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4843
					} else {
4844
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4845
						if ( is_wp_error( $response ) ) {
4846
							$ssl = 0;
4847
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4848
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4849
							$ssl = 0;
4850
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4851
						}
4852
					}
4853
				}
4854
			}
4855
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4856
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4857
		}
4858
4859
		return (bool) $ssl;
4860
	}
4861
4862
	/*
4863
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4864
	 */
4865
	public function alert_auto_ssl_fail() {
4866
		if ( ! current_user_can( 'manage_options' ) )
4867
			return;
4868
4869
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4870
		?>
4871
4872
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4873
			<div class="jp-banner__content">
4874
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4875
				<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>
4876
				<p>
4877
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4878
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4879
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4880
				</p>
4881
				<p>
4882
					<?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' ),
4883
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4884
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4885
				</p>
4886
			</div>
4887
		</div>
4888
		<style>
4889
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4890
		</style>
4891
		<script type="text/javascript">
4892
			jQuery( document ).ready( function( $ ) {
4893
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4894
					var $this = $( this );
4895
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4896
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4897
					e.preventDefault();
4898
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4899
					$.post( ajaxurl, data )
4900
					  .done( function( response ) {
4901
					  	if ( response.enabled ) {
4902
					  		$( '#jetpack-ssl-warning' ).hide();
4903
					  	} else {
4904
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4905
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4906
					  	}
4907
					  }.bind( $this ) );
4908
				} );
4909
			} );
4910
		</script>
4911
4912
		<?php
4913
	}
4914
4915
	/**
4916
	 * Returns the Jetpack XML-RPC API
4917
	 *
4918
	 * @return string
4919
	 */
4920
	public static function xmlrpc_api_url() {
4921
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4922
		return untrailingslashit( $base ) . '/xmlrpc.php';
4923
	}
4924
4925
	public static function connection() {
4926
		return self::init()->connection_manager;
4927
	}
4928
4929
	/**
4930
	 * Creates two secret tokens and the end of life timestamp for them.
4931
	 *
4932
	 * Note these tokens are unique per call, NOT static per site for connecting.
4933
	 *
4934
	 * @since 2.6
4935
	 * @return array
4936
	 */
4937
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4938
		if ( false === $user_id ) {
4939
			$user_id = get_current_user_id();
4940
		}
4941
4942
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4943
	}
4944
4945
	public static function get_secrets( $action, $user_id ) {
4946
		$secrets = self::connection()->get_secrets( $action, $user_id );
4947
4948
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4949
			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...
4950
		}
4951
4952
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4953
			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...
4954
		}
4955
4956
		return $secrets;
4957
	}
4958
4959
	/**
4960
	 * @deprecated 7.5 Use Connection_Manager instead.
4961
	 *
4962
	 * @param $action
4963
	 * @param $user_id
4964
	 */
4965
	public static function delete_secrets( $action, $user_id ) {
4966
		return self::connection()->delete_secrets( $action, $user_id );
4967
	}
4968
4969
	/**
4970
	 * Builds the timeout limit for queries talking with the wpcom servers.
4971
	 *
4972
	 * Based on local php max_execution_time in php.ini
4973
	 *
4974
	 * @since 2.6
4975
	 * @return int
4976
	 * @deprecated
4977
	 **/
4978
	public function get_remote_query_timeout_limit() {
4979
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4980
		return Jetpack::get_max_execution_time();
4981
	}
4982
4983
	/**
4984
	 * Builds the timeout limit for queries talking with the wpcom servers.
4985
	 *
4986
	 * Based on local php max_execution_time in php.ini
4987
	 *
4988
	 * @since 5.4
4989
	 * @return int
4990
	 **/
4991
	public static function get_max_execution_time() {
4992
		$timeout = (int) ini_get( 'max_execution_time' );
4993
4994
		// Ensure exec time set in php.ini
4995
		if ( ! $timeout ) {
4996
			$timeout = 30;
4997
		}
4998
		return $timeout;
4999
	}
5000
5001
	/**
5002
	 * Sets a minimum request timeout, and returns the current timeout
5003
	 *
5004
	 * @since 5.4
5005
	 **/
5006 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5007
		$timeout = self::get_max_execution_time();
5008
		if ( $timeout < $min_timeout ) {
5009
			$timeout = $min_timeout;
5010
			set_time_limit( $timeout );
5011
		}
5012
		return $timeout;
5013
	}
5014
5015
	/**
5016
	 * Takes the response from the Jetpack register new site endpoint and
5017
	 * verifies it worked properly.
5018
	 *
5019
	 * @since 2.6
5020
	 * @deprecated since 7.7.0
5021
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5022
	 **/
5023
	public function validate_remote_register_response() {
5024
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5025
	}
5026
5027
	/**
5028
	 * @return bool|WP_Error
5029
	 */
5030
	public static function register() {
5031
		$tracking = new Tracking();
5032
		$tracking->record_user_event( 'jpc_register_begin' );
5033
5034
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5035
5036
		$connection = self::connection();
5037
		$registration = $connection->register();
5038
5039
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5040
5041
		if ( ! $registration || is_wp_error( $registration ) ) {
5042
			return $registration;
5043
		}
5044
5045
		return true;
5046
	}
5047
5048
	/**
5049
	 * Filters the registration request body to include tracking properties.
5050
	 *
5051
	 * @param Array $properties
5052
	 * @return Array amended properties.
5053
	 */
5054
	public static function filter_register_request_body( $properties ) {
5055
		$tracking = new Tracking();
5056
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5057
5058
		return array_merge(
5059
			$properties,
5060
			array(
5061
				'_ui' => $tracks_identity['_ui'],
5062
				'_ut' => $tracks_identity['_ut'],
5063
			)
5064
		);
5065
	}
5066
5067
	/**
5068
	 * If the db version is showing something other that what we've got now, bump it to current.
5069
	 *
5070
	 * @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...
5071
	 */
5072
	public static function maybe_set_version_option() {
5073
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5074
		if ( JETPACK__VERSION != $version ) {
5075
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5076
5077
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5078
				/** This action is documented in class.jetpack.php */
5079
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5080
			}
5081
5082
			return true;
5083
		}
5084
		return false;
5085
	}
5086
5087
/* Client Server API */
5088
5089
	/**
5090
	 * Loads the Jetpack XML-RPC client
5091
	 */
5092
	public static function load_xml_rpc_client() {
5093
		require_once ABSPATH . WPINC . '/class-IXR.php';
5094
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5095
	}
5096
5097
	/**
5098
	 * Resets the saved authentication state in between testing requests.
5099
	 */
5100
	public function reset_saved_auth_state() {
5101
		$this->rest_authentication_status = null;
5102
		$this->connection_manager->reset_saved_auth_state();
5103
	}
5104
5105
	/**
5106
	 * Verifies the signature of the current request.
5107
	 *
5108
	 * @deprecated since 7.7.0
5109
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5110
	 *
5111
	 * @return false|array
5112
	 */
5113
	public function verify_xml_rpc_signature() {
5114
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5115
		return self::connection()->verify_xml_rpc_signature();
5116
	}
5117
5118
	/**
5119
	 * Verifies the signature of the current request.
5120
	 *
5121
	 * This function has side effects and should not be used. Instead,
5122
	 * use the memoized version `->verify_xml_rpc_signature()`.
5123
	 *
5124
	 * @deprecated since 7.7.0
5125
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5126
	 * @internal
5127
	 */
5128
	private function internal_verify_xml_rpc_signature() {
5129
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5130
	}
5131
5132
	/**
5133
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5134
	 *
5135
	 * @deprecated since 7.7.0
5136
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5137
	 *
5138
	 * @param \WP_User|mixed $user     User object if authenticated.
5139
	 * @param string         $username Username.
5140
	 * @param string         $password Password string.
5141
	 * @return \WP_User|mixed Authenticated user or error.
5142
	 */
5143
	public function authenticate_jetpack( $user, $username, $password ) {
5144
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5145
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5146
	}
5147
5148
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5149
	// Uses the existing XMLRPC request signing implementation.
5150
	function wp_rest_authenticate( $user ) {
5151
		if ( ! empty( $user ) ) {
5152
			// Another authentication method is in effect.
5153
			return $user;
5154
		}
5155
5156
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5157
			// Nothing to do for this authentication method.
5158
			return null;
5159
		}
5160
5161
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5162
			// Nothing to do for this authentication method.
5163
			return null;
5164
		}
5165
5166
		// Ensure that we always have the request body available.  At this
5167
		// point, the WP REST API code to determine the request body has not
5168
		// run yet.  That code may try to read from 'php://input' later, but
5169
		// this can only be done once per request in PHP versions prior to 5.6.
5170
		// So we will go ahead and perform this read now if needed, and save
5171
		// the request body where both the Jetpack signature verification code
5172
		// and the WP REST API code can see it.
5173
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5174
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5175
		}
5176
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5177
5178
		// Only support specific request parameters that have been tested and
5179
		// are known to work with signature verification.  A different method
5180
		// can be passed to the WP REST API via the '?_method=' parameter if
5181
		// needed.
5182
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5183
			$this->rest_authentication_status = new WP_Error(
5184
				'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...
5185
				__( 'This request method is not supported.', 'jetpack' ),
5186
				array( 'status' => 400 )
5187
			);
5188
			return null;
5189
		}
5190
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5191
			$this->rest_authentication_status = new WP_Error(
5192
				'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...
5193
				__( 'This request method does not support body parameters.', 'jetpack' ),
5194
				array( 'status' => 400 )
5195
			);
5196
			return null;
5197
		}
5198
5199
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5200
5201
		if (
5202
			$verified &&
5203
			isset( $verified['type'] ) &&
5204
			'user' === $verified['type'] &&
5205
			! empty( $verified['user_id'] )
5206
		) {
5207
			// Authentication successful.
5208
			$this->rest_authentication_status = true;
5209
			return $verified['user_id'];
5210
		}
5211
5212
		// Something else went wrong.  Probably a signature error.
5213
		$this->rest_authentication_status = new WP_Error(
5214
			'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...
5215
			__( 'The request is not signed correctly.', 'jetpack' ),
5216
			array( 'status' => 400 )
5217
		);
5218
		return null;
5219
	}
5220
5221
	/**
5222
	 * Report authentication status to the WP REST API.
5223
	 *
5224
	 * @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...
5225
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5226
	 */
5227
	public function wp_rest_authentication_errors( $value ) {
5228
		if ( $value !== null ) {
5229
			return $value;
5230
		}
5231
		return $this->rest_authentication_status;
5232
	}
5233
5234
	/**
5235
	 * Add our nonce to this request.
5236
	 *
5237
	 * @deprecated since 7.7.0
5238
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5239
	 *
5240
	 * @param int    $timestamp Timestamp of the request.
5241
	 * @param string $nonce     Nonce string.
5242
	 */
5243
	public function add_nonce( $timestamp, $nonce ) {
5244
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5245
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5246
	}
5247
5248
	/**
5249
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5250
	 * Capture it here so we can verify the signature later.
5251
	 *
5252
	 * @deprecated since 7.7.0
5253
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5254
	 *
5255
	 * @param array $methods XMLRPC methods.
5256
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5257
	 */
5258
	public function xmlrpc_methods( $methods ) {
5259
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5260
		return $this->connection_manager->xmlrpc_methods( $methods );
5261
	}
5262
5263
	/**
5264
	 * Register additional public XMLRPC methods.
5265
	 *
5266
	 * @deprecated since 7.7.0
5267
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5268
	 *
5269
	 * @param array $methods Public XMLRPC methods.
5270
	 * @return array Public XMLRPC methods, with the getOptions one.
5271
	 */
5272
	public function public_xmlrpc_methods( $methods ) {
5273
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5274
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5275
	}
5276
5277
	/**
5278
	 * Handles a getOptions XMLRPC method call.
5279
	 *
5280
	 * @deprecated since 7.7.0
5281
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5282
	 *
5283
	 * @param array $args method call arguments.
5284
	 * @return array an amended XMLRPC server options array.
5285
	 */
5286
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5287
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5288
		return $this->connection_manager->jetpack_getOptions( $args );
5289
	}
5290
5291
	/**
5292
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5293
	 *
5294
	 * @deprecated since 7.7.0
5295
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5296
	 *
5297
	 * @param array $options Standard Core options.
5298
	 * @return array Amended options.
5299
	 */
5300
	public function xmlrpc_options( $options ) {
5301
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5302
		return $this->connection_manager->xmlrpc_options( $options );
5303
	}
5304
5305
	/**
5306
	 * Cleans nonces that were saved when calling ::add_nonce.
5307
	 *
5308
	 * @deprecated since 7.7.0
5309
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5310
	 *
5311
	 * @param bool $all whether to clean even non-expired nonces.
5312
	 */
5313
	public static function clean_nonces( $all = false ) {
5314
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5315
		return self::connection()->clean_nonces( $all );
5316
	}
5317
5318
	/**
5319
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5320
	 * SET: state( $key, $value );
5321
	 * GET: $value = state( $key );
5322
	 *
5323
	 * @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...
5324
	 * @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...
5325
	 * @param bool $restate private
5326
	 */
5327
	public static function state( $key = null, $value = null, $restate = false ) {
5328
		static $state = array();
5329
		static $path, $domain;
5330
		if ( ! isset( $path ) ) {
5331
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5332
			$admin_url = Jetpack::admin_url();
5333
			$bits      = wp_parse_url( $admin_url );
5334
5335
			if ( is_array( $bits ) ) {
5336
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5337
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5338
			} else {
5339
				$path = $domain = null;
5340
			}
5341
		}
5342
5343
		// Extract state from cookies and delete cookies
5344
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5345
			$yum = $_COOKIE[ 'jetpackState' ];
5346
			unset( $_COOKIE[ 'jetpackState' ] );
5347
			foreach ( $yum as $k => $v ) {
5348
				if ( strlen( $v ) )
5349
					$state[ $k ] = $v;
5350
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5351
			}
5352
		}
5353
5354
		if ( $restate ) {
5355
			foreach ( $state as $k => $v ) {
5356
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5357
			}
5358
			return;
5359
		}
5360
5361
		// Get a state variable
5362
		if ( isset( $key ) && ! isset( $value ) ) {
5363
			if ( array_key_exists( $key, $state ) )
5364
				return $state[ $key ];
5365
			return null;
5366
		}
5367
5368
		// Set a state variable
5369
		if ( isset ( $key ) && isset( $value ) ) {
5370
			if( is_array( $value ) && isset( $value[0] ) ) {
5371
				$value = $value[0];
5372
			}
5373
			$state[ $key ] = $value;
5374
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5375
		}
5376
	}
5377
5378
	public static function restate() {
5379
		Jetpack::state( null, null, true );
5380
	}
5381
5382
	public static function check_privacy( $file ) {
5383
		static $is_site_publicly_accessible = null;
5384
5385
		if ( is_null( $is_site_publicly_accessible ) ) {
5386
			$is_site_publicly_accessible = false;
5387
5388
			Jetpack::load_xml_rpc_client();
5389
			$rpc = new Jetpack_IXR_Client();
5390
5391
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5392
			if ( $success ) {
5393
				$response = $rpc->getResponse();
5394
				if ( $response ) {
5395
					$is_site_publicly_accessible = true;
5396
				}
5397
			}
5398
5399
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5400
		}
5401
5402
		if ( $is_site_publicly_accessible ) {
5403
			return;
5404
		}
5405
5406
		$module_slug = self::get_module_slug( $file );
5407
5408
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5409
		if ( ! $privacy_checks ) {
5410
			$privacy_checks = $module_slug;
5411
		} else {
5412
			$privacy_checks .= ",$module_slug";
5413
		}
5414
5415
		Jetpack::state( 'privacy_checks', $privacy_checks );
5416
	}
5417
5418
	/**
5419
	 * Helper method for multicall XMLRPC.
5420
	 */
5421
	public static function xmlrpc_async_call() {
5422
		global $blog_id;
5423
		static $clients = array();
5424
5425
		$client_blog_id = is_multisite() ? $blog_id : 0;
5426
5427
		if ( ! isset( $clients[$client_blog_id] ) ) {
5428
			Jetpack::load_xml_rpc_client();
5429
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5430
			if ( function_exists( 'ignore_user_abort' ) ) {
5431
				ignore_user_abort( true );
5432
			}
5433
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5434
		}
5435
5436
		$args = func_get_args();
5437
5438
		if ( ! empty( $args[0] ) ) {
5439
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5440
		} elseif ( is_multisite() ) {
5441
			foreach ( $clients as $client_blog_id => $client ) {
5442
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5443
					continue;
5444
				}
5445
5446
				$switch_success = switch_to_blog( $client_blog_id, true );
5447
				if ( ! $switch_success ) {
5448
					continue;
5449
				}
5450
5451
				flush();
5452
				$client->query();
5453
5454
				restore_current_blog();
5455
			}
5456
		} else {
5457
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5458
				flush();
5459
				$clients[0]->query();
5460
			}
5461
		}
5462
	}
5463
5464
	public static function staticize_subdomain( $url ) {
5465
5466
		// Extract hostname from URL
5467
		$host = parse_url( $url, PHP_URL_HOST );
5468
5469
		// Explode hostname on '.'
5470
		$exploded_host = explode( '.', $host );
5471
5472
		// Retrieve the name and TLD
5473
		if ( count( $exploded_host ) > 1 ) {
5474
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5475
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5476
			// Rebuild domain excluding subdomains
5477
			$domain = $name . '.' . $tld;
5478
		} else {
5479
			$domain = $host;
5480
		}
5481
		// Array of Automattic domains
5482
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5483
5484
		// Return $url if not an Automattic domain
5485
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5486
			return $url;
5487
		}
5488
5489
		if ( is_ssl() ) {
5490
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5491
		}
5492
5493
		srand( crc32( basename( $url ) ) );
5494
		$static_counter = rand( 0, 2 );
5495
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5496
5497
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5498
	}
5499
5500
/* JSON API Authorization */
5501
5502
	/**
5503
	 * Handles the login action for Authorizing the JSON API
5504
	 */
5505
	function login_form_json_api_authorization() {
5506
		$this->verify_json_api_authorization_request();
5507
5508
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5509
5510
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5511
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5512
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5513
	}
5514
5515
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5516
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5517
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5518
			return $url;
5519
		}
5520
5521
		$parsed_url = parse_url( $url );
5522
		$url = strtok( $url, '?' );
5523
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5524
		if ( ! empty( $parsed_url['query'] ) )
5525
			$url .= "&{$parsed_url['query']}";
5526
5527
		return $url;
5528
	}
5529
5530
	// Make sure the POSTed request is handled by the same action
5531
	function preserve_action_in_login_form_for_json_api_authorization() {
5532
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5533
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5534
	}
5535
5536
	// If someone logs in to approve API access, store the Access Code in usermeta
5537
	function store_json_api_authorization_token( $user_login, $user ) {
5538
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5539
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5540
		$token = wp_generate_password( 32, false );
5541
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5542
	}
5543
5544
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5545
	function allow_wpcom_public_api_domain( $domains ) {
5546
		$domains[] = 'public-api.wordpress.com';
5547
		return $domains;
5548
	}
5549
5550
	static function is_redirect_encoded( $redirect_url ) {
5551
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5552
	}
5553
5554
	// Add all wordpress.com environments to the safe redirect whitelist
5555
	function allow_wpcom_environments( $domains ) {
5556
		$domains[] = 'wordpress.com';
5557
		$domains[] = 'wpcalypso.wordpress.com';
5558
		$domains[] = 'horizon.wordpress.com';
5559
		$domains[] = 'calypso.localhost';
5560
		return $domains;
5561
	}
5562
5563
	// Add the Access Code details to the public-api.wordpress.com redirect
5564
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5565
		return add_query_arg(
5566
			urlencode_deep(
5567
				array(
5568
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5569
					'jetpack-user-id' => (int) $user->ID,
5570
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5571
				)
5572
			),
5573
			$redirect_to
5574
		);
5575
	}
5576
5577
5578
	/**
5579
	 * Verifies the request by checking the signature
5580
	 *
5581
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5582
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5583
	 *
5584
	 * @param null|array $environment
5585
	 */
5586
	function verify_json_api_authorization_request( $environment = null ) {
5587
		$environment = is_null( $environment )
5588
			? $_REQUEST
5589
			: $environment;
5590
5591
		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...
5592
		$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...
5593
		if ( ! $token || empty( $token->secret ) ) {
5594
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5595
		}
5596
5597
		$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' );
5598
5599
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5600
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5601
			/**
5602
			 * Jetpack authorisation request Error.
5603
			 *
5604
			 * @since 7.5.0
5605
			 *
5606
			 */
5607
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5608
			$die_error = sprintf(
5609
				/* translators: %s is a URL */
5610
				__( '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' ),
5611
				'https://jetpack.com/support/double-encoding/'
5612
			);
5613
		}
5614
5615
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5616
5617
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5618
			$signature = $jetpack_signature->sign_request(
5619
				$environment['token'],
5620
				$environment['timestamp'],
5621
				$environment['nonce'],
5622
				'',
5623
				'GET',
5624
				$environment['jetpack_json_api_original_query'],
5625
				null,
5626
				true
5627
			);
5628
		} else {
5629
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5630
		}
5631
5632
		if ( ! $signature ) {
5633
			wp_die( $die_error );
5634
		} else if ( is_wp_error( $signature ) ) {
5635
			wp_die( $die_error );
5636
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5637
			if ( is_ssl() ) {
5638
				// 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
5639
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5640
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5641
					wp_die( $die_error );
5642
				}
5643
			} else {
5644
				wp_die( $die_error );
5645
			}
5646
		}
5647
5648
		$timestamp = (int) $environment['timestamp'];
5649
		$nonce     = stripslashes( (string) $environment['nonce'] );
5650
5651
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
Bug introduced by
The property connection does not seem to exist. Did you mean connection_manager?

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

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

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