Completed
Push — renovate/jest-monorepo ( bd2eaf...d289c3 )
by
unknown
44:07 queued 37:28
created

Jetpack::internal_verify_xml_rpc_signature()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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