Completed
Push — iterate/calypsoify ( 2ba5fb...4d78ff )
by George
146:23 queued 138:29
created

Jetpack::load_jetpack_gutenberg()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 89

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 12
nop 0
dl 0
loc 89
rs 6.9955
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
551
552
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
553
			$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
554
555
			$this->require_jetpack_authentication();
556
557
			if ( Jetpack::is_active() ) {
558
				// Hack to preserve $HTTP_RAW_POST_DATA
559
				add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
560
561
				$signed = $this->verify_xml_rpc_signature();
562 View Code Duplication
				if ( $signed && ! is_wp_error( $signed ) ) {
563
					// The actual API methods.
564
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
565
				} else {
566
					// The jetpack.authorize method should be available for unauthenticated users on a site with an
567
					// active Jetpack connection, so that additional users can link their account.
568
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
569
				}
570 View Code Duplication
			} else {
571
				// The bootstrap API methods.
572
				add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
573
				$signed = $this->verify_xml_rpc_signature();
574
				if ( $signed && ! is_wp_error( $signed ) ) {
575
					// the jetpack Provision method is available for blog-token-signed requests
576
					add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'provision_xmlrpc_methods' ) );
577
				}
578
			}
579
580
			// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
581
			add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
582
		} elseif (
583
			is_admin() &&
584
			isset( $_POST['action'] ) && (
585
				'jetpack_upload_file' == $_POST['action'] ||
586
				'jetpack_update_file' == $_POST['action']
587
			)
588
		) {
589
			$this->require_jetpack_authentication();
590
			$this->add_remote_request_handlers();
591
		} else {
592
			if ( Jetpack::is_active() ) {
593
				add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
594
				add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
595
			}
596
		}
597
598
		if ( Jetpack::is_active() ) {
599
			Jetpack_Heartbeat::init();
600
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
601
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
602
				Jetpack_Search_Performance_Logger::init();
603
			}
604
		}
605
606
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
607
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
608
609
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
610
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
611
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
612
		}
613
614
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
615
616
		add_action( 'admin_init', array( $this, 'admin_init' ) );
617
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
618
619
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
620
621
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
622
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
623
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
624
625
		// returns HTTPS support status
626
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
627
628
		// If any module option is updated before Jump Start is dismissed, hide Jump Start.
629
		add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
630
631
		// JITM AJAX callback function
632
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
633
634
		// Universal ajax callback for all tracking events triggered via js
635
		add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
636
637
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
638
639
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
640
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
641
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
642
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
643
644
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
645
646
		/**
647
		 * These actions run checks to load additional files.
648
		 * They check for external files or plugins, so they need to run as late as possible.
649
		 */
650
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
651
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
652
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
653
654
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
655
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
656
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
657
658
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
659
660
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
661
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
662
663
		// A filter to control all just in time messages
664
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
665
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
666
667
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
668
		// We should make sure to only do this for front end links.
669
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
670
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
671
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
672
673
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
674
			//so they point moderation links on emails to Calypso
675
			jetpack_require_lib( 'functions.wp-notify' );
676
		}
677
678
		// Update the Jetpack plan from API on heartbeats
679
		add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
680
681
		/**
682
		 * This is the hack to concatenate all css files into one.
683
		 * For description and reasoning see the implode_frontend_css method
684
		 *
685
		 * Super late priority so we catch all the registered styles
686
		 */
687
		if( !is_admin() ) {
688
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
689
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
690
		}
691
692
		/**
693
		 * These are sync actions that we need to keep track of for jitms
694
		 */
695
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
696
697
		// Actually push the stats on shutdown.
698
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
699
			add_action( 'shutdown', array( $this, 'push_stats' ) );
700
		}
701
	}
702
703
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
704
		$post = get_post( $post_id );
705
706
		if ( empty( $post ) ) {
707
			return $default_url;
708
		}
709
710
		$post_type = $post->post_type;
711
712
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
713
		// https://en.support.wordpress.com/custom-post-types/
714
		$allowed_post_types = array(
715
			'post' => 'post',
716
			'page' => 'page',
717
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
718
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
719
		);
720
721
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
722
			return $default_url;
723
		}
724
725
		$path_prefix = $allowed_post_types[ $post_type ];
726
727
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
728
729
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
730
	}
731
732
	function point_edit_comment_links_to_calypso( $url ) {
733
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
734
		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...
735
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
736
			Jetpack::build_raw_urls( get_home_url() ),
737
			$query_args['amp;c']
738
		) );
739
	}
740
741
	function jetpack_track_last_sync_callback( $params ) {
742
		/**
743
		 * Filter to turn off jitm caching
744
		 *
745
		 * @since 5.4.0
746
		 *
747
		 * @param bool false Whether to cache just in time messages
748
		 */
749
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
750
			return $params;
751
		}
752
753
		if ( is_array( $params ) && isset( $params[0] ) ) {
754
			$option = $params[0];
755
			if ( 'active_plugins' === $option ) {
756
				// use the cache if we can, but not terribly important if it gets evicted
757
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
758
			}
759
		}
760
761
		return $params;
762
	}
763
764
	function jetpack_connection_banner_callback() {
765
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
766
767
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
768
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
769
			wp_send_json_success();
770
		}
771
772
		wp_die();
773
	}
774
775
	function jetpack_admin_ajax_tracks_callback() {
776
		// Check for nonce
777
		if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
778
			wp_die( 'Permissions check failed.' );
779
		}
780
781
		if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] )  ) {
782
			wp_die( 'No valid event name or type.' );
783
		}
784
785
		$tracks_data = array();
786
		if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
787
			if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
788
				$tracks_data = $_REQUEST['tracksEventProp'];
789
			} else {
790
				$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
791
			}
792
		}
793
794
		JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
795
		wp_send_json_success();
796
		wp_die();
797
	}
798
799
	/**
800
	 * The callback for the JITM ajax requests.
801
	 */
802
	function jetpack_jitm_ajax_callback() {
803
		// Check for nonce
804
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
805
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
806
		}
807
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
808
			$module_slug = $_REQUEST['jitmModule'];
809
			Jetpack::log( 'activate', $module_slug );
810
			Jetpack::activate_module( $module_slug, false, false );
811
			Jetpack::state( 'message', 'no_message' );
812
813
			//A Jetpack module is being activated through a JITM, track it
814
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
815
			$this->do_stats( 'server_side' );
816
817
			wp_send_json_success();
818
		}
819
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
820
			// get the hide_jitm options array
821
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
822
			$module_slug = $_REQUEST['jitmModule'];
823
824
			if( ! $jetpack_hide_jitm ) {
825
				$jetpack_hide_jitm = array(
826
					$module_slug => 'hide'
827
				);
828
			} else {
829
				$jetpack_hide_jitm[$module_slug] = 'hide';
830
			}
831
832
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
833
834
			//jitm is being dismissed forever, track it
835
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
836
			$this->do_stats( 'server_side' );
837
838
			wp_send_json_success();
839
		}
840 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
841
			$module_slug = $_REQUEST['jitmModule'];
842
843
			// User went to WordPress.com, track this
844
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
845
			$this->do_stats( 'server_side' );
846
847
			wp_send_json_success();
848
		}
849 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
850
			$track = $_REQUEST['jitmModule'];
851
852
			// User is viewing JITM, track it.
853
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
854
			$this->do_stats( 'server_side' );
855
856
			wp_send_json_success();
857
		}
858
	}
859
860
	/**
861
	 * If there are any stats that need to be pushed, but haven't been, push them now.
862
	 */
863
	function push_stats() {
864
		if ( ! empty( $this->stats ) ) {
865
			$this->do_stats( 'server_side' );
866
		}
867
	}
868
869
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
870
		switch( $cap ) {
871
			case 'jetpack_connect' :
872
			case 'jetpack_reconnect' :
873
				if ( Jetpack::is_development_mode() ) {
874
					$caps = array( 'do_not_allow' );
875
					break;
876
				}
877
				/**
878
				 * Pass through. If it's not development mode, these should match disconnect.
879
				 * Let users disconnect if it's development mode, just in case things glitch.
880
				 */
881
			case 'jetpack_disconnect' :
882
				/**
883
				 * In multisite, can individual site admins manage their own connection?
884
				 *
885
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
886
				 */
887
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
888
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
889
						/**
890
						 * We need to update the option name -- it's terribly unclear which
891
						 * direction the override goes.
892
						 *
893
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
894
						 */
895
						$caps = array( 'do_not_allow' );
896
						break;
897
					}
898
				}
899
900
				$caps = array( 'manage_options' );
901
				break;
902
			case 'jetpack_manage_modules' :
903
			case 'jetpack_activate_modules' :
904
			case 'jetpack_deactivate_modules' :
905
				$caps = array( 'manage_options' );
906
				break;
907
			case 'jetpack_configure_modules' :
908
				$caps = array( 'manage_options' );
909
				break;
910
			case 'jetpack_manage_autoupdates' :
911
				$caps = array(
912
					'manage_options',
913
					'update_plugins',
914
				);
915
				break;
916
			case 'jetpack_network_admin_page':
917
			case 'jetpack_network_settings_page':
918
				$caps = array( 'manage_network_plugins' );
919
				break;
920
			case 'jetpack_network_sites_page':
921
				$caps = array( 'manage_sites' );
922
				break;
923
			case 'jetpack_admin_page' :
924
				if ( Jetpack::is_development_mode() ) {
925
					$caps = array( 'manage_options' );
926
					break;
927
				} else {
928
					$caps = array( 'read' );
929
				}
930
				break;
931
			case 'jetpack_connect_user' :
932
				if ( Jetpack::is_development_mode() ) {
933
					$caps = array( 'do_not_allow' );
934
					break;
935
				}
936
				$caps = array( 'read' );
937
				break;
938
		}
939
		return $caps;
940
	}
941
942
	function require_jetpack_authentication() {
943
		// Don't let anyone authenticate
944
		$_COOKIE = array();
945
		remove_all_filters( 'authenticate' );
946
		remove_all_actions( 'wp_login_failed' );
947
948
		if ( Jetpack::is_active() ) {
949
			// Allow Jetpack authentication
950
			add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
951
		}
952
	}
953
954
	/**
955
	 * Load language files
956
	 * @action plugins_loaded
957
	 */
958
	public static function plugin_textdomain() {
959
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
960
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
961
	}
962
963
	/**
964
	 * Register assets for use in various modules and the Jetpack admin page.
965
	 *
966
	 * @uses wp_script_is, wp_register_script, plugins_url
967
	 * @action wp_loaded
968
	 * @return null
969
	 */
970
	public function register_assets() {
971
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
972
			wp_register_script(
973
				'spin',
974
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
975
				false,
976
				'1.3'
977
			);
978
		}
979
980
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
981
			wp_register_script(
982
				'jquery.spin',
983
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
984
				array( 'jquery', 'spin' ),
985
				'1.3'
986
			);
987
		}
988
989 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
990
			wp_register_script(
991
				'jetpack-gallery-settings',
992
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
993
				array( 'media-views' ),
994
				'20121225'
995
			);
996
		}
997
998
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
999
			wp_register_script(
1000
				'jetpack-twitter-timeline',
1001
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1002
				array( 'jquery' ),
1003
				'4.0.0',
1004
				true
1005
			);
1006
		}
1007
1008
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1009
			wp_register_script(
1010
				'jetpack-facebook-embed',
1011
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1012
				array( 'jquery' ),
1013
				null,
1014
				true
1015
			);
1016
1017
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1018
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1019
			if ( ! is_numeric( $fb_app_id ) ) {
1020
				$fb_app_id = '';
1021
			}
1022
			wp_localize_script(
1023
				'jetpack-facebook-embed',
1024
				'jpfbembed',
1025
				array(
1026
					'appid' => $fb_app_id,
1027
					'locale' => $this->get_locale(),
1028
				)
1029
			);
1030
		}
1031
1032
		/**
1033
		 * As jetpack_register_genericons is by default fired off a hook,
1034
		 * the hook may have already fired by this point.
1035
		 * So, let's just trigger it manually.
1036
		 */
1037
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1038
		jetpack_register_genericons();
1039
1040
		/**
1041
		 * Register the social logos
1042
		 */
1043
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1044
		jetpack_register_social_logos();
1045
1046 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1047
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1048
	}
1049
1050
	/**
1051
	 * Guess locale from language code.
1052
	 *
1053
	 * @param string $lang Language code.
1054
	 * @return string|bool
1055
	 */
1056 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1057
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1058
			return 'en_US';
1059
		}
1060
1061
		if ( ! class_exists( 'GP_Locales' ) ) {
1062
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1063
				return false;
1064
			}
1065
1066
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1067
		}
1068
1069
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1070
			// WP.com: get_locale() returns 'it'
1071
			$locale = GP_Locales::by_slug( $lang );
1072
		} else {
1073
			// Jetpack: get_locale() returns 'it_IT';
1074
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1075
		}
1076
1077
		if ( ! $locale ) {
1078
			return false;
1079
		}
1080
1081
		if ( empty( $locale->facebook_locale ) ) {
1082
			if ( empty( $locale->wp_locale ) ) {
1083
				return false;
1084
			} else {
1085
				// Facebook SDK is smart enough to fall back to en_US if a
1086
				// locale isn't supported. Since supported Facebook locales
1087
				// can fall out of sync, we'll attempt to use the known
1088
				// wp_locale value and rely on said fallback.
1089
				return $locale->wp_locale;
1090
			}
1091
		}
1092
1093
		return $locale->facebook_locale;
1094
	}
1095
1096
	/**
1097
	 * Get the locale.
1098
	 *
1099
	 * @return string|bool
1100
	 */
1101
	function get_locale() {
1102
		$locale = $this->guess_locale_from_lang( get_locale() );
1103
1104
		if ( ! $locale ) {
1105
			$locale = 'en_US';
1106
		}
1107
1108
		return $locale;
1109
	}
1110
1111
	/**
1112
	 * Device Pixels support
1113
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1114
	 */
1115
	function devicepx() {
1116
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1117
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1118
		}
1119
	}
1120
1121
	/**
1122
	 * Return the network_site_url so that .com knows what network this site is a part of.
1123
	 * @param  bool $option
1124
	 * @return string
1125
	 */
1126
	public function jetpack_main_network_site_option( $option ) {
1127
		return network_site_url();
1128
	}
1129
	/**
1130
	 * Network Name.
1131
	 */
1132
	static function network_name( $option = null ) {
1133
		global $current_site;
1134
		return $current_site->site_name;
1135
	}
1136
	/**
1137
	 * Does the network allow new user and site registrations.
1138
	 * @return string
1139
	 */
1140
	static function network_allow_new_registrations( $option = null ) {
1141
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1142
	}
1143
	/**
1144
	 * Does the network allow admins to add new users.
1145
	 * @return boolian
1146
	 */
1147
	static function network_add_new_users( $option = null ) {
1148
		return (bool) get_site_option( 'add_new_users' );
1149
	}
1150
	/**
1151
	 * File upload psace left per site in MB.
1152
	 *  -1 means NO LIMIT.
1153
	 * @return number
1154
	 */
1155
	static function network_site_upload_space( $option = null ) {
1156
		// value in MB
1157
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1158
	}
1159
1160
	/**
1161
	 * Network allowed file types.
1162
	 * @return string
1163
	 */
1164
	static function network_upload_file_types( $option = null ) {
1165
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1166
	}
1167
1168
	/**
1169
	 * Maximum file upload size set by the network.
1170
	 * @return number
1171
	 */
1172
	static function network_max_upload_file_size( $option = null ) {
1173
		// value in KB
1174
		return get_site_option( 'fileupload_maxk', 300 );
1175
	}
1176
1177
	/**
1178
	 * Lets us know if a site allows admins to manage the network.
1179
	 * @return array
1180
	 */
1181
	static function network_enable_administration_menus( $option = null ) {
1182
		return get_site_option( 'menu_items' );
1183
	}
1184
1185
	/**
1186
	 * If a user has been promoted to or demoted from admin, we need to clear the
1187
	 * jetpack_other_linked_admins transient.
1188
	 *
1189
	 * @since 4.3.2
1190
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1191
	 *
1192
	 * @param int    $user_id   The user ID whose role changed.
1193
	 * @param string $role      The new role.
1194
	 * @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...
1195
	 */
1196
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1197
		if ( 'administrator' == $role
1198
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1199
			|| is_null( $old_roles )
1200
		) {
1201
			delete_transient( 'jetpack_other_linked_admins' );
1202
		}
1203
	}
1204
1205
	/**
1206
	 * Checks to see if there are any other users available to become primary
1207
	 * Users must both:
1208
	 * - Be linked to wpcom
1209
	 * - Be an admin
1210
	 *
1211
	 * @return mixed False if no other users are linked, Int if there are.
1212
	 */
1213
	static function get_other_linked_admins() {
1214
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1215
1216
		if ( false === $other_linked_users ) {
1217
			$admins = get_users( array( 'role' => 'administrator' ) );
1218
			if ( count( $admins ) > 1 ) {
1219
				$available = array();
1220
				foreach ( $admins as $admin ) {
1221
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1222
						$available[] = $admin->ID;
1223
					}
1224
				}
1225
1226
				$count_connected_admins = count( $available );
1227
				if ( count( $available ) > 1 ) {
1228
					$other_linked_users = $count_connected_admins;
1229
				} else {
1230
					$other_linked_users = 0;
1231
				}
1232
			} else {
1233
				$other_linked_users = 0;
1234
			}
1235
1236
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1237
		}
1238
1239
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1240
	}
1241
1242
	/**
1243
	 * Return whether we are dealing with a multi network setup or not.
1244
	 * The reason we are type casting this is because we want to avoid the situation where
1245
	 * the result is false since when is_main_network_option return false it cases
1246
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1247
	 * database which could be set to anything as opposed to what this function returns.
1248
	 * @param  bool  $option
1249
	 *
1250
	 * @return boolean
1251
	 */
1252
	public function is_main_network_option( $option ) {
1253
		// return '1' or ''
1254
		return (string) (bool) Jetpack::is_multi_network();
1255
	}
1256
1257
	/**
1258
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1259
	 *
1260
	 * @param  string  $option
1261
	 * @return boolean
1262
	 */
1263
	public function is_multisite( $option ) {
1264
		return (string) (bool) is_multisite();
1265
	}
1266
1267
	/**
1268
	 * Implemented since there is no core is multi network function
1269
	 * Right now there is no way to tell if we which network is the dominant network on the system
1270
	 *
1271
	 * @since  3.3
1272
	 * @return boolean
1273
	 */
1274
	public static function is_multi_network() {
1275
		global  $wpdb;
1276
1277
		// if we don't have a multi site setup no need to do any more
1278
		if ( ! is_multisite() ) {
1279
			return false;
1280
		}
1281
1282
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1283
		if ( $num_sites > 1 ) {
1284
			return true;
1285
		} else {
1286
			return false;
1287
		}
1288
	}
1289
1290
	/**
1291
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1292
	 * @return null
1293
	 */
1294
	function update_jetpack_main_network_site_option() {
1295
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1296
	}
1297
	/**
1298
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1299
	 *
1300
	 */
1301
	function update_jetpack_network_settings() {
1302
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1303
		// Only sync this info for the main network site.
1304
	}
1305
1306
	/**
1307
	 * Get back if the current site is single user site.
1308
	 *
1309
	 * @return bool
1310
	 */
1311
	public static function is_single_user_site() {
1312
		global $wpdb;
1313
1314 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1315
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1316
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1317
		}
1318
		return 1 === (int) $some_users;
1319
	}
1320
1321
	/**
1322
	 * Returns true if the site has file write access false otherwise.
1323
	 * @return string ( '1' | '0' )
1324
	 **/
1325
	public static function file_system_write_access() {
1326
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1327
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1328
		}
1329
1330
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1331
1332
		$filesystem_method = get_filesystem_method();
1333
		if ( $filesystem_method === 'direct' ) {
1334
			return 1;
1335
		}
1336
1337
		ob_start();
1338
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1339
		ob_end_clean();
1340
		if ( $filesystem_credentials_are_stored ) {
1341
			return 1;
1342
		}
1343
		return 0;
1344
	}
1345
1346
	/**
1347
	 * Finds out if a site is using a version control system.
1348
	 * @return string ( '1' | '0' )
1349
	 **/
1350
	public static function is_version_controlled() {
1351
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1352
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1353
	}
1354
1355
	/**
1356
	 * Determines whether the current theme supports featured images or not.
1357
	 * @return string ( '1' | '0' )
1358
	 */
1359
	public static function featured_images_enabled() {
1360
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1361
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1362
	}
1363
1364
	/**
1365
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1366
	 *
1367
	 * @deprecated 4.7 use get_avatar_url instead.
1368
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1369
	 * @param int $size Size of the avatar image
1370
	 * @param string $default URL to a default image to use if no avatar is available
1371
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1372
	 *
1373
	 * @return array
1374
	 */
1375
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1376
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1377
		return get_avatar_url( $id_or_email, array(
1378
			'size' => $size,
1379
			'default' => $default,
1380
			'force_default' => $force_display,
1381
		) );
1382
	}
1383
1384
	/**
1385
	 * jetpack_updates is saved in the following schema:
1386
	 *
1387
	 * array (
1388
	 *      'plugins'                       => (int) Number of plugin updates available.
1389
	 *      'themes'                        => (int) Number of theme updates available.
1390
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1391
	 *      'translations'                  => (int) Number of translation updates available.
1392
	 *      'total'                         => (int) Total of all available updates.
1393
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1394
	 * )
1395
	 * @return array
1396
	 */
1397
	public static function get_updates() {
1398
		$update_data = wp_get_update_data();
1399
1400
		// Stores the individual update counts as well as the total count.
1401
		if ( isset( $update_data['counts'] ) ) {
1402
			$updates = $update_data['counts'];
1403
		}
1404
1405
		// If we need to update WordPress core, let's find the latest version number.
1406 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1407
			$cur = get_preferred_from_update_core();
1408
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1409
				$updates['wp_update_version'] = $cur->current;
1410
			}
1411
		}
1412
		return isset( $updates ) ? $updates : array();
1413
	}
1414
1415
	public static function get_update_details() {
1416
		$update_details = array(
1417
			'update_core' => get_site_transient( 'update_core' ),
1418
			'update_plugins' => get_site_transient( 'update_plugins' ),
1419
			'update_themes' => get_site_transient( 'update_themes' ),
1420
		);
1421
		return $update_details;
1422
	}
1423
1424
	public static function refresh_update_data() {
1425
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1426
1427
	}
1428
1429
	public static function refresh_theme_data() {
1430
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1431
	}
1432
1433
	/**
1434
	 * Is Jetpack active?
1435
	 */
1436
	public static function is_active() {
1437
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1438
	}
1439
1440
	/**
1441
	 * Make an API call to WordPress.com for plan status
1442
	 *
1443
	 * @uses Jetpack_Options::get_option()
1444
	 * @uses Jetpack_Client::wpcom_json_api_request_as_blog()
1445
	 * @uses update_option()
1446
	 *
1447
	 * @access public
1448
	 * @static
1449
	 *
1450
	 * @return bool True if plan is updated, false if no update
1451
	 */
1452
	public static function refresh_active_plan_from_wpcom() {
1453
		// Make the API request
1454
		$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
1455
		$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
1456
1457
		// Bail if there was an error or malformed response
1458
		if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
1459
			return false;
1460
		}
1461
1462
		// Decode the results
1463
		$results = json_decode( $response['body'], true );
1464
1465
		// Bail if there were no results or plan details returned
1466
		if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
1467
			return false;
1468
		}
1469
1470
		// Store the option and return true if updated
1471
		return update_option( 'jetpack_active_plan', $results['plan'] );
1472
	}
1473
1474
	/**
1475
	 * Get the plan that this Jetpack site is currently using
1476
	 *
1477
	 * @uses get_option()
1478
	 *
1479
	 * @access public
1480
	 * @static
1481
	 *
1482
	 * @return array Active Jetpack plan details
1483
	 */
1484
	public static function get_active_plan() {
1485
		global $active_plan_cache;
1486
1487
		// this can be expensive to compute so we cache for the duration of a request
1488
		if ( is_array( $active_plan_cache ) && ! empty( $active_plan_cache ) ) {
1489
			return $active_plan_cache;
1490
		}
1491
1492
		$plan = get_option( 'jetpack_active_plan', array() );
1493
1494
		// Set the default options
1495
		$plan = wp_parse_args( $plan, array(
1496
			'product_slug' => 'jetpack_free',
1497
			'class'        => 'free',
1498
			'features'     => array(
1499
				'active' => array()
1500
			),
1501
		) );
1502
1503
		$supports = array();
1504
1505
		// Define what paid modules are supported by personal plans
1506
		$personal_plans = array(
1507
			'jetpack_personal',
1508
			'jetpack_personal_monthly',
1509
			'personal-bundle',
1510
			'personal-bundle-2y',
1511
		);
1512
1513
		if ( in_array( $plan['product_slug'], $personal_plans ) ) {
1514
			// special support value, not a module but a separate plugin
1515
			$supports[] = 'akismet';
1516
			$plan['class'] = 'personal';
1517
		}
1518
1519
		// Define what paid modules are supported by premium plans
1520
		$premium_plans = array(
1521
			'jetpack_premium',
1522
			'jetpack_premium_monthly',
1523
			'value_bundle',
1524
			'value_bundle-2y',
1525
		);
1526
1527 View Code Duplication
		if ( in_array( $plan['product_slug'], $premium_plans ) ) {
1528
			$supports[] = 'akismet';
1529
			$supports[] = 'simple-payments';
1530
			$supports[] = 'vaultpress';
1531
			$supports[] = 'videopress';
1532
			$plan['class'] = 'premium';
1533
		}
1534
1535
		// Define what paid modules are supported by professional plans
1536
		$business_plans = array(
1537
			'jetpack_business',
1538
			'jetpack_business_monthly',
1539
			'business-bundle',
1540
			'business-bundle-2y',
1541
			'vip',
1542
		);
1543
1544 View Code Duplication
		if ( in_array( $plan['product_slug'], $business_plans ) ) {
1545
			$supports[] = 'akismet';
1546
			$supports[] = 'simple-payments';
1547
			$supports[] = 'vaultpress';
1548
			$supports[] = 'videopress';
1549
			$plan['class'] = 'business';
1550
		}
1551
1552
		// get available features
1553
		foreach ( self::get_available_modules() as $module_slug ) {
1554
			$module = self::get_module( $module_slug );
1555
			if ( ! isset( $module ) || ! is_array( $module ) ) {
1556
				continue;
1557
			}
1558
			if ( in_array( 'free', $module['plan_classes'] ) || in_array( $plan['class'], $module['plan_classes'] ) ) {
1559
				$supports[] = $module_slug;
1560
			}
1561
		}
1562
1563
		$plan['supports'] = $supports;
1564
1565
		$active_plan_cache = $plan;
1566
1567
		return $plan;
1568
	}
1569
1570
	/**
1571
	 * Determine whether the active plan supports a particular feature
1572
	 *
1573
	 * @uses Jetpack::get_active_plan()
1574
	 *
1575
	 * @access public
1576
	 * @static
1577
	 *
1578
	 * @return bool True if plan supports feature, false if not
1579
	 */
1580
	public static function active_plan_supports( $feature ) {
1581
		$plan = Jetpack::get_active_plan();
1582
1583
		// Manually mapping WordPress.com features to Jetpack module slugs
1584
		foreach ( $plan['features']['active'] as $wpcom_feature ) {
1585
			switch ( $wpcom_feature ) {
1586
				case 'wordads-jetpack';
1587
1588
				// WordAds are supported for this site
1589
				if ( 'wordads' === $feature ) {
1590
					return true;
1591
				}
1592
				break;
1593
			}
1594
		}
1595
1596
		if (
1597
			in_array( $feature, $plan['supports'] )
1598
			|| in_array( $feature, $plan['features']['active'] )
1599
		) {
1600
			return true;
1601
		}
1602
1603
		return false;
1604
	}
1605
1606
	/**
1607
	 * Is Jetpack in development (offline) mode?
1608
	 */
1609
	public static function is_development_mode() {
1610
		$development_mode = false;
1611
1612
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1613
			$development_mode = JETPACK_DEV_DEBUG;
1614
		} elseif ( $site_url = site_url() ) {
1615
			$development_mode = false === strpos( $site_url, '.' );
1616
		}
1617
1618
		/**
1619
		 * Filters Jetpack's development mode.
1620
		 *
1621
		 * @see https://jetpack.com/support/development-mode/
1622
		 *
1623
		 * @since 2.2.1
1624
		 *
1625
		 * @param bool $development_mode Is Jetpack's development mode active.
1626
		 */
1627
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1628
		return $development_mode;
1629
	}
1630
1631
	/**
1632
	 * Whether the site is currently onboarding or not.
1633
	 * A site is considered as being onboarded if it currently has an onboarding token.
1634
	 *
1635
	 * @since 5.8
1636
	 *
1637
	 * @access public
1638
	 * @static
1639
	 *
1640
	 * @return bool True if the site is currently onboarding, false otherwise
1641
	 */
1642
	public static function is_onboarding() {
1643
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1644
	}
1645
1646
	/**
1647
	* Get Jetpack development mode notice text and notice class.
1648
	*
1649
	* Mirrors the checks made in Jetpack::is_development_mode
1650
	*
1651
	*/
1652
	public static function show_development_mode_notice() {
1653
		if ( Jetpack::is_development_mode() ) {
1654
			if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1655
				$notice = sprintf(
1656
					/* translators: %s is a URL */
1657
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
1658
					'https://jetpack.com/support/development-mode/'
1659
				);
1660
			} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1661
				$notice = sprintf(
1662
					/* translators: %s is a URL */
1663
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
1664
					'https://jetpack.com/support/development-mode/'
1665
				);
1666
			} else {
1667
				$notice = sprintf(
1668
					/* translators: %s is a URL */
1669
					__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
1670
					'https://jetpack.com/support/development-mode/'
1671
				);
1672
			}
1673
1674
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1675
		}
1676
1677
		// Throw up a notice if using a development version and as for feedback.
1678
		if ( Jetpack::is_development_version() ) {
1679
			/* translators: %s is a URL */
1680
			$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/' );
1681
1682
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1683
		}
1684
		// Throw up a notice if using staging mode
1685
		if ( Jetpack::is_staging_site() ) {
1686
			/* translators: %s is a URL */
1687
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1688
1689
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1690
		}
1691
	}
1692
1693
	/**
1694
	 * Whether Jetpack's version maps to a public release, or a development version.
1695
	 */
1696
	public static function is_development_version() {
1697
		/**
1698
		 * Allows filtering whether this is a development version of Jetpack.
1699
		 *
1700
		 * This filter is especially useful for tests.
1701
		 *
1702
		 * @since 4.3.0
1703
		 *
1704
		 * @param bool $development_version Is this a develoment version of Jetpack?
1705
		 */
1706
		return (bool) apply_filters(
1707
			'jetpack_development_version',
1708
			! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
1709
		);
1710
	}
1711
1712
	/**
1713
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1714
	 */
1715
	public static function is_user_connected( $user_id = false ) {
1716
		$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
1717
		if ( ! $user_id ) {
1718
			return false;
1719
		}
1720
1721
		return (bool) Jetpack_Data::get_access_token( $user_id );
1722
	}
1723
1724
	/**
1725
	 * Get the wpcom user data of the current|specified connected user.
1726
	 */
1727
	public static function get_connected_user_data( $user_id = null ) {
1728
		if ( ! $user_id ) {
1729
			$user_id = get_current_user_id();
1730
		}
1731
1732
		$transient_key = "jetpack_connected_user_data_$user_id";
1733
1734
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1735
			return $cached_user_data;
1736
		}
1737
1738
		Jetpack::load_xml_rpc_client();
1739
		$xml = new Jetpack_IXR_Client( array(
1740
			'user_id' => $user_id,
1741
		) );
1742
		$xml->query( 'wpcom.getUser' );
1743
		if ( ! $xml->isError() ) {
1744
			$user_data = $xml->getResponse();
1745
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1746
			return $user_data;
1747
		}
1748
1749
		return false;
1750
	}
1751
1752
	/**
1753
	 * Get the wpcom email of the current|specified connected user.
1754
	 */
1755 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1756
		if ( ! $user_id ) {
1757
			$user_id = get_current_user_id();
1758
		}
1759
		Jetpack::load_xml_rpc_client();
1760
		$xml = new Jetpack_IXR_Client( array(
1761
			'user_id' => $user_id,
1762
		) );
1763
		$xml->query( 'wpcom.getUserEmail' );
1764
		if ( ! $xml->isError() ) {
1765
			return $xml->getResponse();
1766
		}
1767
		return false;
1768
	}
1769
1770
	/**
1771
	 * Get the wpcom email of the master user.
1772
	 */
1773
	public static function get_master_user_email() {
1774
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1775
		if ( $master_user_id ) {
1776
			return self::get_connected_user_email( $master_user_id );
1777
		}
1778
		return '';
1779
	}
1780
1781
	function current_user_is_connection_owner() {
1782
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
1783
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1784
	}
1785
1786
	/**
1787
	 * Gets current user IP address.
1788
	 *
1789
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1790
	 *
1791
	 * @return string                  Current user IP address.
1792
	 */
1793
	public static function current_user_ip( $check_all_headers = false ) {
1794
		if ( $check_all_headers ) {
1795
			foreach ( array(
1796
				'HTTP_CF_CONNECTING_IP',
1797
				'HTTP_CLIENT_IP',
1798
				'HTTP_X_FORWARDED_FOR',
1799
				'HTTP_X_FORWARDED',
1800
				'HTTP_X_CLUSTER_CLIENT_IP',
1801
				'HTTP_FORWARDED_FOR',
1802
				'HTTP_FORWARDED',
1803
				'HTTP_VIA',
1804
			) as $key ) {
1805
				if ( ! empty( $_SERVER[ $key ] ) ) {
1806
					return $_SERVER[ $key ];
1807
				}
1808
			}
1809
		}
1810
1811
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1812
	}
1813
1814
	/**
1815
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1816
	 */
1817
	function extra_oembed_providers() {
1818
		// Cloudup: https://dev.cloudup.com/#oembed
1819
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1820
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1821
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1822
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1823
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1824
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1825
	}
1826
1827
	/**
1828
	 * Synchronize connected user role changes
1829
	 */
1830
	function user_role_change( $user_id ) {
1831
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1832
		Jetpack_Sync_Users::user_role_change( $user_id );
1833
	}
1834
1835
	/**
1836
	 * Loads the currently active modules.
1837
	 */
1838
	public static function load_modules() {
1839
		if (
1840
			! self::is_active()
1841
			&& ! self::is_development_mode()
1842
			&& ! self::is_onboarding()
1843
			&& (
1844
				! is_multisite()
1845
				|| ! get_site_option( 'jetpack_protect_active' )
1846
			)
1847
		) {
1848
			return;
1849
		}
1850
1851
		$version = Jetpack_Options::get_option( 'version' );
1852 View Code Duplication
		if ( ! $version ) {
1853
			$version = $old_version = JETPACK__VERSION . ':' . time();
1854
			/** This action is documented in class.jetpack.php */
1855
			do_action( 'updating_jetpack_version', $version, false );
1856
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1857
		}
1858
		list( $version ) = explode( ':', $version );
1859
1860
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1861
1862
		$modules_data = array();
1863
1864
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1865
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1866
			$updated_modules = array();
1867
			foreach ( $modules as $module ) {
1868
				$modules_data[ $module ] = Jetpack::get_module( $module );
1869
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1870
					continue;
1871
				}
1872
1873
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1874
					continue;
1875
				}
1876
1877
				$updated_modules[] = $module;
1878
			}
1879
1880
			$modules = array_diff( $modules, $updated_modules );
1881
		}
1882
1883
		$is_development_mode = Jetpack::is_development_mode();
1884
1885
		foreach ( $modules as $index => $module ) {
1886
			// If we're in dev mode, disable modules requiring a connection
1887
			if ( $is_development_mode ) {
1888
				// Prime the pump if we need to
1889
				if ( empty( $modules_data[ $module ] ) ) {
1890
					$modules_data[ $module ] = Jetpack::get_module( $module );
1891
				}
1892
				// If the module requires a connection, but we're in local mode, don't include it.
1893
				if ( $modules_data[ $module ]['requires_connection'] ) {
1894
					continue;
1895
				}
1896
			}
1897
1898
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1899
				continue;
1900
			}
1901
1902
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1903
				unset( $modules[ $index ] );
1904
				self::update_active_modules( array_values( $modules ) );
1905
				continue;
1906
			}
1907
1908
			/**
1909
			 * Fires when a specific module is loaded.
1910
			 * The dynamic part of the hook, $module, is the module slug.
1911
			 *
1912
			 * @since 1.1.0
1913
			 */
1914
			do_action( 'jetpack_module_loaded_' . $module );
1915
		}
1916
1917
		/**
1918
		 * Fires when all the modules are loaded.
1919
		 *
1920
		 * @since 1.1.0
1921
		 */
1922
		do_action( 'jetpack_modules_loaded' );
1923
1924
		// 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.
1925
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1926
	}
1927
1928
	/**
1929
	 * Check if Jetpack's REST API compat file should be included
1930
	 * @action plugins_loaded
1931
	 * @return null
1932
	 */
1933
	public function check_rest_api_compat() {
1934
		/**
1935
		 * Filters the list of REST API compat files to be included.
1936
		 *
1937
		 * @since 2.2.5
1938
		 *
1939
		 * @param array $args Array of REST API compat files to include.
1940
		 */
1941
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1942
1943
		if ( function_exists( 'bbpress' ) )
1944
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1945
1946
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1947
			require_once $_jetpack_rest_api_compat_include;
1948
	}
1949
1950
	/**
1951
	 * Gets all plugins currently active in values, regardless of whether they're
1952
	 * traditionally activated or network activated.
1953
	 *
1954
	 * @todo Store the result in core's object cache maybe?
1955
	 */
1956
	public static function get_active_plugins() {
1957
		$active_plugins = (array) get_option( 'active_plugins', array() );
1958
1959
		if ( is_multisite() ) {
1960
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1961
			// whereas active_plugins stores them in the values.
1962
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1963
			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...
1964
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1965
			}
1966
		}
1967
1968
		sort( $active_plugins );
1969
1970
		return array_unique( $active_plugins );
1971
	}
1972
1973
	/**
1974
	 * Gets and parses additional plugin data to send with the heartbeat data
1975
	 *
1976
	 * @since 3.8.1
1977
	 *
1978
	 * @return array Array of plugin data
1979
	 */
1980
	public static function get_parsed_plugin_data() {
1981
		if ( ! function_exists( 'get_plugins' ) ) {
1982
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1983
		}
1984
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1985
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1986
		$active_plugins = Jetpack::get_active_plugins();
1987
1988
		$plugins = array();
1989
		foreach ( $all_plugins as $path => $plugin_data ) {
1990
			$plugins[ $path ] = array(
1991
					'is_active' => in_array( $path, $active_plugins ),
1992
					'file'      => $path,
1993
					'name'      => $plugin_data['Name'],
1994
					'version'   => $plugin_data['Version'],
1995
					'author'    => $plugin_data['Author'],
1996
			);
1997
		}
1998
1999
		return $plugins;
2000
	}
2001
2002
	/**
2003
	 * Gets and parses theme data to send with the heartbeat data
2004
	 *
2005
	 * @since 3.8.1
2006
	 *
2007
	 * @return array Array of theme data
2008
	 */
2009
	public static function get_parsed_theme_data() {
2010
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
2011
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2012
2013
		$themes = array();
2014
		foreach ( $all_themes as $slug => $theme_data ) {
2015
			$theme_headers = array();
2016
			foreach ( $header_keys as $header_key ) {
2017
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2018
			}
2019
2020
			$themes[ $slug ] = array(
2021
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2022
					'slug' => $slug,
2023
					'theme_root' => $theme_data->get_theme_root_uri(),
2024
					'parent' => $theme_data->parent(),
2025
					'headers' => $theme_headers
2026
			);
2027
		}
2028
2029
		return $themes;
2030
	}
2031
2032
	/**
2033
	 * Checks whether a specific plugin is active.
2034
	 *
2035
	 * We don't want to store these in a static variable, in case
2036
	 * there are switch_to_blog() calls involved.
2037
	 */
2038
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2039
		return in_array( $plugin, self::get_active_plugins() );
2040
	}
2041
2042
	/**
2043
	 * Check if Jetpack's Open Graph tags should be used.
2044
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2045
	 *
2046
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2047
	 * @action plugins_loaded
2048
	 * @return null
2049
	 */
2050
	public function check_open_graph() {
2051
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2052
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2053
		}
2054
2055
		$active_plugins = self::get_active_plugins();
2056
2057
		if ( ! empty( $active_plugins ) ) {
2058
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2059
				if ( in_array( $plugin, $active_plugins ) ) {
2060
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2061
					break;
2062
				}
2063
			}
2064
		}
2065
2066
		/**
2067
		 * Allow the addition of Open Graph Meta Tags to all pages.
2068
		 *
2069
		 * @since 2.0.3
2070
		 *
2071
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2072
		 */
2073
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2074
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2075
		}
2076
	}
2077
2078
	/**
2079
	 * Check if Jetpack's Twitter tags should be used.
2080
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2081
	 *
2082
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2083
	 * @action plugins_loaded
2084
	 * @return null
2085
	 */
2086
	public function check_twitter_tags() {
2087
2088
		$active_plugins = self::get_active_plugins();
2089
2090
		if ( ! empty( $active_plugins ) ) {
2091
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2092
				if ( in_array( $plugin, $active_plugins ) ) {
2093
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2094
					break;
2095
				}
2096
			}
2097
		}
2098
2099
		/**
2100
		 * Allow Twitter Card Meta tags to be disabled.
2101
		 *
2102
		 * @since 2.6.0
2103
		 *
2104
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2105
		 */
2106
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2107
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2108
		}
2109
	}
2110
2111
	/**
2112
	 * Allows plugins to submit security reports.
2113
 	 *
2114
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2115
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2116
	 * @param array   $args         See definitions above
2117
	 */
2118
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2119
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2120
	}
2121
2122
/* Jetpack Options API */
2123
2124
	public static function get_option_names( $type = 'compact' ) {
2125
		return Jetpack_Options::get_option_names( $type );
2126
	}
2127
2128
	/**
2129
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2130
 	 *
2131
	 * @param string $name    Option name
2132
	 * @param mixed  $default (optional)
2133
	 */
2134
	public static function get_option( $name, $default = false ) {
2135
		return Jetpack_Options::get_option( $name, $default );
2136
	}
2137
2138
	/**
2139
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2140
 	 *
2141
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2142
	 * @param string $name  Option name
2143
	 * @param mixed  $value Option value
2144
	 */
2145
	public static function update_option( $name, $value ) {
2146
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2147
		return Jetpack_Options::update_option( $name, $value );
2148
	}
2149
2150
	/**
2151
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2152
 	 *
2153
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2154
	 * @param array $array array( option name => option value, ... )
2155
	 */
2156
	public static function update_options( $array ) {
2157
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2158
		return Jetpack_Options::update_options( $array );
2159
	}
2160
2161
	/**
2162
	 * Deletes the given option.  May be passed multiple option names as an array.
2163
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2164
	 *
2165
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2166
	 * @param string|array $names
2167
	 */
2168
	public static function delete_option( $names ) {
2169
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2170
		return Jetpack_Options::delete_option( $names );
2171
	}
2172
2173
	/**
2174
	 * Enters a user token into the user_tokens option
2175
	 *
2176
	 * @param int $user_id
2177
	 * @param string $token
2178
	 * return bool
2179
	 */
2180
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2181
		// not designed for concurrent updates
2182
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2183
		if ( ! is_array( $user_tokens ) )
2184
			$user_tokens = array();
2185
		$user_tokens[$user_id] = $token;
2186
		if ( $is_master_user ) {
2187
			$master_user = $user_id;
2188
			$options     = compact( 'user_tokens', 'master_user' );
2189
		} else {
2190
			$options = compact( 'user_tokens' );
2191
		}
2192
		return Jetpack_Options::update_options( $options );
2193
	}
2194
2195
	/**
2196
	 * Returns an array of all PHP files in the specified absolute path.
2197
	 * Equivalent to glob( "$absolute_path/*.php" ).
2198
	 *
2199
	 * @param string $absolute_path The absolute path of the directory to search.
2200
	 * @return array Array of absolute paths to the PHP files.
2201
	 */
2202
	public static function glob_php( $absolute_path ) {
2203
		if ( function_exists( 'glob' ) ) {
2204
			return glob( "$absolute_path/*.php" );
2205
		}
2206
2207
		$absolute_path = untrailingslashit( $absolute_path );
2208
		$files = array();
2209
		if ( ! $dir = @opendir( $absolute_path ) ) {
2210
			return $files;
2211
		}
2212
2213
		while ( false !== $file = readdir( $dir ) ) {
2214
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2215
				continue;
2216
			}
2217
2218
			$file = "$absolute_path/$file";
2219
2220
			if ( ! is_file( $file ) ) {
2221
				continue;
2222
			}
2223
2224
			$files[] = $file;
2225
		}
2226
2227
		closedir( $dir );
2228
2229
		return $files;
2230
	}
2231
2232
	public static function activate_new_modules( $redirect = false ) {
2233
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2234
			return;
2235
		}
2236
2237
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2238 View Code Duplication
		if ( ! $jetpack_old_version ) {
2239
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2240
			/** This action is documented in class.jetpack.php */
2241
			do_action( 'updating_jetpack_version', $version, false );
2242
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2243
		}
2244
2245
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2246
2247
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2248
			return;
2249
		}
2250
2251
		$active_modules     = Jetpack::get_active_modules();
2252
		$reactivate_modules = array();
2253
		foreach ( $active_modules as $active_module ) {
2254
			$module = Jetpack::get_module( $active_module );
2255
			if ( ! isset( $module['changed'] ) ) {
2256
				continue;
2257
			}
2258
2259
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2260
				continue;
2261
			}
2262
2263
			$reactivate_modules[] = $active_module;
2264
			Jetpack::deactivate_module( $active_module );
2265
		}
2266
2267
		$new_version = JETPACK__VERSION . ':' . time();
2268
		/** This action is documented in class.jetpack.php */
2269
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2270
		Jetpack_Options::update_options(
2271
			array(
2272
				'version'     => $new_version,
2273
				'old_version' => $jetpack_old_version,
2274
			)
2275
		);
2276
2277
		Jetpack::state( 'message', 'modules_activated' );
2278
		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...
2279
2280
		if ( $redirect ) {
2281
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2282
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2283
				$page = $_GET['page'];
2284
			}
2285
2286
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2287
			exit;
2288
		}
2289
	}
2290
2291
	/**
2292
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2293
	 * Make sure to tuck away module "library" files in a sub-directory.
2294
	 */
2295
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2296
		static $modules = null;
2297
2298
		if ( ! isset( $modules ) ) {
2299
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2300
			// Use the cache if we're on the front-end and it's available...
2301
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2302
				$modules = $available_modules_option[ JETPACK__VERSION ];
2303
			} else {
2304
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2305
2306
				$modules = array();
2307
2308
				foreach ( $files as $file ) {
2309
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2310
						continue;
2311
					}
2312
2313
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2314
				}
2315
2316
				Jetpack_Options::update_option( 'available_modules', array(
2317
					JETPACK__VERSION => $modules,
2318
				) );
2319
			}
2320
		}
2321
2322
		/**
2323
		 * Filters the array of modules available to be activated.
2324
		 *
2325
		 * @since 2.4.0
2326
		 *
2327
		 * @param array $modules Array of available modules.
2328
		 * @param string $min_version Minimum version number required to use modules.
2329
		 * @param string $max_version Maximum version number required to use modules.
2330
		 */
2331
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2332
2333
		if ( ! $min_version && ! $max_version ) {
2334
			return array_keys( $mods );
2335
		}
2336
2337
		$r = array();
2338
		foreach ( $mods as $slug => $introduced ) {
2339
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2340
				continue;
2341
			}
2342
2343
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2344
				continue;
2345
			}
2346
2347
			$r[] = $slug;
2348
		}
2349
2350
		return $r;
2351
	}
2352
2353
	/**
2354
	 * Default modules loaded on activation.
2355
	 */
2356
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2357
		$return = array();
2358
2359
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2360
			$module_data = Jetpack::get_module( $module );
2361
2362
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2363
				case 'yes' :
2364
					$return[] = $module;
2365
					break;
2366
				case 'public' :
2367
					if ( Jetpack_Options::get_option( 'public' ) ) {
2368
						$return[] = $module;
2369
					}
2370
					break;
2371
				case 'no' :
2372
				default :
2373
					break;
2374
			}
2375
		}
2376
		/**
2377
		 * Filters the array of default modules.
2378
		 *
2379
		 * @since 2.5.0
2380
		 *
2381
		 * @param array $return Array of default modules.
2382
		 * @param string $min_version Minimum version number required to use modules.
2383
		 * @param string $max_version Maximum version number required to use modules.
2384
		 */
2385
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2386
	}
2387
2388
	/**
2389
	 * Checks activated modules during auto-activation to determine
2390
	 * if any of those modules are being deprecated.  If so, close
2391
	 * them out, and add any replacement modules.
2392
	 *
2393
	 * Runs at priority 99 by default.
2394
	 *
2395
	 * This is run late, so that it can still activate a module if
2396
	 * the new module is a replacement for another that the user
2397
	 * currently has active, even if something at the normal priority
2398
	 * would kibosh everything.
2399
	 *
2400
	 * @since 2.6
2401
	 * @uses jetpack_get_default_modules filter
2402
	 * @param array $modules
2403
	 * @return array
2404
	 */
2405
	function handle_deprecated_modules( $modules ) {
2406
		$deprecated_modules = array(
2407
			'debug'            => null,  // Closed out and moved to ./class.jetpack-debugger.php
2408
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2409
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2410
		);
2411
2412
		// Don't activate SSO if they never completed activating WPCC.
2413
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2414
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2415
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2416
				$deprecated_modules['wpcc'] = null;
2417
			}
2418
		}
2419
2420
		foreach ( $deprecated_modules as $module => $replacement ) {
2421
			if ( Jetpack::is_module_active( $module ) ) {
2422
				self::deactivate_module( $module );
2423
				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...
2424
					$modules[] = $replacement;
2425
				}
2426
			}
2427
		}
2428
2429
		return array_unique( $modules );
2430
	}
2431
2432
	/**
2433
	 * Checks activated plugins during auto-activation to determine
2434
	 * if any of those plugins are in the list with a corresponding module
2435
	 * that is not compatible with the plugin. The module will not be allowed
2436
	 * to auto-activate.
2437
	 *
2438
	 * @since 2.6
2439
	 * @uses jetpack_get_default_modules filter
2440
	 * @param array $modules
2441
	 * @return array
2442
	 */
2443
	function filter_default_modules( $modules ) {
2444
2445
		$active_plugins = self::get_active_plugins();
2446
2447
		if ( ! empty( $active_plugins ) ) {
2448
2449
			// For each module we'd like to auto-activate...
2450
			foreach ( $modules as $key => $module ) {
2451
				// If there are potential conflicts for it...
2452
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2453
					// For each potential conflict...
2454
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2455
						// If that conflicting plugin is active...
2456
						if ( in_array( $plugin, $active_plugins ) ) {
2457
							// Remove that item from being auto-activated.
2458
							unset( $modules[ $key ] );
2459
						}
2460
					}
2461
				}
2462
			}
2463
		}
2464
2465
		return $modules;
2466
	}
2467
2468
	/**
2469
	 * Extract a module's slug from its full path.
2470
	 */
2471
	public static function get_module_slug( $file ) {
2472
		return str_replace( '.php', '', basename( $file ) );
2473
	}
2474
2475
	/**
2476
	 * Generate a module's path from its slug.
2477
	 */
2478
	public static function get_module_path( $slug ) {
2479
		return JETPACK__PLUGIN_DIR . "modules/$slug.php";
2480
	}
2481
2482
	/**
2483
	 * Load module data from module file. Headers differ from WordPress
2484
	 * plugin headers to avoid them being identified as standalone
2485
	 * plugins on the WordPress plugins page.
2486
	 */
2487
	public static function get_module( $module ) {
2488
		$headers = array(
2489
			'name'                      => 'Module Name',
2490
			'description'               => 'Module Description',
2491
			'jumpstart_desc'            => 'Jumpstart Description',
2492
			'sort'                      => 'Sort Order',
2493
			'recommendation_order'      => 'Recommendation Order',
2494
			'introduced'                => 'First Introduced',
2495
			'changed'                   => 'Major Changes In',
2496
			'deactivate'                => 'Deactivate',
2497
			'free'                      => 'Free',
2498
			'requires_connection'       => 'Requires Connection',
2499
			'auto_activate'             => 'Auto Activate',
2500
			'module_tags'               => 'Module Tags',
2501
			'feature'                   => 'Feature',
2502
			'additional_search_queries' => 'Additional Search Queries',
2503
			'plan_classes'              => 'Plans',
2504
		);
2505
2506
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2507
2508
		$mod = Jetpack::get_file_data( $file, $headers );
2509
		if ( empty( $mod['name'] ) ) {
2510
			return false;
2511
		}
2512
2513
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2514
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2515
		$mod['deactivate']              = empty( $mod['deactivate'] );
2516
		$mod['free']                    = empty( $mod['free'] );
2517
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2518
2519
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2520
			$mod['auto_activate'] = 'No';
2521
		} else {
2522
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2523
		}
2524
2525
		if ( $mod['module_tags'] ) {
2526
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2527
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2528
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2529
		} else {
2530
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2531
		}
2532
2533 View Code Duplication
		if ( $mod['plan_classes'] ) {
2534
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2535
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2536
		} else {
2537
			$mod['plan_classes'] = array( 'free' );
2538
		}
2539
2540 View Code Duplication
		if ( $mod['feature'] ) {
2541
			$mod['feature'] = explode( ',', $mod['feature'] );
2542
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2543
		} else {
2544
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2545
		}
2546
2547
		/**
2548
		 * Filters the feature array on a module.
2549
		 *
2550
		 * This filter allows you to control where each module is filtered: Recommended,
2551
		 * Jumpstart, and the default "Other" listing.
2552
		 *
2553
		 * @since 3.5.0
2554
		 *
2555
		 * @param array   $mod['feature'] The areas to feature this module:
2556
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2557
		 *     'Recommended' shows on the main Jetpack admin screen.
2558
		 *     'Other' should be the default if no other value is in the array.
2559
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2560
		 * @param array   $mod All the currently assembled module data.
2561
		 */
2562
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2563
2564
		/**
2565
		 * Filter the returned data about a module.
2566
		 *
2567
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2568
		 * so please be careful.
2569
		 *
2570
		 * @since 3.6.0
2571
		 *
2572
		 * @param array   $mod    The details of the requested module.
2573
		 * @param string  $module The slug of the module, e.g. sharedaddy
2574
		 * @param string  $file   The path to the module source file.
2575
		 */
2576
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2577
	}
2578
2579
	/**
2580
	 * Like core's get_file_data implementation, but caches the result.
2581
	 */
2582
	public static function get_file_data( $file, $headers ) {
2583
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2584
		$file_name = basename( $file );
2585
2586
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2587
2588
		$file_data_option = get_transient( $cache_key );
2589
2590
		if ( false === $file_data_option ) {
2591
			$file_data_option = array();
2592
		}
2593
2594
		$key           = md5( $file_name . serialize( $headers ) );
2595
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2596
2597
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2598
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2599
			return $file_data_option[ $key ];
2600
		}
2601
2602
		$data = get_file_data( $file, $headers );
2603
2604
		$file_data_option[ $key ] = $data;
2605
2606
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2607
2608
		return $data;
2609
	}
2610
2611
2612
	/**
2613
	 * Return translated module tag.
2614
	 *
2615
	 * @param string $tag Tag as it appears in each module heading.
2616
	 *
2617
	 * @return mixed
2618
	 */
2619
	public static function translate_module_tag( $tag ) {
2620
		return jetpack_get_module_i18n_tag( $tag );
2621
	}
2622
2623
	/**
2624
	 * Get i18n strings as a JSON-encoded string
2625
	 *
2626
	 * @return string The locale as JSON
2627
	 */
2628
	public static function get_i18n_data_json() {
2629
		$i18n_json = JETPACK__PLUGIN_DIR . 'languages/json/jetpack-' . get_user_locale() . '.json';
2630
2631
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2632
			$locale_data = @file_get_contents( $i18n_json );
2633
			if ( $locale_data ) {
2634
				return $locale_data;
2635
			}
2636
		}
2637
2638
		// Return valid empty Jed locale
2639
		return json_encode( array(
2640
			'' => array(
2641
				'domain' => 'jetpack',
2642
				'lang'   => is_admin() ? get_user_locale() : get_locale(),
2643
			),
2644
		) );
2645
	}
2646
2647
	/**
2648
	 * Add locale data setup to wp-i18n
2649
	 *
2650
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2651
	 *
2652
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2653
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2654
	 *
2655
	 * This method provides a safe way to request the setup multiple times but add the script at
2656
	 * most once.
2657
	 *
2658
	 * @since 6.7.0
2659
	 *
2660
	 * @return void
2661
	 */
2662
	public static function setup_wp_i18n_locale_data() {
2663
		static $script_added = false;
2664
		if ( ! $script_added ) {
2665
			$script_added = true;
2666
			wp_add_inline_script(
2667
				'wp-i18n',
2668
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2669
			);
2670
		}
2671
	}
2672
2673
	/**
2674
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2675
	 *
2676
	 * @since 3.9.2
2677
	 *
2678
	 * @param array $modules
2679
	 *
2680
	 * @return string|void
2681
	 */
2682
	public static function get_translated_modules( $modules ) {
2683
		foreach ( $modules as $index => $module ) {
2684
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2685
			if ( isset( $module['name'] ) ) {
2686
				$modules[ $index ]['name'] = $i18n_module['name'];
2687
			}
2688
			if ( isset( $module['description'] ) ) {
2689
				$modules[ $index ]['description'] = $i18n_module['description'];
2690
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2691
			}
2692
		}
2693
		return $modules;
2694
	}
2695
2696
	/**
2697
	 * Get a list of activated modules as an array of module slugs.
2698
	 */
2699
	public static function get_active_modules() {
2700
		$active = Jetpack_Options::get_option( 'active_modules' );
2701
2702
		if ( ! is_array( $active ) ) {
2703
			$active = array();
2704
		}
2705
2706
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2707
			$active[] = 'vaultpress';
2708
		} else {
2709
			$active = array_diff( $active, array( 'vaultpress' ) );
2710
		}
2711
2712
		//If protect is active on the main site of a multisite, it should be active on all sites.
2713
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2714
			$active[] = 'protect';
2715
		}
2716
2717
		/**
2718
		 * Allow filtering of the active modules.
2719
		 *
2720
		 * Gives theme and plugin developers the power to alter the modules that
2721
		 * are activated on the fly.
2722
		 *
2723
		 * @since 5.8.0
2724
		 *
2725
		 * @param array $active Array of active module slugs.
2726
		 */
2727
		$active = apply_filters( 'jetpack_active_modules', $active );
2728
2729
		return array_unique( $active );
2730
	}
2731
2732
	/**
2733
	 * Check whether or not a Jetpack module is active.
2734
	 *
2735
	 * @param string $module The slug of a Jetpack module.
2736
	 * @return bool
2737
	 *
2738
	 * @static
2739
	 */
2740
	public static function is_module_active( $module ) {
2741
		return in_array( $module, self::get_active_modules() );
2742
	}
2743
2744
	public static function is_module( $module ) {
2745
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2746
	}
2747
2748
	/**
2749
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2750
	 *
2751
	 * @param bool $catch True to start catching, False to stop.
2752
	 *
2753
	 * @static
2754
	 */
2755
	public static function catch_errors( $catch ) {
2756
		static $display_errors, $error_reporting;
2757
2758
		if ( $catch ) {
2759
			$display_errors  = @ini_set( 'display_errors', 1 );
2760
			$error_reporting = @error_reporting( E_ALL );
2761
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2762
		} else {
2763
			@ini_set( 'display_errors', $display_errors );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2764
			@error_reporting( $error_reporting );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
2765
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2766
		}
2767
	}
2768
2769
	/**
2770
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2771
	 */
2772
	public static function catch_errors_on_shutdown() {
2773
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2774
	}
2775
2776
	/**
2777
	 * Rewrite any string to make paths easier to read.
2778
	 *
2779
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2780
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2781
	 *
2782
	 * @param $string
2783
	 * @return mixed
2784
	 */
2785
	public static function alias_directories( $string ) {
2786
		// ABSPATH has a trailing slash.
2787
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2788
		// WP_CONTENT_DIR does not have a trailing slash.
2789
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2790
2791
		return $string;
2792
	}
2793
2794
	public static function activate_default_modules(
2795
		$min_version = false,
2796
		$max_version = false,
2797
		$other_modules = array(),
2798
		$redirect = true,
2799
		$send_state_messages = true
2800
	) {
2801
		$jetpack = Jetpack::init();
2802
2803
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2804
		$modules = array_merge( $other_modules, $modules );
2805
2806
		// Look for standalone plugins and disable if active.
2807
2808
		$to_deactivate = array();
2809
		foreach ( $modules as $module ) {
2810
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2811
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2812
			}
2813
		}
2814
2815
		$deactivated = array();
2816
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2817
			list( $probable_file, $probable_title ) = $deactivate_me;
2818
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2819
				$deactivated[] = $module;
2820
			}
2821
		}
2822
2823
		if ( $deactivated && $redirect ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $deactivated of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2824
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2825
2826
			$url = add_query_arg(
2827
				array(
2828
					'action'   => 'activate_default_modules',
2829
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2830
				),
2831
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2832
			);
2833
			wp_safe_redirect( $url );
2834
			exit;
2835
		}
2836
2837
		/**
2838
		 * Fires before default modules are activated.
2839
		 *
2840
		 * @since 1.9.0
2841
		 *
2842
		 * @param string $min_version Minimum version number required to use modules.
2843
		 * @param string $max_version Maximum version number required to use modules.
2844
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2845
		 */
2846
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2847
2848
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2849
		if ( $send_state_messages ) {
2850
			Jetpack::restate();
2851
			Jetpack::catch_errors( true );
2852
		}
2853
2854
		$active = Jetpack::get_active_modules();
2855
2856
		foreach ( $modules as $module ) {
2857
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2858
				$active[] = $module;
2859
				self::update_active_modules( $active );
2860
				continue;
2861
			}
2862
2863
			if ( $send_state_messages && in_array( $module, $active ) ) {
2864
				$module_info = Jetpack::get_module( $module );
2865 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2866
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2867
					if ( $active_state = Jetpack::state( $state ) ) {
2868
						$active_state = explode( ',', $active_state );
2869
					} else {
2870
						$active_state = array();
2871
					}
2872
					$active_state[] = $module;
2873
					Jetpack::state( $state, implode( ',', $active_state ) );
2874
				}
2875
				continue;
2876
			}
2877
2878
			$file = Jetpack::get_module_path( $module );
2879
			if ( ! file_exists( $file ) ) {
2880
				continue;
2881
			}
2882
2883
			// we'll override this later if the plugin can be included without fatal error
2884
			if ( $redirect ) {
2885
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2886
			}
2887
2888
			if ( $send_state_messages ) {
2889
				Jetpack::state( 'error', 'module_activation_failed' );
2890
				Jetpack::state( 'module', $module );
2891
			}
2892
2893
			ob_start();
2894
			require_once $file;
2895
2896
			$active[] = $module;
2897
2898 View Code Duplication
			if ( $send_state_messages ) {
2899
2900
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2901
				if ( $active_state = Jetpack::state( $state ) ) {
2902
					$active_state = explode( ',', $active_state );
2903
				} else {
2904
					$active_state = array();
2905
				}
2906
				$active_state[] = $module;
2907
				Jetpack::state( $state, implode( ',', $active_state ) );
2908
			}
2909
2910
			Jetpack::update_active_modules( $active );
2911
2912
			ob_end_clean();
2913
		}
2914
2915
		if ( $send_state_messages ) {
2916
			Jetpack::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3009
		ob_end_clean();
3010
		Jetpack::catch_errors( false );
3011
3012
		// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
3013 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
3014
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
3015
3016
			//Jump start is being dismissed send data to MC Stats
3017
			$jetpack->stat( 'jumpstart', 'manual,'.$module );
3018
3019
			$jetpack->do_stats( 'server_side' );
3020
		}
3021
3022
		if ( $redirect ) {
3023
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3024
		}
3025
		if ( $exit ) {
3026
			exit;
3027
		}
3028
		return true;
3029
	}
3030
3031
	function activate_module_actions( $module ) {
3032
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3033
	}
3034
3035
	public static function deactivate_module( $module ) {
3036
		/**
3037
		 * Fires when a module is deactivated.
3038
		 *
3039
		 * @since 1.9.0
3040
		 *
3041
		 * @param string $module Module slug.
3042
		 */
3043
		do_action( 'jetpack_pre_deactivate_module', $module );
3044
3045
		$jetpack = Jetpack::init();
3046
3047
		$active = Jetpack::get_active_modules();
3048
		$new    = array_filter( array_diff( $active, (array) $module ) );
3049
3050
		// A flag for Jump Start so it's not shown again.
3051 View Code Duplication
		if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
3052
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
3053
3054
			//Jump start is being dismissed send data to MC Stats
3055
			$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
3056
3057
			$jetpack->do_stats( 'server_side' );
3058
		}
3059
3060
		return self::update_active_modules( $new );
3061
	}
3062
3063
	public static function enable_module_configurable( $module ) {
3064
		$module = Jetpack::get_module_slug( $module );
3065
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3066
	}
3067
3068
	public static function module_configuration_url( $module ) {
3069
		$module = Jetpack::get_module_slug( $module );
3070
		return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
3071
	}
3072
3073
	public static function module_configuration_load( $module, $method ) {
3074
		$module = Jetpack::get_module_slug( $module );
3075
		add_action( 'jetpack_module_configuration_load_' . $module, $method );
3076
	}
3077
3078
	public static function module_configuration_head( $module, $method ) {
3079
		$module = Jetpack::get_module_slug( $module );
3080
		add_action( 'jetpack_module_configuration_head_' . $module, $method );
3081
	}
3082
3083
	public static function module_configuration_screen( $module, $method ) {
3084
		$module = Jetpack::get_module_slug( $module );
3085
		add_action( 'jetpack_module_configuration_screen_' . $module, $method );
3086
	}
3087
3088
	public static function module_configuration_activation_screen( $module, $method ) {
3089
		$module = Jetpack::get_module_slug( $module );
3090
		add_action( 'display_activate_module_setting_' . $module, $method );
3091
	}
3092
3093
/* Installation */
3094
3095
	public static function bail_on_activation( $message, $deactivate = true ) {
3096
?>
3097
<!doctype html>
3098
<html>
3099
<head>
3100
<meta charset="<?php bloginfo( 'charset' ); ?>">
3101
<style>
3102
* {
3103
	text-align: center;
3104
	margin: 0;
3105
	padding: 0;
3106
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3107
}
3108
p {
3109
	margin-top: 1em;
3110
	font-size: 18px;
3111
}
3112
</style>
3113
<body>
3114
<p><?php echo esc_html( $message ); ?></p>
3115
</body>
3116
</html>
3117
<?php
3118
		if ( $deactivate ) {
3119
			$plugins = get_option( 'active_plugins' );
3120
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3121
			$update  = false;
3122
			foreach ( $plugins as $i => $plugin ) {
3123
				if ( $plugin === $jetpack ) {
3124
					$plugins[$i] = false;
3125
					$update = true;
3126
				}
3127
			}
3128
3129
			if ( $update ) {
3130
				update_option( 'active_plugins', array_filter( $plugins ) );
3131
			}
3132
		}
3133
		exit;
3134
	}
3135
3136
	/**
3137
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3138
	 * @static
3139
	 */
3140
	public static function plugin_activation( $network_wide ) {
3141
		Jetpack_Options::update_option( 'activated', 1 );
3142
3143
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3144
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3145
		}
3146
3147
		if ( $network_wide )
3148
			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...
3149
3150
		// For firing one-off events (notices) immediately after activation
3151
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3152
3153
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3154
3155
		Jetpack::plugin_initialize();
3156
	}
3157
3158
	public static function get_activation_source( $referer_url ) {
3159
3160
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3161
			return array( 'wp-cli', null );
3162
		}
3163
3164
		$referer = parse_url( $referer_url );
3165
3166
		$source_type = 'unknown';
3167
		$source_query = null;
3168
3169
		if ( ! is_array( $referer ) ) {
3170
			return array( $source_type, $source_query );
3171
		}
3172
3173
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3174
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3175
3176
		if ( isset( $referer['query'] ) ) {
3177
			parse_str( $referer['query'], $query_parts );
3178
		} else {
3179
			$query_parts = array();
3180
		}
3181
3182
		if ( $plugins_path === $referer['path'] ) {
3183
			$source_type = 'list';
3184
		} elseif ( $plugins_install_path === $referer['path'] ) {
3185
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3186
			switch( $tab ) {
3187
				case 'popular':
3188
					$source_type = 'popular';
3189
					break;
3190
				case 'recommended':
3191
					$source_type = 'recommended';
3192
					break;
3193
				case 'favorites':
3194
					$source_type = 'favorites';
3195
					break;
3196
				case 'search':
3197
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3198
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3199
					break;
3200
				default:
3201
					$source_type = 'featured';
3202
			}
3203
		}
3204
3205
		return array( $source_type, $source_query );
3206
	}
3207
3208
	/**
3209
	 * Runs before bumping version numbers up to a new version
3210
	 * @param  string $version    Version:timestamp
3211
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3212
	 * @return null              [description]
3213
	 */
3214
	public static function do_version_bump( $version, $old_version ) {
3215
3216
		if ( ! $old_version ) { // For new sites
3217
			// Setting up jetpack manage
3218
			Jetpack::activate_manage();
3219
		}
3220
	}
3221
3222
	/**
3223
	 * Sets the internal version number and activation state.
3224
	 * @static
3225
	 */
3226
	public static function plugin_initialize() {
3227
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3228
			Jetpack_Options::update_option( 'activated', 2 );
3229
		}
3230
3231 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3232
			$version = $old_version = JETPACK__VERSION . ':' . time();
3233
			/** This action is documented in class.jetpack.php */
3234
			do_action( 'updating_jetpack_version', $version, false );
3235
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3236
		}
3237
3238
		Jetpack::load_modules();
3239
3240
		Jetpack_Options::delete_option( 'do_activate' );
3241
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3242
	}
3243
3244
	/**
3245
	 * Removes all connection options
3246
	 * @static
3247
	 */
3248
	public static function plugin_deactivation( ) {
3249
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3250
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3251
			Jetpack_Network::init()->deactivate();
3252
		} else {
3253
			Jetpack::disconnect( false );
3254
			//Jetpack_Heartbeat::init()->deactivate();
3255
		}
3256
	}
3257
3258
	/**
3259
	 * Disconnects from the Jetpack servers.
3260
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3261
	 * @static
3262
	 */
3263
	public static function disconnect( $update_activated_state = true ) {
3264
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3265
		Jetpack::clean_nonces( true );
3266
3267
		// If the site is in an IDC because sync is not allowed,
3268
		// let's make sure to not disconnect the production site.
3269
		if ( ! self::validate_sync_error_idc_option() ) {
3270
			JetpackTracking::record_user_event( 'disconnect_site', array() );
3271
			Jetpack::load_xml_rpc_client();
3272
			$xml = new Jetpack_IXR_Client();
3273
			$xml->query( 'jetpack.deregister' );
3274
		}
3275
3276
		Jetpack_Options::delete_option(
3277
			array(
3278
				'blog_token',
3279
				'user_token',
3280
				'user_tokens',
3281
				'master_user',
3282
				'time_diff',
3283
				'fallback_no_verify_ssl_certs',
3284
			)
3285
		);
3286
3287
		Jetpack_IDC::clear_all_idc_options();
3288
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3289
3290
		if ( $update_activated_state ) {
3291
			Jetpack_Options::update_option( 'activated', 4 );
3292
		}
3293
3294
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3295
			// Check then record unique disconnection if site has never been disconnected previously
3296
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3297
				$jetpack_unique_connection['disconnected'] = 1;
3298
			} else {
3299
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3300
					//track unique disconnect
3301
					$jetpack = Jetpack::init();
3302
3303
					$jetpack->stat( 'connections', 'unique-disconnect' );
3304
					$jetpack->do_stats( 'server_side' );
3305
				}
3306
				// increment number of times disconnected
3307
				$jetpack_unique_connection['disconnected'] += 1;
3308
			}
3309
3310
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3311
		}
3312
3313
		// Delete cached connected user data
3314
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3315
		delete_transient( $transient_key );
3316
3317
		// Delete all the sync related data. Since it could be taking up space.
3318
		require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-sender.php';
3319
		Jetpack_Sync_Sender::get_instance()->uninstall();
3320
3321
		// Disable the Heartbeat cron
3322
		Jetpack_Heartbeat::init()->deactivate();
3323
	}
3324
3325
	/**
3326
	 * Unlinks the current user from the linked WordPress.com user
3327
	 */
3328
	public static function unlink_user( $user_id = null ) {
3329
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3330
			return false;
3331
3332
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3333
3334
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3335
			return false;
3336
3337
		if ( ! isset( $tokens[ $user_id ] ) )
3338
			return false;
3339
3340
		Jetpack::load_xml_rpc_client();
3341
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3342
		$xml->query( 'jetpack.unlink_user', $user_id );
3343
3344
		unset( $tokens[ $user_id ] );
3345
3346
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3347
3348
		/**
3349
		 * Fires after the current user has been unlinked from WordPress.com.
3350
		 *
3351
		 * @since 4.1.0
3352
		 *
3353
		 * @param int $user_id The current user's ID.
3354
		 */
3355
		do_action( 'jetpack_unlinked_user', $user_id );
3356
3357
		return true;
3358
	}
3359
3360
	/**
3361
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3362
	 */
3363
	public static function try_registration() {
3364
		// The user has agreed to the TOS at some point by now.
3365
		Jetpack_Options::update_option( 'tos_agreed', true );
3366
3367
		// Let's get some testing in beta versions and such.
3368
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3369
			// Before attempting to connect, let's make sure that the domains are viable.
3370
			$domains_to_check = array_unique( array(
3371
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3372
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3373
			) );
3374
			foreach ( $domains_to_check as $domain ) {
3375
				$result = Jetpack_Data::is_usable_domain( $domain );
3376
				if ( is_wp_error( $result ) ) {
3377
					return $result;
3378
				}
3379
			}
3380
		}
3381
3382
		$result = Jetpack::register();
3383
3384
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3385
		if ( ! $result || is_wp_error( $result ) ) {
3386
			return $result;
3387
		} else {
3388
			return true;
3389
		}
3390
	}
3391
3392
	/**
3393
	 * Tracking an internal event log. Try not to put too much chaff in here.
3394
	 *
3395
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3396
	 */
3397
	public static function log( $code, $data = null ) {
3398
		// only grab the latest 200 entries
3399
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3400
3401
		// Append our event to the log
3402
		$log_entry = array(
3403
			'time'    => time(),
3404
			'user_id' => get_current_user_id(),
3405
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3406
			'code'    => $code,
3407
		);
3408
		// Don't bother storing it unless we've got some.
3409
		if ( ! is_null( $data ) ) {
3410
			$log_entry['data'] = $data;
3411
		}
3412
		$log[] = $log_entry;
3413
3414
		// Try add_option first, to make sure it's not autoloaded.
3415
		// @todo: Add an add_option method to Jetpack_Options
3416
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3417
			Jetpack_Options::update_option( 'log', $log );
3418
		}
3419
3420
		/**
3421
		 * Fires when Jetpack logs an internal event.
3422
		 *
3423
		 * @since 3.0.0
3424
		 *
3425
		 * @param array $log_entry {
3426
		 *	Array of details about the log entry.
3427
		 *
3428
		 *	@param string time Time of the event.
3429
		 *	@param int user_id ID of the user who trigerred the event.
3430
		 *	@param int blog_id Jetpack Blog ID.
3431
		 *	@param string code Unique name for the event.
3432
		 *	@param string data Data about the event.
3433
		 * }
3434
		 */
3435
		do_action( 'jetpack_log_entry', $log_entry );
3436
	}
3437
3438
	/**
3439
	 * Get the internal event log.
3440
	 *
3441
	 * @param $event (string) - only return the specific log events
3442
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3443
	 *
3444
	 * @return array of log events || WP_Error for invalid params
3445
	 */
3446
	public static function get_log( $event = false, $num = false ) {
3447
		if ( $event && ! is_string( $event ) ) {
3448
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3449
		}
3450
3451
		if ( $num && ! is_numeric( $num ) ) {
3452
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3453
		}
3454
3455
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3456
3457
		// If nothing set - act as it did before, otherwise let's start customizing the output
3458
		if ( ! $num && ! $event ) {
3459
			return $entire_log;
3460
		} else {
3461
			$entire_log = array_reverse( $entire_log );
3462
		}
3463
3464
		$custom_log_output = array();
3465
3466
		if ( $event ) {
3467
			foreach ( $entire_log as $log_event ) {
3468
				if ( $event == $log_event[ 'code' ] ) {
3469
					$custom_log_output[] = $log_event;
3470
				}
3471
			}
3472
		} else {
3473
			$custom_log_output = $entire_log;
3474
		}
3475
3476
		if ( $num ) {
3477
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3478
		}
3479
3480
		return $custom_log_output;
3481
	}
3482
3483
	/**
3484
	 * Log modification of important settings.
3485
	 */
3486
	public static function log_settings_change( $option, $old_value, $value ) {
3487
		switch( $option ) {
3488
			case 'jetpack_sync_non_public_post_stati':
3489
				self::log( $option, $value );
3490
				break;
3491
		}
3492
	}
3493
3494
	/**
3495
	 * Return stat data for WPCOM sync
3496
	 */
3497
	public static function get_stat_data( $encode = true, $extended = true ) {
3498
		$data = Jetpack_Heartbeat::generate_stats_array();
3499
3500
		if ( $extended ) {
3501
			$additional_data = self::get_additional_stat_data();
3502
			$data = array_merge( $data, $additional_data );
3503
		}
3504
3505
		if ( $encode ) {
3506
			return json_encode( $data );
3507
		}
3508
3509
		return $data;
3510
	}
3511
3512
	/**
3513
	 * Get additional stat data to sync to WPCOM
3514
	 */
3515
	public static function get_additional_stat_data( $prefix = '' ) {
3516
		$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...
3517
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3518
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3519
		$return["{$prefix}site-count"]     = 0;
3520
3521
		if ( function_exists( 'get_blog_count' ) ) {
3522
			$return["{$prefix}site-count"] = get_blog_count();
3523
		}
3524
		return $return;
3525
	}
3526
3527
	private static function get_site_user_count() {
3528
		global $wpdb;
3529
3530
		if ( function_exists( 'wp_is_large_network' ) ) {
3531
			if ( wp_is_large_network( 'users' ) ) {
3532
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3533
			}
3534
		}
3535 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3536
			// It wasn't there, so regenerate the data and save the transient
3537
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3538
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3539
		}
3540
		return $user_count;
3541
	}
3542
3543
	/* Admin Pages */
3544
3545
	function admin_init() {
3546
		// If the plugin is not connected, display a connect message.
3547
		if (
3548
			// the plugin was auto-activated and needs its candy
3549
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3550
		||
3551
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3552
			! Jetpack_Options::get_option( 'activated' )
3553
		) {
3554
			Jetpack::plugin_initialize();
3555
		}
3556
3557
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3558
			Jetpack_Connection_Banner::init();
3559
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3560
			// Upgrade: 1.1 -> 1.1.1
3561
			// Check and see if host can verify the Jetpack servers' SSL certificate
3562
			$args = array();
3563
			Jetpack_Client::_wp_remote_request(
3564
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3565
				$args,
3566
				true
3567
			);
3568
		} else if ( $this->can_display_jetpack_manage_notice() && ! Jetpack_Options::get_option( 'dismissed_manage_banner' ) ) {
3569
			// Show the notice on the Dashboard only for now
3570
			add_action( 'load-index.php', array( $this, 'prepare_manage_jetpack_notice' ) );
3571
		}
3572
3573
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3574
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3575
		}
3576
3577
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3578
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3579
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3580
3581
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3582
			// Artificially throw errors in certain whitelisted cases during plugin activation
3583
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3584
		}
3585
3586
		// Jetpack Manage Activation Screen from .com
3587
		Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
3588
3589
		// Add custom column in wp-admin/users.php to show whether user is linked.
3590
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3591
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3592
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3593
	}
3594
3595
	function admin_body_class( $admin_body_class = '' ) {
3596
		$classes = explode( ' ', trim( $admin_body_class ) );
3597
3598
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3599
3600
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3601
		return " $admin_body_class ";
3602
	}
3603
3604
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3605
		return $admin_body_class . ' jetpack-pagestyles ';
3606
	}
3607
3608
	/**
3609
	 * Call this function if you want the Big Jetpack Manage Notice to show up.
3610
	 *
3611
	 * @return null
3612
	 */
3613
	function prepare_manage_jetpack_notice() {
3614
3615
		add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
3616
		add_action( 'admin_notices', array( $this, 'admin_jetpack_manage_notice' ) );
3617
	}
3618
3619
	function manage_activate_screen() {
3620
		include ( JETPACK__PLUGIN_DIR . 'modules/manage/activate-admin.php' );
3621
	}
3622
	/**
3623
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3624
	 * This function artificially throws errors for such cases (whitelisted).
3625
	 *
3626
	 * @param string $plugin The activated plugin.
3627
	 */
3628
	function throw_error_on_activate_plugin( $plugin ) {
3629
		$active_modules = Jetpack::get_active_modules();
3630
3631
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3632
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3633
			$throw = false;
3634
3635
			// Try and make sure it really was the stats plugin
3636
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3637
				if ( 'stats.php' == basename( $plugin ) ) {
3638
					$throw = true;
3639
				}
3640
			} else {
3641
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3642
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3643
					$throw = true;
3644
				}
3645
			}
3646
3647
			if ( $throw ) {
3648
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3649
			}
3650
		}
3651
	}
3652
3653
	function intercept_plugin_error_scrape_init() {
3654
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3655
	}
3656
3657
	function intercept_plugin_error_scrape( $action, $result ) {
3658
		if ( ! $result ) {
3659
			return;
3660
		}
3661
3662
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3663
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3664
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3665
			}
3666
		}
3667
	}
3668
3669
	function add_remote_request_handlers() {
3670
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3671
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3672
	}
3673
3674
	function remote_request_handlers() {
3675
		$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...
3676
3677
		switch ( current_filter() ) {
3678
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3679
			$response = $this->upload_handler();
3680
			break;
3681
3682
		case 'wp_ajax_nopriv_jetpack_update_file' :
3683
			$response = $this->upload_handler( true );
3684
			break;
3685
		default :
3686
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
3687
			break;
3688
		}
3689
3690
		if ( ! $response ) {
3691
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
3692
		}
3693
3694
		if ( is_wp_error( $response ) ) {
3695
			$status_code       = $response->get_error_data();
3696
			$error             = $response->get_error_code();
3697
			$error_description = $response->get_error_message();
3698
3699
			if ( ! is_int( $status_code ) ) {
3700
				$status_code = 400;
3701
			}
3702
3703
			status_header( $status_code );
3704
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3705
		}
3706
3707
		status_header( 200 );
3708
		if ( true === $response ) {
3709
			exit;
3710
		}
3711
3712
		die( json_encode( (object) $response ) );
3713
	}
3714
3715
	/**
3716
	 * Uploads a file gotten from the global $_FILES.
3717
	 * If `$update_media_item` is true and `post_id` is defined
3718
	 * the attachment file of the media item (gotten through of the post_id)
3719
	 * will be updated instead of add a new one.
3720
	 *
3721
	 * @param  boolean $update_media_item - update media attachment
3722
	 * @return array - An array describing the uploadind files process
3723
	 */
3724
	function upload_handler( $update_media_item = false ) {
3725
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3726
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
3727
		}
3728
3729
		$user = wp_authenticate( '', '' );
3730
		if ( ! $user || is_wp_error( $user ) ) {
3731
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
3732
		}
3733
3734
		wp_set_current_user( $user->ID );
3735
3736
		if ( ! current_user_can( 'upload_files' ) ) {
3737
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3738
		}
3739
3740
		if ( empty( $_FILES ) ) {
3741
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3742
		}
3743
3744
		foreach ( array_keys( $_FILES ) as $files_key ) {
3745
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3746
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3747
			}
3748
		}
3749
3750
		$media_keys = array_keys( $_FILES['media'] );
3751
3752
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
3753
		if ( ! $token || is_wp_error( $token ) ) {
3754
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3755
		}
3756
3757
		$uploaded_files = array();
3758
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3759
		unset( $GLOBALS['post'] );
3760
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3761
			$file = array();
3762
			foreach ( $media_keys as $media_key ) {
3763
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3764
			}
3765
3766
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3767
3768
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3769
			if ( $hmac_provided !== $hmac_file ) {
3770
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3771
				continue;
3772
			}
3773
3774
			$_FILES['.jetpack.upload.'] = $file;
3775
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3776
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3777
				$post_id = 0;
3778
			}
3779
3780
			if ( $update_media_item ) {
3781
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3782
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3783
				}
3784
3785
				$media_array = $_FILES['media'];
3786
3787
				$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...
3788
				$file_array['type'] = $media_array['type'][0];
3789
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3790
				$file_array['error'] = $media_array['error'][0];
3791
				$file_array['size'] = $media_array['size'][0];
3792
3793
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3794
3795
				if ( is_wp_error( $edited_media_item ) ) {
3796
					return $edited_media_item;
3797
				}
3798
3799
				$response = (object) array(
3800
					'id'   => (string) $post_id,
3801
					'file' => (string) $edited_media_item->post_title,
3802
					'url'  => (string) wp_get_attachment_url( $post_id ),
3803
					'type' => (string) $edited_media_item->post_mime_type,
3804
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3805
				);
3806
3807
				return (array) array( $response );
3808
			}
3809
3810
			$attachment_id = media_handle_upload(
3811
				'.jetpack.upload.',
3812
				$post_id,
3813
				array(),
3814
				array(
3815
					'action' => 'jetpack_upload_file',
3816
				)
3817
			);
3818
3819
			if ( ! $attachment_id ) {
3820
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3821
			} elseif ( is_wp_error( $attachment_id ) ) {
3822
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3823
			} else {
3824
				$attachment = get_post( $attachment_id );
3825
				$uploaded_files[$index] = (object) array(
3826
					'id'   => (string) $attachment_id,
3827
					'file' => $attachment->post_title,
3828
					'url'  => wp_get_attachment_url( $attachment_id ),
3829
					'type' => $attachment->post_mime_type,
3830
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3831
				);
3832
				// Zip files uploads are not supported unless they are done for installation purposed
3833
				// lets delete them in case something goes wrong in this whole process
3834
				if ( 'application/zip' === $attachment->post_mime_type ) {
3835
					// Schedule a cleanup for 2 hours from now in case of failed install.
3836
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3837
				}
3838
			}
3839
		}
3840
		if ( ! is_null( $global_post ) ) {
3841
			$GLOBALS['post'] = $global_post;
3842
		}
3843
3844
		return $uploaded_files;
3845
	}
3846
3847
	/**
3848
	 * Add help to the Jetpack page
3849
	 *
3850
	 * @since Jetpack (1.2.3)
3851
	 * @return false if not the Jetpack page
3852
	 */
3853
	function admin_help() {
3854
		$current_screen = get_current_screen();
3855
3856
		// Overview
3857
		$current_screen->add_help_tab(
3858
			array(
3859
				'id'		=> 'home',
3860
				'title'		=> __( 'Home', 'jetpack' ),
3861
				'content'	=>
3862
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3863
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3864
					'<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>',
3865
			)
3866
		);
3867
3868
		// Screen Content
3869
		if ( current_user_can( 'manage_options' ) ) {
3870
			$current_screen->add_help_tab(
3871
				array(
3872
					'id'		=> 'settings',
3873
					'title'		=> __( 'Settings', 'jetpack' ),
3874
					'content'	=>
3875
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3876
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3877
						'<ol>' .
3878
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3879
							'<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>' .
3880
						'</ol>' .
3881
						'<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>'
3882
				)
3883
			);
3884
		}
3885
3886
		// Help Sidebar
3887
		$current_screen->set_help_sidebar(
3888
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3889
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3890
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3891
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3892
		);
3893
	}
3894
3895
	function admin_menu_css() {
3896
		wp_enqueue_style( 'jetpack-icons' );
3897
	}
3898
3899
	function admin_menu_order() {
3900
		return true;
3901
	}
3902
3903 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3904
		$jp_menu_order = array();
3905
3906
		foreach ( $menu_order as $index => $item ) {
3907
			if ( $item != 'jetpack' ) {
3908
				$jp_menu_order[] = $item;
3909
			}
3910
3911
			if ( $index == 0 ) {
3912
				$jp_menu_order[] = 'jetpack';
3913
			}
3914
		}
3915
3916
		return $jp_menu_order;
3917
	}
3918
3919
	function admin_head() {
3920 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
3921
			/** This action is documented in class.jetpack-admin-page.php */
3922
			do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
3923
	}
3924
3925
	function admin_banner_styles() {
3926
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3927
3928
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3929
			wp_register_style(
3930
				'jetpack-dops-style',
3931
				plugins_url( '_inc/build/admin.dops-style.css', JETPACK__PLUGIN_FILE ),
3932
				array(),
3933
				JETPACK__VERSION
3934
			);
3935
		}
3936
3937
		wp_enqueue_style(
3938
			'jetpack',
3939
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3940
			array( 'jetpack-dops-style' ),
3941
			 JETPACK__VERSION . '-20121016'
3942
		);
3943
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3944
		wp_style_add_data( 'jetpack', 'suffix', $min );
3945
	}
3946
3947
	function plugin_action_links( $actions ) {
3948
3949
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3950
3951
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3952
			return array_merge(
3953
				$jetpack_home,
3954
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3955
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3956
				$actions
3957
				);
3958
			}
3959
3960
		return array_merge( $jetpack_home, $actions );
3961
	}
3962
3963
	/**
3964
	 * This is the first banner
3965
	 * It should be visible only to user that can update the option
3966
	 * Are not connected
3967
	 *
3968
	 * @return null
3969
	 */
3970
	function admin_jetpack_manage_notice() {
3971
		$screen = get_current_screen();
3972
3973
		// Don't show the connect notice on the jetpack settings page.
3974
		if ( ! in_array( $screen->base, array( 'dashboard' ) ) || $screen->is_network || $screen->action ) {
3975
			return;
3976
		}
3977
3978
		$opt_out_url = $this->opt_out_jetpack_manage_url();
3979
		$opt_in_url  = $this->opt_in_jetpack_manage_url();
3980
		/**
3981
		 * I think it would be great to have different wordsing depending on where you are
3982
		 * for example if we show the notice on dashboard and a different one if we show it on Plugins screen
3983
		 * etc..
3984
		 */
3985
3986
		?>
3987
		<div id="message" class="updated jp-banner">
3988
				<a href="<?php echo esc_url( $opt_out_url ); ?>" class="notice-dismiss" title="<?php esc_attr_e( 'Dismiss this notice', 'jetpack' ); ?>"></a>
3989
				<div class="jp-banner__description-container">
3990
					<h2 class="jp-banner__header"><?php esc_html_e( 'Jetpack Centralized Site Management', 'jetpack' ); ?></h2>
3991
					<p class="jp-banner__description"><?php printf( __( 'Manage multiple Jetpack enabled sites from one single dashboard at wordpress.com. Allows all existing, connected Administrators to modify your site.', 'jetpack' ), 'https://jetpack.com/support/site-management' ); ?></p>
3992
					<p class="jp-banner__button-container">
3993
						<a href="<?php echo esc_url( $opt_in_url ); ?>" class="button button-primary" id="wpcom-connect"><?php _e( 'Activate Jetpack Manage', 'jetpack' ); ?></a>
3994
						<a href="https://jetpack.com/support/site-management" class="button" target="_blank" title="<?php esc_attr_e( 'Learn more about Jetpack Manage on Jetpack.com', 'jetpack' ); ?>"><?php _e( 'Learn more', 'jetpack' ); ?></a>
3995
					</p>
3996
				</div>
3997
		</div>
3998
		<?php
3999
	}
4000
4001
	/**
4002
	 * Returns the url that the user clicks to remove the notice for the big banner
4003
	 * @return string
4004
	 */
4005
	function opt_out_jetpack_manage_url() {
4006
		$referer = '&_wp_http_referer=' . add_query_arg( '_wp_http_referer', null );
4007
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-out' . $referer ), 'jetpack_manage_banner_opt_out' );
4008
	}
4009
	/**
4010
	 * Returns the url that the user clicks to opt in to Jetpack Manage
4011
	 * @return string
4012
	 */
4013
	function opt_in_jetpack_manage_url() {
4014
		return wp_nonce_url( Jetpack::admin_url( 'jetpack-notice=jetpack-manage-opt-in' ), 'jetpack_manage_banner_opt_in' );
4015
	}
4016
4017
	function opt_in_jetpack_manage_notice() {
4018
		?>
4019
		<div class="wrap">
4020
			<div id="message" class="jetpack-message is-opt-in">
4021
				<?php echo sprintf( __( '<p><a href="%1$s" title="Opt in to WordPress.com Site Management" >Activate Site Management</a> to manage multiple sites from our centralized dashboard at wordpress.com/sites. <a href="%2$s" target="_blank">Learn more</a>.</p><a href="%1$s" class="jp-button">Activate Now</a>', 'jetpack' ), $this->opt_in_jetpack_manage_url(), 'https://jetpack.com/support/site-management' ); ?>
4022
			</div>
4023
		</div>
4024
		<?php
4025
4026
	}
4027
	/**
4028
	 * Determines whether to show the notice of not true = display notice
4029
	 * @return bool
4030
	 */
4031
	function can_display_jetpack_manage_notice() {
4032
		// never display the notice to users that can't do anything about it anyways
4033
		if( ! current_user_can( 'jetpack_manage_modules' ) )
4034
			return false;
4035
4036
		// don't display if we are in development more
4037
		if( Jetpack::is_development_mode() ) {
4038
			return false;
4039
		}
4040
		// don't display if the site is private
4041
		if(  ! Jetpack_Options::get_option( 'public' ) )
4042
			return false;
4043
4044
		/**
4045
		 * Should the Jetpack Remote Site Management notice be displayed.
4046
		 *
4047
		 * @since 3.3.0
4048
		 *
4049
		 * @param bool ! self::is_module_active( 'manage' ) Is the Manage module inactive.
4050
		 */
4051
		return apply_filters( 'can_display_jetpack_manage_notice', ! self::is_module_active( 'manage' ) );
4052
	}
4053
4054
	/*
4055
	 * Registration flow:
4056
	 * 1 - ::admin_page_load() action=register
4057
	 * 2 - ::try_registration()
4058
	 * 3 - ::register()
4059
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4060
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4061
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4062
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4063
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4064
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4065
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4066
	 *       jetpack_id, jetpack_secret, jetpack_public
4067
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4068
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4069
	 * 5 - user logs in with WP.com account
4070
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4071
	 *		- Jetpack_Client_Server::authorize()
4072
	 *		- Jetpack_Client_Server::get_token()
4073
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4074
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4075
	 *			- which responds with access_token, token_type, scope
4076
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
4077
	 *		- Jetpack::activate_default_modules()
4078
	 *     		- Deactivates deprecated plugins
4079
	 *     		- Activates all default modules
4080
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4081
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4082
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4083
	 *     Done!
4084
	 */
4085
4086
	/**
4087
	 * Handles the page load events for the Jetpack admin page
4088
	 */
4089
	function admin_page_load() {
4090
		$error = false;
4091
4092
		// Make sure we have the right body class to hook stylings for subpages off of.
4093
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
4094
4095
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4096
			// Should only be used in intermediate redirects to preserve state across redirects
4097
			Jetpack::restate();
4098
		}
4099
4100
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4101
			// User clicked in the iframe to link their accounts
4102
			if ( ! Jetpack::is_user_connected() ) {
4103
				$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4104
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4105
4106
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4107
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4108
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4109
4110
				if ( isset( $_GET['notes_iframe'] ) )
4111
					$connect_url .= '&notes_iframe';
4112
				wp_redirect( $connect_url );
4113
				exit;
4114
			} else {
4115
				if ( ! isset( $_GET['calypso_env'] ) ) {
4116
					Jetpack::state( 'message', 'already_authorized' );
4117
					wp_safe_redirect( Jetpack::admin_url() );
4118
					exit;
4119
				} else {
4120
					$connect_url = $this->build_connect_url( true, false, 'iframe' );
4121
					$connect_url .= '&already_authorized=true';
4122
					wp_redirect( $connect_url );
4123
					exit;
4124
				}
4125
			}
4126
		}
4127
4128
4129
		if ( isset( $_GET['action'] ) ) {
4130
			switch ( $_GET['action'] ) {
4131
			case 'authorize':
4132
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4133
					Jetpack::state( 'message', 'already_authorized' );
4134
					wp_safe_redirect( Jetpack::admin_url() );
4135
					exit;
4136
				}
4137
				Jetpack::log( 'authorize' );
4138
				$client_server = new Jetpack_Client_Server;
4139
				$client_server->client_authorize();
4140
				exit;
4141
			case 'register' :
4142
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4143
					$error = 'cheatin';
4144
					break;
4145
				}
4146
				check_admin_referer( 'jetpack-register' );
4147
				Jetpack::log( 'register' );
4148
				Jetpack::maybe_set_version_option();
4149
				$registered = Jetpack::try_registration();
4150
				if ( is_wp_error( $registered ) ) {
4151
					$error = $registered->get_error_code();
4152
					Jetpack::state( 'error', $error );
4153
					Jetpack::state( 'error', $registered->get_error_message() );
4154
					JetpackTracking::record_user_event( 'jpc_register_fail', array(
4155
						'error_code' => $error,
4156
						'error_message' => $registered->get_error_message()
4157
					) );
4158
					break;
4159
				}
4160
4161
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4162
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4163
4164
				JetpackTracking::record_user_event( 'jpc_register_success', array(
4165
					'from' => $from
4166
				) );
4167
4168
				$url = $this->build_connect_url( true, $redirect, $from );
4169
4170
				if ( ! empty( $_GET['onboarding'] ) ) {
4171
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4172
				}
4173
4174
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4175
					$url = add_query_arg( 'auth_approved', 'true', $url );
4176
				}
4177
4178
				wp_redirect( $url );
4179
				exit;
4180
			case 'activate' :
4181
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4182
					$error = 'cheatin';
4183
					break;
4184
				}
4185
4186
				$module = stripslashes( $_GET['module'] );
4187
				check_admin_referer( "jetpack_activate-$module" );
4188
				Jetpack::log( 'activate', $module );
4189
				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...
4190
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4191
				}
4192
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4193
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4194
				exit;
4195
			case 'activate_default_modules' :
4196
				check_admin_referer( 'activate_default_modules' );
4197
				Jetpack::log( 'activate_default_modules' );
4198
				Jetpack::restate();
4199
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4200
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4201
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4202
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4203
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4204
				exit;
4205
			case 'disconnect' :
4206
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4207
					$error = 'cheatin';
4208
					break;
4209
				}
4210
4211
				check_admin_referer( 'jetpack-disconnect' );
4212
				Jetpack::log( 'disconnect' );
4213
				Jetpack::disconnect();
4214
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4215
				exit;
4216
			case 'reconnect' :
4217
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4218
					$error = 'cheatin';
4219
					break;
4220
				}
4221
4222
				check_admin_referer( 'jetpack-reconnect' );
4223
				Jetpack::log( 'reconnect' );
4224
				$this->disconnect();
4225
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4226
				exit;
4227 View Code Duplication
			case 'deactivate' :
4228
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4229
					$error = 'cheatin';
4230
					break;
4231
				}
4232
4233
				$modules = stripslashes( $_GET['module'] );
4234
				check_admin_referer( "jetpack_deactivate-$modules" );
4235
				foreach ( explode( ',', $modules ) as $module ) {
4236
					Jetpack::log( 'deactivate', $module );
4237
					Jetpack::deactivate_module( $module );
4238
					Jetpack::state( 'message', 'module_deactivated' );
4239
				}
4240
				Jetpack::state( 'module', $modules );
4241
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4242
				exit;
4243
			case 'unlink' :
4244
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4245
				check_admin_referer( 'jetpack-unlink' );
4246
				Jetpack::log( 'unlink' );
4247
				$this->unlink_user();
4248
				Jetpack::state( 'message', 'unlinked' );
4249
				if ( 'sub-unlink' == $redirect ) {
4250
					wp_safe_redirect( admin_url() );
4251
				} else {
4252
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4253
				}
4254
				exit;
4255
			case 'onboard' :
4256
				if ( ! current_user_can( 'manage_options' ) ) {
4257
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4258
				} else {
4259
					Jetpack::create_onboarding_token();
4260
					$url = $this->build_connect_url( true );
4261
4262
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4263
						$url = add_query_arg( 'onboarding', $token, $url );
4264
					}
4265
4266
					$calypso_env = ! empty( $_GET[ 'calypso_env' ] ) ? $_GET[ 'calypso_env' ] : false;
4267
					if ( $calypso_env ) {
4268
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4269
					}
4270
4271
					wp_redirect( $url );
4272
					exit;
4273
				}
4274
				exit;
4275
			default:
4276
				/**
4277
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4278
				 *
4279
				 * @since 2.6.0
4280
				 *
4281
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4282
				 */
4283
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4284
			}
4285
		}
4286
4287
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4288
			self::activate_new_modules( true );
4289
		}
4290
4291
		$message_code = Jetpack::state( 'message' );
4292
		if ( Jetpack::state( 'optin-manage' ) ) {
4293
			$activated_manage = $message_code;
4294
			$message_code = 'jetpack-manage';
4295
		}
4296
4297
		switch ( $message_code ) {
4298
		case 'jetpack-manage':
4299
			$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>';
4300
			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...
4301
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4302
			}
4303
			break;
4304
4305
		}
4306
4307
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4308
4309
		if ( ! empty( $deactivated_plugins ) ) {
4310
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4311
			$deactivated_titles  = array();
4312
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4313
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4314
					continue;
4315
				}
4316
4317
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4318
			}
4319
4320
			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...
4321
				if ( $this->message ) {
4322
					$this->message .= "<br /><br />\n";
4323
				}
4324
4325
				$this->message .= wp_sprintf(
4326
					_n(
4327
						'Jetpack contains the most recent version of the old %l plugin.',
4328
						'Jetpack contains the most recent versions of the old %l plugins.',
4329
						count( $deactivated_titles ),
4330
						'jetpack'
4331
					),
4332
					$deactivated_titles
4333
				);
4334
4335
				$this->message .= "<br />\n";
4336
4337
				$this->message .= _n(
4338
					'The old version has been deactivated and can be removed from your site.',
4339
					'The old versions have been deactivated and can be removed from your site.',
4340
					count( $deactivated_titles ),
4341
					'jetpack'
4342
				);
4343
			}
4344
		}
4345
4346
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4347
4348
		if ( $this->message || $this->error || $this->privacy_checks || $this->can_display_jetpack_manage_notice() ) {
4349
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4350
		}
4351
4352 View Code Duplication
		if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
4353
			/**
4354
			 * Fires when a module configuration page is loaded.
4355
			 * The dynamic part of the hook is the configure parameter from the URL.
4356
			 *
4357
			 * @since 1.1.0
4358
			 */
4359
			do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
4360
		}
4361
4362
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4363
	}
4364
4365
	function admin_notices() {
4366
4367
		if ( $this->error ) {
4368
?>
4369
<div id="message" class="jetpack-message jetpack-err">
4370
	<div class="squeezer">
4371
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4372
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4373
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4374
<?php	endif; ?>
4375
	</div>
4376
</div>
4377
<?php
4378
		}
4379
4380
		if ( $this->message ) {
4381
?>
4382
<div id="message" class="jetpack-message">
4383
	<div class="squeezer">
4384
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4385
	</div>
4386
</div>
4387
<?php
4388
		}
4389
4390
		if ( $this->privacy_checks ) :
4391
			$module_names = $module_slugs = array();
4392
4393
			$privacy_checks = explode( ',', $this->privacy_checks );
4394
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4395
			foreach ( $privacy_checks as $module_slug ) {
4396
				$module = Jetpack::get_module( $module_slug );
4397
				if ( ! $module ) {
4398
					continue;
4399
				}
4400
4401
				$module_slugs[] = $module_slug;
4402
				$module_names[] = "<strong>{$module['name']}</strong>";
4403
			}
4404
4405
			$module_slugs = join( ',', $module_slugs );
4406
?>
4407
<div id="message" class="jetpack-message jetpack-err">
4408
	<div class="squeezer">
4409
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4410
		<p><?php
4411
			echo wp_kses(
4412
				wptexturize(
4413
					wp_sprintf(
4414
						_nx(
4415
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4416
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4417
							count( $privacy_checks ),
4418
							'%l = list of Jetpack module/feature names',
4419
							'jetpack'
4420
						),
4421
						$module_names
4422
					)
4423
				),
4424
				array( 'strong' => true )
4425
			);
4426
4427
			echo "\n<br />\n";
4428
4429
			echo wp_kses(
4430
				sprintf(
4431
					_nx(
4432
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4433
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4434
						count( $privacy_checks ),
4435
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4436
						'jetpack'
4437
					),
4438
					wp_nonce_url(
4439
						Jetpack::admin_url(
4440
							array(
4441
								'page'   => 'jetpack',
4442
								'action' => 'deactivate',
4443
								'module' => urlencode( $module_slugs ),
4444
							)
4445
						),
4446
						"jetpack_deactivate-$module_slugs"
4447
					),
4448
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4449
				),
4450
				array( 'a' => array( 'href' => true, 'title' => true ) )
4451
			);
4452
		?></p>
4453
	</div>
4454
</div>
4455
<?php endif;
4456
	// only display the notice if the other stuff is not there
4457
	if( $this->can_display_jetpack_manage_notice() && !  $this->error && ! $this->message && ! $this->privacy_checks ) {
4458
		if( isset( $_GET['page'] ) && 'jetpack' != $_GET['page'] )
4459
			$this->opt_in_jetpack_manage_notice();
4460
		}
4461
	}
4462
4463
	/**
4464
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4465
	 */
4466
	function stat( $group, $detail ) {
4467
		if ( ! isset( $this->stats[ $group ] ) )
4468
			$this->stats[ $group ] = array();
4469
		$this->stats[ $group ][] = $detail;
4470
	}
4471
4472
	/**
4473
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4474
	 */
4475
	function do_stats( $method = '' ) {
4476
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4477
			foreach ( $this->stats as $group => $stats ) {
4478
				if ( is_array( $stats ) && count( $stats ) ) {
4479
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4480
					if ( 'server_side' === $method ) {
4481
						self::do_server_side_stat( $args );
4482
					} else {
4483
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4484
					}
4485
				}
4486
				unset( $this->stats[ $group ] );
4487
			}
4488
		}
4489
	}
4490
4491
	/**
4492
	 * Runs stats code for a one-off, server-side.
4493
	 *
4494
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4495
	 *
4496
	 * @return bool If it worked.
4497
	 */
4498
	static function do_server_side_stat( $args ) {
4499
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4500
		if ( is_wp_error( $response ) )
4501
			return false;
4502
4503
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4504
			return false;
4505
4506
		return true;
4507
	}
4508
4509
	/**
4510
	 * Builds the stats url.
4511
	 *
4512
	 * @param $args array|string The arguments to append to the URL.
4513
	 *
4514
	 * @return string The URL to be pinged.
4515
	 */
4516
	static function build_stats_url( $args ) {
4517
		$defaults = array(
4518
			'v'    => 'wpcom2',
4519
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4520
		);
4521
		$args     = wp_parse_args( $args, $defaults );
4522
		/**
4523
		 * Filter the URL used as the Stats tracking pixel.
4524
		 *
4525
		 * @since 2.3.2
4526
		 *
4527
		 * @param string $url Base URL used as the Stats tracking pixel.
4528
		 */
4529
		$base_url = apply_filters(
4530
			'jetpack_stats_base_url',
4531
			'https://pixel.wp.com/g.gif'
4532
		);
4533
		$url      = add_query_arg( $args, $base_url );
4534
		return $url;
4535
	}
4536
4537
	static function translate_current_user_to_role() {
4538
		foreach ( self::$capability_translations as $role => $cap ) {
4539
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4540
				return $role;
4541
			}
4542
		}
4543
4544
		return false;
4545
	}
4546
4547
	static function translate_user_to_role( $user ) {
4548
		foreach ( self::$capability_translations as $role => $cap ) {
4549
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4550
				return $role;
4551
			}
4552
		}
4553
4554
		return false;
4555
    }
4556
4557
	static function translate_role_to_cap( $role ) {
4558
		if ( ! isset( self::$capability_translations[$role] ) ) {
4559
			return false;
4560
		}
4561
4562
		return self::$capability_translations[$role];
4563
	}
4564
4565
	static function sign_role( $role, $user_id = null ) {
4566
		if ( empty( $user_id ) ) {
4567
			$user_id = (int) get_current_user_id();
4568
		}
4569
4570
		if ( ! $user_id  ) {
4571
			return false;
4572
		}
4573
4574
		$token = Jetpack_Data::get_access_token();
4575
		if ( ! $token || is_wp_error( $token ) ) {
4576
			return false;
4577
		}
4578
4579
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4580
	}
4581
4582
4583
	/**
4584
	 * Builds a URL to the Jetpack connection auth page
4585
	 *
4586
	 * @since 3.9.5
4587
	 *
4588
	 * @param bool $raw If true, URL will not be escaped.
4589
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4590
	 *                              If string, will be a custom redirect.
4591
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4592
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4593
	 *
4594
	 * @return string Connect URL
4595
	 */
4596
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4597
		$site_id = Jetpack_Options::get_option( 'id' );
4598
		$token = Jetpack_Options::get_option( 'blog_token' );
4599
4600
		if ( $register || ! $token || ! $site_id ) {
4601
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4602
4603
			if ( ! empty( $redirect ) ) {
4604
				$url = add_query_arg(
4605
					'redirect',
4606
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4607
					$url
4608
				);
4609
			}
4610
4611
			if( is_network_admin() ) {
4612
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4613
			}
4614
		} else {
4615
4616
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4617
			// because otherwise this logic can get us in to a loop.
4618
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4619
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4620
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4621
4622
				$response = Jetpack_Client::wpcom_json_api_request_as_blog(
4623
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4624
					'1.1'
4625
				);
4626
4627
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4628
					// Generating a register URL instead to refresh the existing token
4629
					return $this->build_connect_url( $raw, $redirect, $from, true );
4630
				}
4631
			}
4632
4633
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4634
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4635
			}
4636
4637
			$role = self::translate_current_user_to_role();
4638
			$signed_role = self::sign_role( $role );
4639
4640
			$user = wp_get_current_user();
4641
4642
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4643
			$redirect = $redirect
4644
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4645
				: $jetpack_admin_page;
4646
4647
			if( isset( $_REQUEST['is_multisite'] ) ) {
4648
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4649
			}
4650
4651
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4652
4653
			$site_icon = ( function_exists( 'has_site_icon') && has_site_icon() )
4654
				? get_site_icon_url()
4655
				: false;
4656
4657
			/**
4658
			 * Filter the type of authorization.
4659
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4660
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4661
			 *
4662
			 * @since 4.3.3
4663
			 *
4664
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4665
			 */
4666
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4667
4668
			$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
4669
4670
			$args = urlencode_deep(
4671
				array(
4672
					'response_type' => 'code',
4673
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4674
					'redirect_uri'  => add_query_arg(
4675
						array(
4676
							'action'   => 'authorize',
4677
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4678
							'redirect' => urlencode( $redirect ),
4679
						),
4680
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4681
					),
4682
					'state'         => $user->ID,
4683
					'scope'         => $signed_role,
4684
					'user_email'    => $user->user_email,
4685
					'user_login'    => $user->user_login,
4686
					'is_active'     => Jetpack::is_active(),
4687
					'jp_version'    => JETPACK__VERSION,
4688
					'auth_type'     => $auth_type,
4689
					'secret'        => $secrets['secret_1'],
4690
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4691
					'blogname'      => get_option( 'blogname' ),
4692
					'site_url'      => site_url(),
4693
					'home_url'      => home_url(),
4694
					'site_icon'     => $site_icon,
4695
					'site_lang'     => get_locale(),
4696
					'_ui'           => $tracks_identity['_ui'],
4697
					'_ut'           => $tracks_identity['_ut']
4698
				)
4699
			);
4700
4701
			self::apply_activation_source_to_args( $args );
4702
4703
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4704
		}
4705
4706
		if ( $from ) {
4707
			$url = add_query_arg( 'from', $from, $url );
4708
		}
4709
4710
4711
		if ( isset( $_GET['calypso_env'] ) ) {
4712
			$url = add_query_arg( 'calypso_env', sanitize_key( $_GET['calypso_env'] ), $url );
4713
		}
4714
4715
		return $raw ? $url : esc_url( $url );
4716
	}
4717
4718
	public static function apply_activation_source_to_args( &$args ) {
4719
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4720
4721
		if ( $activation_source_name ) {
4722
			$args['_as'] = urlencode( $activation_source_name );
4723
		}
4724
4725
		if ( $activation_source_keyword ) {
4726
			$args['_ak'] = urlencode( $activation_source_keyword );
4727
		}
4728
	}
4729
4730
	function build_reconnect_url( $raw = false ) {
4731
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4732
		return $raw ? $url : esc_url( $url );
4733
	}
4734
4735
	public static function admin_url( $args = null ) {
4736
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4737
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4738
		return $url;
4739
	}
4740
4741
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4742
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4743
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4744
	}
4745
4746
	function dismiss_jetpack_notice() {
4747
4748
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4749
			return;
4750
		}
4751
4752
		switch( $_GET['jetpack-notice'] ) {
4753
			case 'dismiss':
4754
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4755
4756
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4757
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4758
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4759
				}
4760
				break;
4761 View Code Duplication
			case 'jetpack-manage-opt-out':
4762
4763
				if ( check_admin_referer( 'jetpack_manage_banner_opt_out' ) ) {
4764
					// Don't show the banner again
4765
4766
					Jetpack_Options::update_option( 'dismissed_manage_banner', true );
4767
					// redirect back to the page that had the notice
4768
					if ( wp_get_referer() ) {
4769
						wp_safe_redirect( wp_get_referer() );
4770
					} else {
4771
						// Take me to Jetpack
4772
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4773
					}
4774
				}
4775
				break;
4776 View Code Duplication
			case 'jetpack-protect-multisite-opt-out':
4777
4778
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4779
					// Don't show the banner again
4780
4781
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4782
					// redirect back to the page that had the notice
4783
					if ( wp_get_referer() ) {
4784
						wp_safe_redirect( wp_get_referer() );
4785
					} else {
4786
						// Take me to Jetpack
4787
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4788
					}
4789
				}
4790
				break;
4791
			case 'jetpack-manage-opt-in':
4792
				if ( check_admin_referer( 'jetpack_manage_banner_opt_in' ) ) {
4793
					// This makes sure that we are redirect to jetpack home so that we can see the Success Message.
4794
4795
					$redirection_url = Jetpack::admin_url();
4796
					remove_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4797
4798
					// Don't redirect form the Jetpack Setting Page
4799
					$referer_parsed = parse_url ( wp_get_referer() );
4800
					// check that we do have a wp_get_referer and the query paramater is set orderwise go to the Jetpack Home
4801
					if ( isset( $referer_parsed['query'] ) && false !== strpos( $referer_parsed['query'], 'page=jetpack_modules' ) ) {
4802
						// Take the user to Jetpack home except when on the setting page
4803
						$redirection_url = wp_get_referer();
4804
						add_action( 'jetpack_pre_activate_module',   array( Jetpack_Admin::init(), 'fix_redirect' ) );
4805
					}
4806
					// Also update the JSON API FULL MANAGEMENT Option
4807
					Jetpack::activate_module( 'manage', false, false );
4808
4809
					// Special Message when option in.
4810
					Jetpack::state( 'optin-manage', 'true' );
4811
					// Activate the Module if not activated already
4812
4813
					// Redirect properly
4814
					wp_safe_redirect( $redirection_url );
4815
4816
				}
4817
				break;
4818
		}
4819
	}
4820
4821
	public static function admin_screen_configure_module( $module_id ) {
4822
4823
		// User that doesn't have 'jetpack_configure_modules' will never end up here since Jetpack Landing Page woun't let them.
4824
		if ( ! in_array( $module_id, Jetpack::get_active_modules() ) && current_user_can( 'manage_options' ) ) {
4825
			if ( has_action( 'display_activate_module_setting_' . $module_id ) ) {
4826
				/**
4827
				 * Fires to diplay a custom module activation screen.
4828
				 *
4829
				 * To add a module actionation screen use Jetpack::module_configuration_activation_screen method.
4830
				 * Example: Jetpack::module_configuration_activation_screen( 'manage', array( $this, 'manage_activate_screen' ) );
4831
				 *
4832
				 * @module manage
4833
				 *
4834
				 * @since 3.8.0
4835
				 *
4836
				 * @param int $module_id Module ID.
4837
				 */
4838
				do_action( 'display_activate_module_setting_' . $module_id );
4839
			} else {
4840
				self::display_activate_module_link( $module_id );
4841
			}
4842
4843
			return false;
4844
		} ?>
4845
4846
		<div id="jp-settings-screen" style="position: relative">
4847
			<h3>
4848
			<?php
4849
				$module = Jetpack::get_module( $module_id );
4850
				printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
4851
			?>
4852
			</h3>
4853
			<?php
4854
				/**
4855
				 * Fires within the displayed message when a feature configuation is updated.
4856
				 *
4857
				 * @since 3.4.0
4858
				 *
4859
				 * @param int $module_id Module ID.
4860
				 */
4861
				do_action( 'jetpack_notices_update_settings', $module_id );
4862
				/**
4863
				 * Fires when a feature configuation screen is loaded.
4864
				 * The dynamic part of the hook, $module_id, is the module ID.
4865
				 *
4866
				 * @since 1.1.0
4867
				 */
4868
				do_action( 'jetpack_module_configuration_screen_' . $module_id );
4869
			?>
4870
		</div><?php
4871
	}
4872
4873
	/**
4874
	 * Display link to activate the module to see the settings screen.
4875
	 * @param  string $module_id
4876
	 * @return null
4877
	 */
4878
	public static function display_activate_module_link( $module_id ) {
4879
4880
		$info =  Jetpack::get_module( $module_id );
4881
		$extra = '';
4882
		$activate_url = wp_nonce_url(
4883
				Jetpack::admin_url(
4884
					array(
4885
						'page'   => 'jetpack',
4886
						'action' => 'activate',
4887
						'module' => $module_id,
4888
					)
4889
				),
4890
				"jetpack_activate-$module_id"
4891
			);
4892
4893
		?>
4894
4895
		<div class="wrap configure-module">
4896
			<div id="jp-settings-screen">
4897
				<?php
4898
				if ( $module_id == 'json-api' ) {
4899
4900
					$info['name'] = esc_html__( 'Activate Site Management and JSON API', 'jetpack' );
4901
4902
					$activate_url = Jetpack::init()->opt_in_jetpack_manage_url();
4903
4904
					$info['description'] = sprintf( __( 'Manage your multiple Jetpack sites from our centralized dashboard at wordpress.com/sites. <a href="%s" target="_blank">Learn more</a>.', 'jetpack' ), 'https://jetpack.com/support/site-management' );
4905
4906
					// $extra = __( 'To use Site Management, you need to first activate JSON API to allow remote management of your site. ', 'jetpack' );
4907
				} ?>
4908
4909
				<h3><?php echo esc_html( $info['name'] ); ?></h3>
4910
				<div class="narrow">
4911
					<p><?php echo  $info['description']; ?></p>
4912
					<?php if( $extra ) { ?>
4913
					<p><?php echo esc_html( $extra ); ?></p>
4914
					<?php } ?>
4915
					<p>
4916
						<?php
4917
						if( wp_get_referer() ) {
4918
							printf( __( '<a class="button-primary" href="%s">Activate Now</a> or <a href="%s" >return to previous page</a>.', 'jetpack' ) , $activate_url, wp_get_referer() );
4919
						} else {
4920
							printf( __( '<a class="button-primary" href="%s">Activate Now</a>', 'jetpack' ) , $activate_url  );
4921
						} ?>
4922
					</p>
4923
				</div>
4924
4925
			</div>
4926
		</div>
4927
4928
		<?php
4929
	}
4930
4931
	public static function sort_modules( $a, $b ) {
4932
		if ( $a['sort'] == $b['sort'] )
4933
			return 0;
4934
4935
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4936
	}
4937
4938
	function ajax_recheck_ssl() {
4939
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4940
		$result = Jetpack::permit_ssl( true );
4941
		wp_send_json( array(
4942
			'enabled' => $result,
4943
			'message' => get_transient( 'jetpack_https_test_message' )
4944
		) );
4945
	}
4946
4947
/* Client API */
4948
4949
	/**
4950
	 * Returns the requested Jetpack API URL
4951
	 *
4952
	 * @return string
4953
	 */
4954
	public static function api_url( $relative_url ) {
4955
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4956
	}
4957
4958
	/**
4959
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4960
	 */
4961
	public static function fix_url_for_bad_hosts( $url ) {
4962
		if ( 0 !== strpos( $url, 'https://' ) ) {
4963
			return $url;
4964
		}
4965
4966
		switch ( JETPACK_CLIENT__HTTPS ) {
4967
			case 'ALWAYS' :
4968
				return $url;
4969
			case 'NEVER' :
4970
				return set_url_scheme( $url, 'http' );
4971
			// default : case 'AUTO' :
4972
		}
4973
4974
		// we now return the unmodified SSL URL by default, as a security precaution
4975
		return $url;
4976
	}
4977
4978
	/**
4979
	 * Create a random secret for validating onboarding payload
4980
	 *
4981
	 * @return string Secret token
4982
	 */
4983
	public static function create_onboarding_token() {
4984
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4985
			$token = wp_generate_password( 32, false );
4986
			Jetpack_Options::update_option( 'onboarding', $token );
4987
		}
4988
4989
		return $token;
4990
	}
4991
4992
	/**
4993
	 * Remove the onboarding token
4994
	 *
4995
	 * @return bool True on success, false on failure
4996
	 */
4997
	public static function invalidate_onboarding_token() {
4998
		return Jetpack_Options::delete_option( 'onboarding' );
4999
	}
5000
5001
	/**
5002
	 * Validate an onboarding token for a specific action
5003
	 *
5004
	 * @return boolean True if token/action pair is accepted, false if not
5005
	 */
5006
	public static function validate_onboarding_token_action( $token, $action ) {
5007
		// Compare tokens, bail if tokens do not match
5008
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5009
			return false;
5010
		}
5011
5012
		// List of valid actions we can take
5013
		$valid_actions = array(
5014
			'/jetpack/v4/settings',
5015
		);
5016
5017
		// Whitelist the action
5018
		if ( ! in_array( $action, $valid_actions ) ) {
5019
			return false;
5020
		}
5021
5022
		return true;
5023
	}
5024
5025
	/**
5026
	 * Checks to see if the URL is using SSL to connect with Jetpack
5027
	 *
5028
	 * @since 2.3.3
5029
	 * @return boolean
5030
	 */
5031
	public static function permit_ssl( $force_recheck = false ) {
5032
		// Do some fancy tests to see if ssl is being supported
5033
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5034
			$message = '';
5035
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5036
				$ssl = 0;
5037
			} else {
5038
				switch ( JETPACK_CLIENT__HTTPS ) {
5039
					case 'NEVER':
5040
						$ssl = 0;
5041
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5042
						break;
5043
					case 'ALWAYS':
5044
					case 'AUTO':
5045
					default:
5046
						$ssl = 1;
5047
						break;
5048
				}
5049
5050
				// If it's not 'NEVER', test to see
5051
				if ( $ssl ) {
5052
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5053
						$ssl = 0;
5054
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5055
					} else {
5056
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5057
						if ( is_wp_error( $response ) ) {
5058
							$ssl = 0;
5059
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5060
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5061
							$ssl = 0;
5062
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5063
						}
5064
					}
5065
				}
5066
			}
5067
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5068
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5069
		}
5070
5071
		return (bool) $ssl;
5072
	}
5073
5074
	/*
5075
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5076
	 */
5077
	public function alert_auto_ssl_fail() {
5078
		if ( ! current_user_can( 'manage_options' ) )
5079
			return;
5080
5081
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5082
		?>
5083
5084
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5085
			<div class="jp-banner__content">
5086
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5087
				<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>
5088
				<p>
5089
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5090
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5091
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5092
				</p>
5093
				<p>
5094
					<?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' ),
5095
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
5096
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
5097
				</p>
5098
			</div>
5099
		</div>
5100
		<style>
5101
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5102
		</style>
5103
		<script type="text/javascript">
5104
			jQuery( document ).ready( function( $ ) {
5105
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5106
					var $this = $( this );
5107
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5108
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5109
					e.preventDefault();
5110
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5111
					$.post( ajaxurl, data )
5112
					  .done( function( response ) {
5113
					  	if ( response.enabled ) {
5114
					  		$( '#jetpack-ssl-warning' ).hide();
5115
					  	} else {
5116
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5117
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5118
					  	}
5119
					  }.bind( $this ) );
5120
				} );
5121
			} );
5122
		</script>
5123
5124
		<?php
5125
	}
5126
5127
	/**
5128
	 * Returns the Jetpack XML-RPC API
5129
	 *
5130
	 * @return string
5131
	 */
5132
	public static function xmlrpc_api_url() {
5133
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
5134
		return untrailingslashit( $base ) . '/xmlrpc.php';
5135
	}
5136
5137
	/**
5138
	 * Creates two secret tokens and the end of life timestamp for them.
5139
	 *
5140
	 * Note these tokens are unique per call, NOT static per site for connecting.
5141
	 *
5142
	 * @since 2.6
5143
	 * @return array
5144
	 */
5145
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5146
		if ( ! $user_id ) {
5147
			$user_id = get_current_user_id();
5148
		}
5149
5150
		$secret_name  = 'jetpack_' . $action . '_' . $user_id;
5151
		$secrets      = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5152
5153
		if (
5154
			isset( $secrets[ $secret_name ] ) &&
5155
			$secrets[ $secret_name ]['exp'] > time()
5156
		) {
5157
			return $secrets[ $secret_name ];
5158
		}
5159
5160
		$secret_value = array(
5161
			'secret_1'  => wp_generate_password( 32, false ),
5162
			'secret_2'  => wp_generate_password( 32, false ),
5163
			'exp'       => time() + $exp,
5164
		);
5165
5166
		$secrets[ $secret_name ] = $secret_value;
5167
5168
		Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
5169
		return $secrets[ $secret_name ];
5170
	}
5171
5172
	public static function get_secrets( $action, $user_id ) {
5173
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
5174
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5175
5176
		if ( ! isset( $secrets[ $secret_name ] ) ) {
5177
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5178
		}
5179
5180
		if ( $secrets[ $secret_name ]['exp'] < time() ) {
5181
			self::delete_secrets( $action, $user_id );
5182
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5183
		}
5184
5185
		return $secrets[ $secret_name ];
5186
	}
5187
5188
	public static function delete_secrets( $action, $user_id ) {
5189
		$secret_name = 'jetpack_' . $action . '_' . $user_id;
5190
		$secrets = Jetpack_Options::get_raw_option( 'jetpack_secrets', array() );
5191
		if ( isset( $secrets[ $secret_name ] ) ) {
5192
			unset( $secrets[ $secret_name ] );
5193
			Jetpack_Options::update_raw_option( 'jetpack_secrets', $secrets );
5194
		}
5195
	}
5196
5197
	/**
5198
	 * Builds the timeout limit for queries talking with the wpcom servers.
5199
	 *
5200
	 * Based on local php max_execution_time in php.ini
5201
	 *
5202
	 * @since 2.6
5203
	 * @return int
5204
	 * @deprecated
5205
	 **/
5206
	public function get_remote_query_timeout_limit() {
5207
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5208
		return Jetpack::get_max_execution_time();
5209
	}
5210
5211
	/**
5212
	 * Builds the timeout limit for queries talking with the wpcom servers.
5213
	 *
5214
	 * Based on local php max_execution_time in php.ini
5215
	 *
5216
	 * @since 5.4
5217
	 * @return int
5218
	 **/
5219
	public static function get_max_execution_time() {
5220
		$timeout = (int) ini_get( 'max_execution_time' );
5221
5222
		// Ensure exec time set in php.ini
5223
		if ( ! $timeout ) {
5224
			$timeout = 30;
5225
		}
5226
		return $timeout;
5227
	}
5228
5229
	/**
5230
	 * Sets a minimum request timeout, and returns the current timeout
5231
	 *
5232
	 * @since 5.4
5233
	 **/
5234
	public static function set_min_time_limit( $min_timeout ) {
5235
		$timeout = self::get_max_execution_time();
5236
		if ( $timeout < $min_timeout ) {
5237
			$timeout = $min_timeout;
5238
			set_time_limit( $timeout );
5239
		}
5240
		return $timeout;
5241
	}
5242
5243
5244
	/**
5245
	 * Takes the response from the Jetpack register new site endpoint and
5246
	 * verifies it worked properly.
5247
	 *
5248
	 * @since 2.6
5249
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
5250
	 **/
5251
	public function validate_remote_register_response( $response ) {
5252
	  if ( is_wp_error( $response ) ) {
5253
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
5254
		}
5255
5256
		$code   = wp_remote_retrieve_response_code( $response );
5257
		$entity = wp_remote_retrieve_body( $response );
5258
		if ( $entity )
5259
			$registration_response = json_decode( $entity );
5260
		else
5261
			$registration_response = false;
5262
5263
		$code_type = intval( $code / 100 );
5264
		if ( 5 == $code_type ) {
5265
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5266
		} elseif ( 408 == $code ) {
5267
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5268
		} elseif ( ! empty( $registration_response->error ) ) {
5269
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
5270
				$error_description = __( "PHP's XML extension is not available. Jetpack requires the XML extension to communicate with WordPress.com. Please contact your hosting provider to enable PHP's XML extension.", 'jetpack' );
5271
			} else {
5272
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
5273
			}
5274
5275
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
5276
		} elseif ( 200 != $code ) {
5277
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
5278
		}
5279
5280
		// Jetpack ID error block
5281
		if ( empty( $registration_response->jetpack_id ) ) {
5282
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
5283
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
5284
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is not a scalar. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5285
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
5286
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID begins with a numeral. Do not publicly post this error message! %s', 'jetpack' ) , $entity ), $entity );
5287
		}
5288
5289
	    return $registration_response;
5290
	}
5291
	/**
5292
	 * @return bool|WP_Error
5293
	 */
5294
	public static function register() {
5295
		JetpackTracking::record_user_event( 'jpc_register_begin' );
5296
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
5297
		$secrets = Jetpack::generate_secrets( 'register' );
5298
5299 View Code Duplication
		if (
5300
			empty( $secrets['secret_1'] ) ||
5301
			empty( $secrets['secret_2'] ) ||
5302
			empty( $secrets['exp'] )
5303
		) {
5304
			return new Jetpack_Error( 'missing_secrets' );
5305
		}
5306
5307
		// better to try (and fail) to set a higher timeout than this system
5308
		// supports than to have register fail for more users than it should
5309
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
5310
5311
		$gmt_offset = get_option( 'gmt_offset' );
5312
		if ( ! $gmt_offset ) {
5313
			$gmt_offset = 0;
5314
		}
5315
5316
		$stats_options = get_option( 'stats_options' );
5317
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
5318
5319
		$tracks_identity = jetpack_tracks_get_identity( get_current_user_id() );
5320
5321
		$args = array(
5322
			'method'  => 'POST',
5323
			'body'    => array(
5324
				'siteurl'         => site_url(),
5325
				'home'            => home_url(),
5326
				'gmt_offset'      => $gmt_offset,
5327
				'timezone_string' => (string) get_option( 'timezone_string' ),
5328
				'site_name'       => (string) get_option( 'blogname' ),
5329
				'secret_1'        => $secrets['secret_1'],
5330
				'secret_2'        => $secrets['secret_2'],
5331
				'site_lang'       => get_locale(),
5332
				'timeout'         => $timeout,
5333
				'stats_id'        => $stats_id,
5334
				'state'           => get_current_user_id(),
5335
				'_ui'             => $tracks_identity['_ui'],
5336
				'_ut'             => $tracks_identity['_ut'],
5337
				'jetpack_version' => JETPACK__VERSION
5338
			),
5339
			'headers' => array(
5340
				'Accept' => 'application/json',
5341
			),
5342
			'timeout' => $timeout,
5343
		);
5344
5345
		self::apply_activation_source_to_args( $args['body'] );
5346
5347
		$response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
5348
5349
		// Make sure the response is valid and does not contain any Jetpack errors
5350
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
5351
		if ( is_wp_error( $registration_details ) ) {
5352
			return $registration_details;
5353
		} elseif ( ! $registration_details ) {
5354
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
5355
		}
5356
5357 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
5358
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
5359
		}
5360
5361
		if ( isset( $registration_details->jetpack_public ) ) {
5362
			$jetpack_public = (int) $registration_details->jetpack_public;
5363
		} else {
5364
			$jetpack_public = false;
5365
		}
5366
5367
		Jetpack_Options::update_options(
5368
			array(
5369
				'id'         => (int)    $registration_details->jetpack_id,
5370
				'blog_token' => (string) $registration_details->jetpack_secret,
5371
				'public'     => $jetpack_public,
5372
			)
5373
		);
5374
5375
		/**
5376
		 * Fires when a site is registered on WordPress.com.
5377
		 *
5378
		 * @since 3.7.0
5379
		 *
5380
		 * @param int $json->jetpack_id Jetpack Blog ID.
5381
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5382
		 * @param int|bool $jetpack_public Is the site public.
5383
		 */
5384
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5385
5386
		// Initialize Jump Start for the first and only time.
5387
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5388
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5389
5390
			$jetpack = Jetpack::init();
5391
5392
			$jetpack->stat( 'jumpstart', 'unique-views' );
5393
			$jetpack->do_stats( 'server_side' );
5394
		};
5395
5396
		return true;
5397
	}
5398
5399
	/**
5400
	 * If the db version is showing something other that what we've got now, bump it to current.
5401
	 *
5402
	 * @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...
5403
	 */
5404
	public static function maybe_set_version_option() {
5405
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5406
		if ( JETPACK__VERSION != $version ) {
5407
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5408
5409
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5410
				/** This action is documented in class.jetpack.php */
5411
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5412
			}
5413
5414
			return true;
5415
		}
5416
		return false;
5417
	}
5418
5419
/* Client Server API */
5420
5421
	/**
5422
	 * Loads the Jetpack XML-RPC client
5423
	 */
5424
	public static function load_xml_rpc_client() {
5425
		require_once ABSPATH . WPINC . '/class-IXR.php';
5426
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5427
	}
5428
5429
	/**
5430
	 * Resets the saved authentication state in between testing requests.
5431
	 */
5432
	public function reset_saved_auth_state() {
5433
		$this->xmlrpc_verification = null;
5434
		$this->rest_authentication_status = null;
5435
	}
5436
5437
	function verify_xml_rpc_signature() {
5438
		if ( $this->xmlrpc_verification ) {
5439
			return $this->xmlrpc_verification;
5440
		}
5441
5442
		// It's not for us
5443
		if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
5444
			return false;
5445
		}
5446
5447
		@list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
5448
		if (
5449
			empty( $token_key )
5450
		||
5451
			empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
5452
		) {
5453
			return false;
5454
		}
5455
5456
		if ( '0' === $user_id ) {
5457
			$token_type = 'blog';
5458
			$user_id = 0;
5459
		} else {
5460
			$token_type = 'user';
5461
			if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
5462
				return false;
5463
			}
5464
			$user_id = (int) $user_id;
5465
5466
			$user = new WP_User( $user_id );
5467
			if ( ! $user || ! $user->exists() ) {
5468
				return false;
5469
			}
5470
		}
5471
5472
		$token = Jetpack_Data::get_access_token( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type integer, but the function expects a boolean.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
5473
		if ( ! $token ) {
5474
			return false;
5475
		}
5476
5477
		$token_check = "$token_key.";
5478
		if ( ! hash_equals( substr( $token->secret, 0, strlen( $token_check ) ), $token_check ) ) {
5479
			return false;
5480
		}
5481
5482
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
5483
5484
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5485
		if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
5486
			$post_data   = $_POST;
5487
			$file_hashes = array();
5488
			foreach ( $post_data as $post_data_key => $post_data_value ) {
5489
				if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
5490
					continue;
5491
				}
5492
				$post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
5493
				$file_hashes[$post_data_key] = $post_data_value;
5494
			}
5495
5496
			foreach ( $file_hashes as $post_data_key => $post_data_value ) {
5497
				unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
5498
				$post_data[$post_data_key] = $post_data_value;
5499
			}
5500
5501
			ksort( $post_data );
5502
5503
			$body = http_build_query( stripslashes_deep( $post_data ) );
5504
		} elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
5505
			$body = file_get_contents( 'php://input' );
5506
		} else {
5507
			$body = null;
5508
		}
5509
5510
		$signature = $jetpack_signature->sign_current_request(
5511
			array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
5512
		);
5513
5514
		if ( ! $signature ) {
5515
			return false;
5516
		} else if ( is_wp_error( $signature ) ) {
5517
			return $signature;
5518
		} else if ( ! hash_equals( $signature, $_GET['signature'] ) ) {
5519
			return false;
5520
		}
5521
5522
		$timestamp = (int) $_GET['timestamp'];
5523
		$nonce     = stripslashes( (string) $_GET['nonce'] );
5524
5525
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5526
			return false;
5527
		}
5528
5529
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5530
		if ( isset( $this->HTTP_RAW_POST_DATA ) || ! empty( $_GET['onboarding'] ) ) {
5531
			if ( ! empty( $_GET['onboarding'] ) ) {
5532
				$jpo = $_GET;
5533
			} else {
5534
				$jpo = json_decode( $this->HTTP_RAW_POST_DATA, true );
5535
			}
5536
5537
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5538
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5539
5540
			if (
5541
				isset( $jpo_user ) && isset( $jpo_token ) &&
5542
				is_email( $jpo_user ) && ctype_alnum( $jpo_token ) &&
5543
				isset( $_GET['rest_route'] ) &&
5544
				self::validate_onboarding_token_action( $jpo_token, $_GET['rest_route'] )
5545
			) {
5546
				$jpUser = get_user_by( 'email', $jpo_user );
5547
				if ( is_a( $jpUser, 'WP_User' ) ) {
5548
					wp_set_current_user( $jpUser->ID );
5549
					$user_can = is_multisite()
5550
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5551
						: current_user_can( 'manage_options' );
5552
					if ( $user_can ) {
5553
						$token_type = 'user';
5554
						$token->external_user_id = $jpUser->ID;
5555
					}
5556
				}
5557
			}
5558
		}
5559
5560
		$this->xmlrpc_verification = array(
5561
			'type'    => $token_type,
5562
			'user_id' => $token->external_user_id,
5563
		);
5564
5565
		return $this->xmlrpc_verification;
5566
	}
5567
5568
	/**
5569
	 * Authenticates XML-RPC and other requests from the Jetpack Server
5570
	 */
5571
	function authenticate_jetpack( $user, $username, $password ) {
5572
		if ( is_a( $user, 'WP_User' ) ) {
5573
			return $user;
5574
		}
5575
5576
		$token_details = $this->verify_xml_rpc_signature();
5577
5578
		if ( ! $token_details || is_wp_error( $token_details ) ) {
5579
			return $user;
5580
		}
5581
5582
		if ( 'user' !== $token_details['type'] ) {
5583
			return $user;
5584
		}
5585
5586
		if ( ! $token_details['user_id'] ) {
5587
			return $user;
5588
		}
5589
5590
		nocache_headers();
5591
5592
		return new WP_User( $token_details['user_id'] );
5593
	}
5594
5595
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5596
	// Uses the existing XMLRPC request signing implementation.
5597
	function wp_rest_authenticate( $user ) {
5598
		if ( ! empty( $user ) ) {
5599
			// Another authentication method is in effect.
5600
			return $user;
5601
		}
5602
5603
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5604
			// Nothing to do for this authentication method.
5605
			return null;
5606
		}
5607
5608
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5609
			// Nothing to do for this authentication method.
5610
			return null;
5611
		}
5612
5613
		// Ensure that we always have the request body available.  At this
5614
		// point, the WP REST API code to determine the request body has not
5615
		// run yet.  That code may try to read from 'php://input' later, but
5616
		// this can only be done once per request in PHP versions prior to 5.6.
5617
		// So we will go ahead and perform this read now if needed, and save
5618
		// the request body where both the Jetpack signature verification code
5619
		// and the WP REST API code can see it.
5620
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5621
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5622
		}
5623
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5624
5625
		// Only support specific request parameters that have been tested and
5626
		// are known to work with signature verification.  A different method
5627
		// can be passed to the WP REST API via the '?_method=' parameter if
5628
		// needed.
5629
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5630
			$this->rest_authentication_status = new WP_Error(
5631
				'rest_invalid_request',
5632
				__( 'This request method is not supported.', 'jetpack' ),
5633
				array( 'status' => 400 )
5634
			);
5635
			return null;
5636
		}
5637
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5638
			$this->rest_authentication_status = new WP_Error(
5639
				'rest_invalid_request',
5640
				__( 'This request method does not support body parameters.', 'jetpack' ),
5641
				array( 'status' => 400 )
5642
			);
5643
			return null;
5644
		}
5645
5646
		$verified = $this->verify_xml_rpc_signature();
5647
5648
		if ( is_wp_error( $verified ) ) {
5649
			$this->rest_authentication_status = $verified;
5650
			return null;
5651
		}
5652
5653
		if (
5654
			$verified &&
5655
			isset( $verified['type'] ) &&
5656
			'user' === $verified['type'] &&
5657
			! empty( $verified['user_id'] )
5658
		) {
5659
			// Authentication successful.
5660
			$this->rest_authentication_status = true;
5661
			return $verified['user_id'];
5662
		}
5663
5664
		// Something else went wrong.  Probably a signature error.
5665
		$this->rest_authentication_status = new WP_Error(
5666
			'rest_invalid_signature',
5667
			__( 'The request is not signed correctly.', 'jetpack' ),
5668
			array( 'status' => 400 )
5669
		);
5670
		return null;
5671
	}
5672
5673
	/**
5674
	 * Report authentication status to the WP REST API.
5675
	 *
5676
	 * @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...
5677
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5678
	 */
5679
	public function wp_rest_authentication_errors( $value ) {
5680
		if ( $value !== null ) {
5681
			return $value;
5682
		}
5683
		return $this->rest_authentication_status;
5684
	}
5685
5686
	function add_nonce( $timestamp, $nonce ) {
5687
		global $wpdb;
5688
		static $nonces_used_this_request = array();
5689
5690
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5691
			return $nonces_used_this_request["$timestamp:$nonce"];
5692
		}
5693
5694
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5695
		$timestamp = (int) $timestamp;
5696
		$nonce     = esc_sql( $nonce );
5697
5698
		// Raw query so we can avoid races: add_option will also update
5699
		$show_errors = $wpdb->show_errors( false );
5700
5701
		$old_nonce = $wpdb->get_row(
5702
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5703
		);
5704
5705
		if ( is_null( $old_nonce ) ) {
5706
			$return = $wpdb->query(
5707
				$wpdb->prepare(
5708
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5709
					"jetpack_nonce_{$timestamp}_{$nonce}",
5710
					time(),
5711
					'no'
5712
				)
5713
			);
5714
		} else {
5715
			$return = false;
5716
		}
5717
5718
		$wpdb->show_errors( $show_errors );
5719
5720
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5721
5722
		return $return;
5723
	}
5724
5725
	/**
5726
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5727
	 * Capture it here so we can verify the signature later.
5728
	 */
5729
	function xmlrpc_methods( $methods ) {
5730
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5731
		return $methods;
5732
	}
5733
5734
	function public_xmlrpc_methods( $methods ) {
5735
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5736
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5737
		}
5738
		return $methods;
5739
	}
5740
5741
	function jetpack_getOptions( $args ) {
5742
		global $wp_xmlrpc_server;
5743
5744
		$wp_xmlrpc_server->escape( $args );
5745
5746
		$username	= $args[1];
5747
		$password	= $args[2];
5748
5749
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5750
			return $wp_xmlrpc_server->error;
5751
		}
5752
5753
		$options = array();
5754
		$user_data = $this->get_connected_user_data();
5755
		if ( is_array( $user_data ) ) {
5756
			$options['jetpack_user_id'] = array(
5757
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5758
				'readonly'      => true,
5759
				'value'         => $user_data['ID'],
5760
			);
5761
			$options['jetpack_user_login'] = array(
5762
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5763
				'readonly'      => true,
5764
				'value'         => $user_data['login'],
5765
			);
5766
			$options['jetpack_user_email'] = array(
5767
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5768
				'readonly'      => true,
5769
				'value'         => $user_data['email'],
5770
			);
5771
			$options['jetpack_user_site_count'] = array(
5772
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5773
				'readonly'      => true,
5774
				'value'         => $user_data['site_count'],
5775
			);
5776
		}
5777
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5778
		$args = stripslashes_deep( $args );
5779
		return $wp_xmlrpc_server->wp_getOptions( $args );
5780
	}
5781
5782
	function xmlrpc_options( $options ) {
5783
		$jetpack_client_id = false;
5784
		if ( self::is_active() ) {
5785
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5786
		}
5787
		$options['jetpack_version'] = array(
5788
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5789
				'readonly'      => true,
5790
				'value'         => JETPACK__VERSION,
5791
		);
5792
5793
		$options['jetpack_client_id'] = array(
5794
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5795
				'readonly'      => true,
5796
				'value'         => $jetpack_client_id,
5797
		);
5798
		return $options;
5799
	}
5800
5801
	public static function clean_nonces( $all = false ) {
5802
		global $wpdb;
5803
5804
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5805
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5806
5807
		if ( true !== $all ) {
5808
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5809
			$sql_args[] = time() - 3600;
5810
		}
5811
5812
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5813
5814
		$sql = $wpdb->prepare( $sql, $sql_args );
5815
5816
		for ( $i = 0; $i < 1000; $i++ ) {
5817
			if ( ! $wpdb->query( $sql ) ) {
5818
				break;
5819
			}
5820
		}
5821
	}
5822
5823
	/**
5824
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5825
	 * SET: state( $key, $value );
5826
	 * GET: $value = state( $key );
5827
	 *
5828
	 * @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...
5829
	 * @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...
5830
	 * @param bool $restate private
5831
	 */
5832
	public static function state( $key = null, $value = null, $restate = false ) {
5833
		static $state = array();
5834
		static $path, $domain;
5835
		if ( ! isset( $path ) ) {
5836
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5837
			$admin_url = Jetpack::admin_url();
5838
			$bits      = parse_url( $admin_url );
5839
5840
			if ( is_array( $bits ) ) {
5841
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5842
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5843
			} else {
5844
				$path = $domain = null;
5845
			}
5846
		}
5847
5848
		// Extract state from cookies and delete cookies
5849
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5850
			$yum = $_COOKIE[ 'jetpackState' ];
5851
			unset( $_COOKIE[ 'jetpackState' ] );
5852
			foreach ( $yum as $k => $v ) {
5853
				if ( strlen( $v ) )
5854
					$state[ $k ] = $v;
5855
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5856
			}
5857
		}
5858
5859
		if ( $restate ) {
5860
			foreach ( $state as $k => $v ) {
5861
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5862
			}
5863
			return;
5864
		}
5865
5866
		// Get a state variable
5867
		if ( isset( $key ) && ! isset( $value ) ) {
5868
			if ( array_key_exists( $key, $state ) )
5869
				return $state[ $key ];
5870
			return null;
5871
		}
5872
5873
		// Set a state variable
5874
		if ( isset ( $key ) && isset( $value ) ) {
5875
			if( is_array( $value ) && isset( $value[0] ) ) {
5876
				$value = $value[0];
5877
			}
5878
			$state[ $key ] = $value;
5879
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5880
		}
5881
	}
5882
5883
	public static function restate() {
5884
		Jetpack::state( null, null, true );
5885
	}
5886
5887
	public static function check_privacy( $file ) {
5888
		static $is_site_publicly_accessible = null;
5889
5890
		if ( is_null( $is_site_publicly_accessible ) ) {
5891
			$is_site_publicly_accessible = false;
5892
5893
			Jetpack::load_xml_rpc_client();
5894
			$rpc = new Jetpack_IXR_Client();
5895
5896
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5897
			if ( $success ) {
5898
				$response = $rpc->getResponse();
5899
				if ( $response ) {
5900
					$is_site_publicly_accessible = true;
5901
				}
5902
			}
5903
5904
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5905
		}
5906
5907
		if ( $is_site_publicly_accessible ) {
5908
			return;
5909
		}
5910
5911
		$module_slug = self::get_module_slug( $file );
5912
5913
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5914
		if ( ! $privacy_checks ) {
5915
			$privacy_checks = $module_slug;
5916
		} else {
5917
			$privacy_checks .= ",$module_slug";
5918
		}
5919
5920
		Jetpack::state( 'privacy_checks', $privacy_checks );
5921
	}
5922
5923
	/**
5924
	 * Helper method for multicall XMLRPC.
5925
	 */
5926
	public static function xmlrpc_async_call() {
5927
		global $blog_id;
5928
		static $clients = array();
5929
5930
		$client_blog_id = is_multisite() ? $blog_id : 0;
5931
5932
		if ( ! isset( $clients[$client_blog_id] ) ) {
5933
			Jetpack::load_xml_rpc_client();
5934
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5935
			if ( function_exists( 'ignore_user_abort' ) ) {
5936
				ignore_user_abort( true );
5937
			}
5938
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5939
		}
5940
5941
		$args = func_get_args();
5942
5943
		if ( ! empty( $args[0] ) ) {
5944
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5945
		} elseif ( is_multisite() ) {
5946
			foreach ( $clients as $client_blog_id => $client ) {
5947
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5948
					continue;
5949
				}
5950
5951
				$switch_success = switch_to_blog( $client_blog_id, true );
5952
				if ( ! $switch_success ) {
5953
					continue;
5954
				}
5955
5956
				flush();
5957
				$client->query();
5958
5959
				restore_current_blog();
5960
			}
5961
		} else {
5962
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5963
				flush();
5964
				$clients[0]->query();
5965
			}
5966
		}
5967
	}
5968
5969
	public static function staticize_subdomain( $url ) {
5970
5971
		// Extract hostname from URL
5972
		$host = parse_url( $url, PHP_URL_HOST );
5973
5974
		// Explode hostname on '.'
5975
		$exploded_host = explode( '.', $host );
5976
5977
		// Retrieve the name and TLD
5978
		if ( count( $exploded_host ) > 1 ) {
5979
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5980
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5981
			// Rebuild domain excluding subdomains
5982
			$domain = $name . '.' . $tld;
5983
		} else {
5984
			$domain = $host;
5985
		}
5986
		// Array of Automattic domains
5987
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5988
5989
		// Return $url if not an Automattic domain
5990
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5991
			return $url;
5992
		}
5993
5994
		if ( is_ssl() ) {
5995
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5996
		}
5997
5998
		srand( crc32( basename( $url ) ) );
5999
		$static_counter = rand( 0, 2 );
6000
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
6001
6002
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
6003
	}
6004
6005
/* JSON API Authorization */
6006
6007
	/**
6008
	 * Handles the login action for Authorizing the JSON API
6009
	 */
6010
	function login_form_json_api_authorization() {
6011
		$this->verify_json_api_authorization_request();
6012
6013
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
6014
6015
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
6016
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
6017
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
6018
	}
6019
6020
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
6021
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
6022
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6023
			return $url;
6024
		}
6025
6026
		$parsed_url = parse_url( $url );
6027
		$url = strtok( $url, '?' );
6028
		$url = "$url?{$_SERVER['QUERY_STRING']}";
6029
		if ( ! empty( $parsed_url['query'] ) )
6030
			$url .= "&{$parsed_url['query']}";
6031
6032
		return $url;
6033
	}
6034
6035
	// Make sure the POSTed request is handled by the same action
6036
	function preserve_action_in_login_form_for_json_api_authorization() {
6037
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6038
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6039
	}
6040
6041
	// If someone logs in to approve API access, store the Access Code in usermeta
6042
	function store_json_api_authorization_token( $user_login, $user ) {
6043
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6044
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6045
		$token = wp_generate_password( 32, false );
6046
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6047
	}
6048
6049
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
6050
	function allow_wpcom_public_api_domain( $domains ) {
6051
		$domains[] = 'public-api.wordpress.com';
6052
		return $domains;
6053
	}
6054
6055
	// Add all wordpress.com environments to the safe redirect whitelist
6056
	function allow_wpcom_environments( $domains ) {
6057
		$domains[] = 'wordpress.com';
6058
		$domains[] = 'wpcalypso.wordpress.com';
6059
		$domains[] = 'horizon.wordpress.com';
6060
		$domains[] = 'calypso.localhost';
6061
		return $domains;
6062
	}
6063
6064
	// Add the Access Code details to the public-api.wordpress.com redirect
6065
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6066
		return add_query_arg(
6067
			urlencode_deep(
6068
				array(
6069
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6070
					'jetpack-user-id' => (int) $user->ID,
6071
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6072
				)
6073
			),
6074
			$redirect_to
6075
		);
6076
	}
6077
6078
6079
	/**
6080
	 * Verifies the request by checking the signature
6081
	 *
6082
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6083
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6084
	 *
6085
	 * @param null|array $environment
6086
	 */
6087
	function verify_json_api_authorization_request( $environment = null ) {
6088
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
6089
6090
		$environment = is_null( $environment )
6091
			? $_REQUEST
6092
			: $environment;
6093
6094
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envToken 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...
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...
6095
		$token = Jetpack_Data::get_access_token( $envUserId );
6096
		if ( ! $token || empty( $token->secret ) ) {
6097
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
6098
		}
6099
6100
		$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' );
6101
6102
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6103
6104
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6105
			$signature = $jetpack_signature->sign_request(
6106
				$environment['token'],
6107
				$environment['timestamp'],
6108
				$environment['nonce'],
6109
				'',
6110
				'GET',
6111
				$environment['jetpack_json_api_original_query'],
6112
				null,
6113
				true
6114
			);
6115
		} else {
6116
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
6117
		}
6118
6119
		if ( ! $signature ) {
6120
			wp_die( $die_error );
6121
		} else if ( is_wp_error( $signature ) ) {
6122
			wp_die( $die_error );
6123
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
6124
			if ( is_ssl() ) {
6125
				// 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
6126
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
6127
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6128
					wp_die( $die_error );
6129
				}
6130
			} else {
6131
				wp_die( $die_error );
6132
			}
6133
		}
6134
6135
		$timestamp = (int) $environment['timestamp'];
6136
		$nonce     = stripslashes( (string) $environment['nonce'] );
6137
6138
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
6139
			// De-nonce the nonce, at least for 5 minutes.
6140
			// 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)
6141
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6142
			if ( $old_nonce_time < time() - 300 ) {
6143
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
6144
			}
6145
		}
6146
6147
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6148
		$data_filters = array(
6149
			'state'        => 'opaque',
6150
			'client_id'    => 'int',
6151
			'client_title' => 'string',
6152
			'client_image' => 'url',
6153
		);
6154
6155
		foreach ( $data_filters as $key => $sanitation ) {
6156
			if ( ! isset( $data->$key ) ) {
6157
				wp_die( $die_error );
6158
			}
6159
6160
			switch ( $sanitation ) {
6161
			case 'int' :
6162
				$this->json_api_authorization_request[$key] = (int) $data->$key;
6163
				break;
6164
			case 'opaque' :
6165
				$this->json_api_authorization_request[$key] = (string) $data->$key;
6166
				break;
6167
			case 'string' :
6168
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
6169
				break;
6170
			case 'url' :
6171
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
6172
				break;
6173
			}
6174
		}
6175
6176
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6177
			wp_die( $die_error );
6178
		}
6179
	}
6180
6181
	function login_message_json_api_authorization( $message ) {
6182
		return '<p class="message">' . sprintf(
6183
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
6184
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6185
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6186
	}
6187
6188
	/**
6189
	 * Get $content_width, but with a <s>twist</s> filter.
6190
	 */
6191
	public static function get_content_width() {
6192
		$content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
6193
		/**
6194
		 * Filter the Content Width value.
6195
		 *
6196
		 * @since 2.2.3
6197
		 *
6198
		 * @param string $content_width Content Width value.
6199
		 */
6200
		return apply_filters( 'jetpack_content_width', $content_width );
6201
	}
6202
6203
	/**
6204
	 * Pings the WordPress.com Mirror Site for the specified options.
6205
	 *
6206
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6207
	 *
6208
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6209
	 */
6210
	public function get_cloud_site_options( $option_names ) {
6211
		$option_names = array_filter( (array) $option_names, 'is_string' );
6212
6213
		Jetpack::load_xml_rpc_client();
6214
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
6215
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6216
		if ( $xml->isError() ) {
6217
			return array(
6218
				'error_code' => $xml->getErrorCode(),
6219
				'error_msg'  => $xml->getErrorMessage(),
6220
			);
6221
		}
6222
		$cloud_site_options = $xml->getResponse();
6223
6224
		return $cloud_site_options;
6225
	}
6226
6227
	/**
6228
	 * Checks if the site is currently in an identity crisis.
6229
	 *
6230
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6231
	 */
6232
	public static function check_identity_crisis() {
6233
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6234
			return false;
6235
		}
6236
6237
		return Jetpack_Options::get_option( 'sync_error_idc' );
6238
	}
6239
6240
	/**
6241
	 * Checks whether the home and siteurl specifically are whitelisted
6242
	 * Written so that we don't have re-check $key and $value params every time
6243
	 * we want to check if this site is whitelisted, for example in footer.php
6244
	 *
6245
	 * @since  3.8.0
6246
	 * @return bool True = already whitelisted False = not whitelisted
6247
	 */
6248
	public static function is_staging_site() {
6249
		$is_staging = false;
6250
6251
		$known_staging = array(
6252
			'urls' => array(
6253
				'#\.staging\.wpengine\.com$#i', // WP Engine
6254
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
6255
				),
6256
			'constants' => array(
6257
				'IS_WPE_SNAPSHOT',      // WP Engine
6258
				'KINSTA_DEV_ENV',       // Kinsta.com
6259
				'WPSTAGECOACH_STAGING', // WP Stagecoach
6260
				'JETPACK_STAGING_MODE', // Generic
6261
				)
6262
			);
6263
		/**
6264
		 * Filters the flags of known staging sites.
6265
		 *
6266
		 * @since 3.9.0
6267
		 *
6268
		 * @param array $known_staging {
6269
		 *     An array of arrays that each are used to check if the current site is staging.
6270
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
6271
		 *     @type array $constants PHP constants of known staging/developement environments.
6272
		 *  }
6273
		 */
6274
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
6275
6276
		if ( isset( $known_staging['urls'] ) ) {
6277
			foreach ( $known_staging['urls'] as $url ){
6278
				if ( preg_match( $url, site_url() ) ) {
6279
					$is_staging = true;
6280
					break;
6281
				}
6282
			}
6283
		}
6284
6285
		if ( isset( $known_staging['constants'] ) ) {
6286
			foreach ( $known_staging['constants'] as $constant ) {
6287
				if ( defined( $constant ) && constant( $constant ) ) {
6288
					$is_staging = true;
6289
				}
6290
			}
6291
		}
6292
6293
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
6294
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
6295
			$is_staging = true;
6296
		}
6297
6298
		/**
6299
		 * Filters is_staging_site check.
6300
		 *
6301
		 * @since 3.9.0
6302
		 *
6303
		 * @param bool $is_staging If the current site is a staging site.
6304
		 */
6305
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
6306
	}
6307
6308
	/**
6309
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6310
	 *
6311
	 * @since 4.4.0
6312
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6313
	 *
6314
	 * @return bool
6315
	 */
6316
	public static function validate_sync_error_idc_option() {
6317
		$is_valid = false;
6318
6319
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6320
		if ( false === $idc_allowed ) {
6321
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6322
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6323
				$json = json_decode( wp_remote_retrieve_body( $response ) );
6324
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
6325
				$transient_duration = HOUR_IN_SECONDS;
6326
			} else {
6327
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6328
				$idc_allowed = '1';
6329
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6330
			}
6331
6332
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6333
		}
6334
6335
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6336
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6337
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6338
			$local_options = self::get_sync_error_idc_option();
6339
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6340
				$is_valid = true;
6341
			}
6342
		}
6343
6344
		/**
6345
		 * Filters whether the sync_error_idc option is valid.
6346
		 *
6347
		 * @since 4.4.0
6348
		 *
6349
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6350
		 */
6351
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6352
6353
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6354
			// Since the option exists, and did not validate, delete it
6355
			Jetpack_Options::delete_option( 'sync_error_idc' );
6356
		}
6357
6358
		return $is_valid;
6359
	}
6360
6361
	/**
6362
	 * Normalizes a url by doing three things:
6363
	 *  - Strips protocol
6364
	 *  - Strips www
6365
	 *  - Adds a trailing slash
6366
	 *
6367
	 * @since 4.4.0
6368
	 * @param string $url
6369
	 * @return WP_Error|string
6370
	 */
6371
	public static function normalize_url_protocol_agnostic( $url ) {
6372
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6373
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6374
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6375
		}
6376
6377
		// Strip www and protocols
6378
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6379
		return $url;
6380
	}
6381
6382
	/**
6383
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6384
	 *
6385
	 * @since 4.4.0
6386
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6387
	 *
6388
	 * @param array $response
6389
	 * @return array Array of the local urls, wpcom urls, and error code
6390
	 */
6391
	public static function get_sync_error_idc_option( $response = array() ) {
6392
		// Since the local options will hit the database directly, store the values
6393
		// in a transient to allow for autoloading and caching on subsequent views.
6394
		$local_options = get_transient( 'jetpack_idc_local' );
6395
		if ( false === $local_options ) {
6396
			require_once JETPACK__PLUGIN_DIR . 'sync/class.jetpack-sync-functions.php';
6397
			$local_options = array(
6398
				'home'    => Jetpack_Sync_Functions::home_url(),
6399
				'siteurl' => Jetpack_Sync_Functions::site_url(),
6400
			);
6401
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6402
		}
6403
6404
		$options = array_merge( $local_options, $response );
6405
6406
		$returned_values = array();
6407
		foreach( $options as $key => $option ) {
6408
			if ( 'error_code' === $key ) {
6409
				$returned_values[ $key ] = $option;
6410
				continue;
6411
			}
6412
6413
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6414
				continue;
6415
			}
6416
6417
			$returned_values[ $key ] = $normalized_url;
6418
		}
6419
6420
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6421
6422
		return $returned_values;
6423
	}
6424
6425
	/**
6426
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6427
	 * If set to true, the site will be put into staging mode.
6428
	 *
6429
	 * @since 4.3.2
6430
	 * @return bool
6431
	 */
6432
	public static function sync_idc_optin() {
6433
		if ( Jetpack_Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6434
			$default = Jetpack_Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6435
		} else {
6436
			$default = ! Jetpack_Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6437
		}
6438
6439
		/**
6440
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6441
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6442
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6443
		 *
6444
		 * @since 4.3.2
6445
		 *
6446
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6447
		 */
6448
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6449
	}
6450
6451
	/**
6452
	 * Maybe Use a .min.css stylesheet, maybe not.
6453
	 *
6454
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6455
	 */
6456
	public static function maybe_min_asset( $url, $path, $plugin ) {
6457
		// Short out on things trying to find actual paths.
6458
		if ( ! $path || empty( $plugin ) ) {
6459
			return $url;
6460
		}
6461
6462
		$path = ltrim( $path, '/' );
6463
6464
		// Strip out the abspath.
6465
		$base = dirname( plugin_basename( $plugin ) );
6466
6467
		// Short out on non-Jetpack assets.
6468
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6469
			return $url;
6470
		}
6471
6472
		// File name parsing.
6473
		$file              = "{$base}/{$path}";
6474
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6475
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6476
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6477
		$extension         = array_shift( $file_name_parts_r );
6478
6479
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6480
			// Already pointing at the minified version.
6481
			if ( 'min' === $file_name_parts_r[0] ) {
6482
				return $url;
6483
			}
6484
6485
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6486
			if ( file_exists( $min_full_path ) ) {
6487
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6488
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6489
				if ( 'css' === $extension ) {
6490
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6491
					self::$min_assets[ $key ] = $path;
6492
				}
6493
			}
6494
		}
6495
6496
		return $url;
6497
	}
6498
6499
	/**
6500
	 * If the asset is minified, let's flag .min as the suffix.
6501
	 *
6502
	 * Attached to `style_loader_src` filter.
6503
	 *
6504
	 * @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...
6505
	 * @param string $handle The registered handle of the script in question.
6506
	 * @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...
6507
	 */
6508
	public static function set_suffix_on_min( $src, $handle ) {
6509
		if ( false === strpos( $src, '.min.css' ) ) {
6510
			return $src;
6511
		}
6512
6513
		if ( ! empty( self::$min_assets ) ) {
6514
			foreach ( self::$min_assets as $file => $path ) {
6515
				if ( false !== strpos( $src, $file ) ) {
6516
					wp_style_add_data( $handle, 'suffix', '.min' );
6517
					return $src;
6518
				}
6519
			}
6520
		}
6521
6522
		return $src;
6523
	}
6524
6525
	/**
6526
	 * Maybe inlines a stylesheet.
6527
	 *
6528
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6529
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6530
	 *
6531
	 * Attached to `style_loader_tag` filter.
6532
	 *
6533
	 * @param string $tag The tag that would link to the external asset.
6534
	 * @param string $handle The registered handle of the script in question.
6535
	 *
6536
	 * @return string
6537
	 */
6538
	public static function maybe_inline_style( $tag, $handle ) {
6539
		global $wp_styles;
6540
		$item = $wp_styles->registered[ $handle ];
6541
6542
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6543
			return $tag;
6544
		}
6545
6546
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6547
			$href = $matches[1];
6548
			// Strip off query string
6549
			if ( $pos = strpos( $href, '?' ) ) {
6550
				$href = substr( $href, 0, $pos );
6551
			}
6552
			// Strip off fragment
6553
			if ( $pos = strpos( $href, '#' ) ) {
6554
				$href = substr( $href, 0, $pos );
6555
			}
6556
		} else {
6557
			return $tag;
6558
		}
6559
6560
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6561
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6562
			return $tag;
6563
		}
6564
6565
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6566
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6567
			// And this isn't the pass that actually deals with the RTL version...
6568
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6569
				// Short out, as the RTL version will deal with it in a moment.
6570
				return $tag;
6571
			}
6572
		}
6573
6574
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6575
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6576
		if ( $css ) {
6577
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6578
			if ( empty( $item->extra['after'] ) ) {
6579
				wp_add_inline_style( $handle, $css );
6580
			} else {
6581
				array_unshift( $item->extra['after'], $css );
6582
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6583
			}
6584
		}
6585
6586
		return $tag;
6587
	}
6588
6589
	/**
6590
	 * Loads a view file from the views
6591
	 *
6592
	 * Data passed in with the $data parameter will be available in the
6593
	 * template file as $data['value']
6594
	 *
6595
	 * @param string $template - Template file to load
6596
	 * @param array $data - Any data to pass along to the template
6597
	 * @return boolean - If template file was found
6598
	 **/
6599
	public function load_view( $template, $data = array() ) {
6600
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6601
6602
		if( file_exists( $views_dir . $template ) ) {
6603
			require_once( $views_dir . $template );
6604
			return true;
6605
		}
6606
6607
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6608
		return false;
6609
	}
6610
6611
	/**
6612
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6613
	 */
6614
	public function deprecated_hooks() {
6615
		global $wp_filter;
6616
6617
		/*
6618
		 * Format:
6619
		 * deprecated_filter_name => replacement_name
6620
		 *
6621
		 * If there is no replacement, use null for replacement_name
6622
		 */
6623
		$deprecated_list = array(
6624
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6625
			'wpl_sharing_2014_1'                                     => null,
6626
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6627
			'jetpack_identity_crisis_options_to_check'               => null,
6628
			'update_option_jetpack_single_user_site'                 => null,
6629
			'audio_player_default_colors'                            => null,
6630
			'add_option_jetpack_featured_images_enabled'             => null,
6631
			'add_option_jetpack_update_details'                      => null,
6632
			'add_option_jetpack_updates'                             => null,
6633
			'add_option_jetpack_network_name'                        => null,
6634
			'add_option_jetpack_network_allow_new_registrations'     => null,
6635
			'add_option_jetpack_network_add_new_users'               => null,
6636
			'add_option_jetpack_network_site_upload_space'           => null,
6637
			'add_option_jetpack_network_upload_file_types'           => null,
6638
			'add_option_jetpack_network_enable_administration_menus' => null,
6639
			'add_option_jetpack_is_multi_site'                       => null,
6640
			'add_option_jetpack_is_main_network'                     => null,
6641
			'add_option_jetpack_main_network_site'                   => null,
6642
			'jetpack_sync_all_registered_options'                    => null,
6643
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6644
			'jetpack_is_post_mailable'                               => null,
6645
			'jetpack_seo_site_host'                                  => null,
6646
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6647
			'jetpack_holiday_snow_option_name'                       => null,
6648
			'jetpack_holiday_chance_of_snow'                         => null,
6649
			'jetpack_holiday_snow_js_url'                            => null,
6650
			'jetpack_is_holiday_snow_season'                         => null,
6651
			'jetpack_holiday_snow_option_updated'                    => null,
6652
			'jetpack_holiday_snowing'                                => null,
6653
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6654
			'jetpack_cache_plans'                                    => null,
6655
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6656
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6657
			'jetpack_enable_site_verification'                       => null,
6658
		);
6659
6660
		// This is a silly loop depth. Better way?
6661
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6662
			if ( has_action( $hook ) ) {
6663
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6664
					foreach( $values AS $hooked ) {
6665
						if ( is_callable( $hooked['function'] ) ) {
6666
							$function_name = 'an anonymous function';
6667
						} else {
6668
							$function_name = $hooked['function'];
6669
						}
6670
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6671
					}
6672
				}
6673
			}
6674
		}
6675
	}
6676
6677
	/**
6678
	 * Converts any url in a stylesheet, to the correct absolute url.
6679
	 *
6680
	 * Considerations:
6681
	 *  - Normal, relative URLs     `feh.png`
6682
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6683
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6684
	 *  - Absolute URLs             `http://domain.com/feh.png`
6685
	 *  - Domain root relative URLs `/feh.png`
6686
	 *
6687
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6688
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6689
	 *
6690
	 * @return mixed|string
6691
	 */
6692
	public static function absolutize_css_urls( $css, $css_file_url ) {
6693
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6694
		$css_dir = dirname( $css_file_url );
6695
		$p       = parse_url( $css_dir );
6696
		$domain  = sprintf(
6697
					'%1$s//%2$s%3$s%4$s',
6698
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6699
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6700
					$p['host'],
6701
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6702
				);
6703
6704
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6705
			$find = $replace = array();
6706
			foreach ( $matches as $match ) {
6707
				$url = trim( $match['path'], "'\" \t" );
6708
6709
				// If this is a data url, we don't want to mess with it.
6710
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6711
					continue;
6712
				}
6713
6714
				// If this is an absolute or protocol-agnostic url,
6715
				// we don't want to mess with it.
6716
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6717
					continue;
6718
				}
6719
6720
				switch ( substr( $url, 0, 1 ) ) {
6721
					case '/':
6722
						$absolute = $domain . $url;
6723
						break;
6724
					default:
6725
						$absolute = $css_dir . '/' . $url;
6726
				}
6727
6728
				$find[]    = $match[0];
6729
				$replace[] = sprintf( 'url("%s")', $absolute );
6730
			}
6731
			$css = str_replace( $find, $replace, $css );
6732
		}
6733
6734
		return $css;
6735
	}
6736
6737
	/**
6738
	 * This methods removes all of the registered css files on the front end
6739
	 * from Jetpack in favor of using a single file. In effect "imploding"
6740
	 * all the files into one file.
6741
	 *
6742
	 * Pros:
6743
	 * - Uses only ONE css asset connection instead of 15
6744
	 * - Saves a minimum of 56k
6745
	 * - Reduces server load
6746
	 * - Reduces time to first painted byte
6747
	 *
6748
	 * Cons:
6749
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6750
	 *		should not cause any issues with themes.
6751
	 * - Plugins/themes dequeuing styles no longer do anything. See
6752
	 *		jetpack_implode_frontend_css filter for a workaround
6753
	 *
6754
	 * For some situations developers may wish to disable css imploding and
6755
	 * instead operate in legacy mode where each file loads seperately and
6756
	 * can be edited individually or dequeued. This can be accomplished with
6757
	 * the following line:
6758
	 *
6759
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6760
	 *
6761
	 * @since 3.2
6762
	 **/
6763
	public function implode_frontend_css( $travis_test = false ) {
6764
		$do_implode = true;
6765
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6766
			$do_implode = false;
6767
		}
6768
6769
		/**
6770
		 * Allow CSS to be concatenated into a single jetpack.css file.
6771
		 *
6772
		 * @since 3.2.0
6773
		 *
6774
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6775
		 */
6776
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6777
6778
		// Do not use the imploded file when default behaviour was altered through the filter
6779
		if ( ! $do_implode ) {
6780
			return;
6781
		}
6782
6783
		// We do not want to use the imploded file in dev mode, or if not connected
6784
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6785
			if ( ! $travis_test ) {
6786
				return;
6787
			}
6788
		}
6789
6790
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6791
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6792
			return;
6793
		}
6794
6795
		/*
6796
		 * Now we assume Jetpack is connected and able to serve the single
6797
		 * file.
6798
		 *
6799
		 * In the future there will be a check here to serve the file locally
6800
		 * or potentially from the Jetpack CDN
6801
		 *
6802
		 * For now:
6803
		 * - Enqueue a single imploded css file
6804
		 * - Zero out the style_loader_tag for the bundled ones
6805
		 * - Be happy, drink scotch
6806
		 */
6807
6808
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6809
6810
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6811
6812
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6813
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6814
	}
6815
6816
	function concat_remove_style_loader_tag( $tag, $handle ) {
6817
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6818
			$tag = '';
6819
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6820
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6821
			}
6822
		}
6823
6824
		return $tag;
6825
	}
6826
6827
	/*
6828
	 * Check the heartbeat data
6829
	 *
6830
	 * Organizes the heartbeat data by severity.  For example, if the site
6831
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6832
	 *
6833
	 * Data will be added to "caution" array, if it either:
6834
	 *  - Out of date Jetpack version
6835
	 *  - Out of date WP version
6836
	 *  - Out of date PHP version
6837
	 *
6838
	 * $return array $filtered_data
6839
	 */
6840
	public static function jetpack_check_heartbeat_data() {
6841
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6842
6843
		$good    = array();
6844
		$caution = array();
6845
		$bad     = array();
6846
6847
		foreach ( $raw_data as $stat => $value ) {
6848
6849
			// Check jetpack version
6850
			if ( 'version' == $stat ) {
6851
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6852
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6853
					continue;
6854
				}
6855
			}
6856
6857
			// Check WP version
6858
			if ( 'wp-version' == $stat ) {
6859
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6860
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6861
					continue;
6862
				}
6863
			}
6864
6865
			// Check PHP version
6866
			if ( 'php-version' == $stat ) {
6867
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6868
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6869
					continue;
6870
				}
6871
			}
6872
6873
			// Check ID crisis
6874
			if ( 'identitycrisis' == $stat ) {
6875
				if ( 'yes' == $value ) {
6876
					$bad[ $stat ] = $value;
6877
					continue;
6878
				}
6879
			}
6880
6881
			// The rest are good :)
6882
			$good[ $stat ] = $value;
6883
		}
6884
6885
		$filtered_data = array(
6886
			'good'    => $good,
6887
			'caution' => $caution,
6888
			'bad'     => $bad
6889
		);
6890
6891
		return $filtered_data;
6892
	}
6893
6894
6895
	/*
6896
	 * This method is used to organize all options that can be reset
6897
	 * without disconnecting Jetpack.
6898
	 *
6899
	 * It is used in class.jetpack-cli.php to reset options
6900
	 *
6901
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6902
	 *
6903
	 * @return array of options to delete.
6904
	 */
6905
	public static function get_jetpack_options_for_reset() {
6906
		return Jetpack_Options::get_options_for_reset();
6907
	}
6908
6909
	/**
6910
	 * Check if an option of a Jetpack module has been updated.
6911
	 *
6912
	 * If any module option has been updated before Jump Start has been dismissed,
6913
	 * update the 'jumpstart' option so we can hide Jump Start.
6914
	 *
6915
	 * @param string $option_name
6916
	 *
6917
	 * @return bool
6918
	 */
6919
	public static function jumpstart_has_updated_module_option( $option_name = '' ) {
6920
		// Bail if Jump Start has already been dismissed
6921
		if ( 'new_connection' !== Jetpack_Options::get_option( 'jumpstart' ) ) {
6922
			return false;
6923
		}
6924
6925
		$jetpack = Jetpack::init();
6926
6927
		// Manual build of module options
6928
		$option_names = self::get_jetpack_options_for_reset();
6929
6930
		if ( in_array( $option_name, $option_names['wp_options'] ) ) {
6931
			Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
6932
6933
			//Jump start is being dismissed send data to MC Stats
6934
			$jetpack->stat( 'jumpstart', 'manual,'.$option_name );
6935
6936
			$jetpack->do_stats( 'server_side' );
6937
		}
6938
6939
	}
6940
6941
	/*
6942
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6943
	 * so we can bring them directly to their site in calypso.
6944
	 *
6945
	 * @param string | url
6946
	 * @return string | url without the guff
6947
	 */
6948
	public static function build_raw_urls( $url ) {
6949
		$strip_http = '/.*?:\/\//i';
6950
		$url = preg_replace( $strip_http, '', $url  );
6951
		$url = str_replace( '/', '::', $url );
6952
		return $url;
6953
	}
6954
6955
	/**
6956
	 * Stores and prints out domains to prefetch for page speed optimization.
6957
	 *
6958
	 * @param mixed $new_urls
6959
	 */
6960
	public static function dns_prefetch( $new_urls = null ) {
6961
		static $prefetch_urls = array();
6962
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6963
			echo "\r\n";
6964
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6965
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6966
			}
6967
		} elseif ( ! empty( $new_urls ) ) {
6968
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6969
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6970
			}
6971
			foreach ( (array) $new_urls as $this_new_url ) {
6972
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6973
			}
6974
			$prefetch_urls = array_unique( $prefetch_urls );
6975
		}
6976
	}
6977
6978
	public function wp_dashboard_setup() {
6979
		if ( self::is_active() ) {
6980
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6981
		}
6982
6983
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6984
			wp_add_dashboard_widget(
6985
				'jetpack_summary_widget',
6986
				esc_html__( 'Site Stats', 'jetpack' ),
6987
				array( __CLASS__, 'dashboard_widget' )
6988
			);
6989
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6990
6991
			// If we're inactive and not in development mode, sort our box to the top.
6992
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6993
				global $wp_meta_boxes;
6994
6995
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6996
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6997
6998
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6999
			}
7000
		}
7001
	}
7002
7003
	/**
7004
	 * @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...
7005
	 * @return mixed
7006
	 */
7007
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7008
		if ( ! is_array( $sorted ) ) {
7009
			return $sorted;
7010
		}
7011
7012
		foreach ( $sorted as $box_context => $ids ) {
7013
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7014
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7015
				continue;
7016
			}
7017
7018
			$ids_array = explode( ',', $ids );
7019
			$key = array_search( 'dashboard_stats', $ids_array );
7020
7021
			if ( false !== $key ) {
7022
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7023
				$ids_array[ $key ] = 'jetpack_summary_widget';
7024
				$sorted[ $box_context ] = implode( ',', $ids_array );
7025
				// We've found it, stop searching, and just return.
7026
				break;
7027
			}
7028
		}
7029
7030
		return $sorted;
7031
	}
7032
7033
	public static function dashboard_widget() {
7034
		/**
7035
		 * Fires when the dashboard is loaded.
7036
		 *
7037
		 * @since 3.4.0
7038
		 */
7039
		do_action( 'jetpack_dashboard_widget' );
7040
	}
7041
7042
	public static function dashboard_widget_footer() {
7043
		?>
7044
		<footer>
7045
7046
		<div class="protect">
7047
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
7048
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
7049
				<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>
7050
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
7051
				<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' ); ?>">
7052
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
7053
				</a>
7054
			<?php else : ?>
7055
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
7056
			<?php endif; ?>
7057
		</div>
7058
7059
		<div class="akismet">
7060
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7061
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
7062
				<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>
7063
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7064
				<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">
7065
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
7066
				</a>
7067
			<?php else : ?>
7068
				<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>
7069
			<?php endif; ?>
7070
		</div>
7071
7072
		</footer>
7073
		<?php
7074
	}
7075
7076
	/**
7077
	 * Return string containing the Jetpack logo.
7078
	 *
7079
	 * @since 3.9.0
7080
	 *
7081
	 * @return string
7082
	 */
7083
	public static function get_jp_emblem() {
7084
		return '<svg id="jetpack-logo__icon" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 32 32"><path fill="#00BE28" d="M16,0C7.2,0,0,7.2,0,16s7.2,16,16,16c8.8,0,16-7.2,16-16S24.8,0,16,0z M15.2,18.7h-8l8-15.5V18.7z M16.8,28.8 V13.3h8L16.8,28.8z"/></svg>';
7085
	}
7086
7087
	/*
7088
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7089
	 */
7090
	function jetpack_icon_user_connected( $columns ) {
7091
		$columns['user_jetpack'] = '';
7092
		return $columns;
7093
	}
7094
7095
	/*
7096
	 * Show Jetpack icon if the user is linked.
7097
	 */
7098
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7099
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
7100
			$emblem_html = sprintf(
7101
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7102
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7103
				Jetpack::get_jp_emblem()
7104
			);
7105
			return $emblem_html;
7106
		}
7107
7108
		return $val;
7109
	}
7110
7111
	/*
7112
	 * Style the Jetpack user column
7113
	 */
7114
	function jetpack_user_col_style() {
7115
		global $current_screen;
7116
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
7117
			<style>
7118
				.fixed .column-user_jetpack {
7119
					width: 21px;
7120
				}
7121
				.jp-emblem-user-admin svg {
7122
					width: 20px;
7123
					height: 20px;
7124
				}
7125
				.jp-emblem-user-admin path {
7126
					fill: #00BE28;
7127
				}
7128
			</style>
7129
		<?php }
7130
	}
7131
7132
	/**
7133
	 * Checks if Akismet is active and working.
7134
	 *
7135
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7136
	 * that implied usage of methods present since more recent version.
7137
	 * See https://github.com/Automattic/jetpack/pull/9585
7138
	 *
7139
	 * @since  5.1.0
7140
	 *
7141
	 * @return bool True = Akismet available. False = Aksimet not available.
7142
	 */
7143
	public static function is_akismet_active() {
7144
		if ( method_exists( 'Akismet' , 'http_post' ) ) {
7145
			$akismet_key = Akismet::get_api_key();
7146
			if ( ! $akismet_key ) {
7147
				return false;
7148
			}
7149
			$cached_key_verification = get_transient( 'jetpack_akismet_key_is_valid' );
7150
7151
			// We cache the result of the Akismet key verification for ten minutes.
7152
			if ( in_array( $cached_key_verification, array( 'valid', 'invalid' ) ) ) {
7153
				$akismet_key_state = $cached_key_verification;
7154
			} else {
7155
				$akismet_key_state = Akismet::verify_key( $akismet_key );
7156
				if ( 'failed' === $akismet_key_state ) {
7157
					return false;
7158
				}
7159
				set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7160
			}
7161
7162
			return ( 'valid' === $akismet_key_state );
7163
		}
7164
		return false;
7165
	}
7166
7167
	/**
7168
	 * Checks if one or more function names is in debug_backtrace
7169
	 *
7170
	 * @param $names Mixed string name of function or array of string names of functions
7171
	 *
7172
	 * @return bool
7173
	 */
7174
	public static function is_function_in_backtrace( $names ) {
7175
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.PHP.NewFunctionParameters.debug_backtrace_optionsFound
7176
		if ( ! is_array( $names ) ) {
7177
			$names = array( $names );
7178
		}
7179
		$names_as_keys = array_flip( $names );
7180
7181
		//Do check in constant O(1) time for PHP5.5+
7182
		if ( function_exists( 'array_column' ) ) {
7183
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.PHP.NewFunctions.array_columnFound
7184
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
7185
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
7186
			return ! empty ( $intersection );
7187
		}
7188
7189
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
7190
		foreach ( $backtrace as $call ) {
7191
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
7192
				return true;
7193
			}
7194
		}
7195
		return false;
7196
	}
7197
7198
	/**
7199
	 * Given a minified path, and a non-minified path, will return
7200
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7201
	 *
7202
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7203
	 * root Jetpack directory.
7204
	 *
7205
	 * @since 5.6.0
7206
	 *
7207
	 * @param string $min_path
7208
	 * @param string $non_min_path
7209
	 * @return string The URL to the file
7210
	 */
7211
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7212
		$path = ( Jetpack_Constants::is_defined( 'SCRIPT_DEBUG' ) && Jetpack_Constants::get_constant( 'SCRIPT_DEBUG' ) )
7213
			? $non_min_path
7214
			: $min_path;
7215
7216
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
7217
	}
7218
7219
	/**
7220
	 * Checks for whether Jetpack Rewind is enabled.
7221
	 * Will return true if the state of Rewind is anything except "unavailable".
7222
	 * @return bool|int|mixed
7223
	 */
7224
	public static function is_rewind_enabled() {
7225
		if ( ! Jetpack::is_active() ) {
7226
			return false;
7227
		}
7228
7229
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7230
		if ( false === $rewind_enabled ) {
7231
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7232
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7233
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7234
				&& ! empty( $rewind_data['state'] )
7235
				&& 'active' === $rewind_data['state'] )
7236
				? 1
7237
				: 0;
7238
7239
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7240
		}
7241
		return $rewind_enabled;
7242
	}
7243
7244
	/**
7245
	 * Checks whether or not TOS has been agreed upon.
7246
	 * Will return true if a user has clicked to register, or is already connected.
7247
	 */
7248
	public static function jetpack_tos_agreed() {
7249
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
7250
	}
7251
7252
	/**
7253
	 * Handles activating default modules as well general cleanup for the new connection.
7254
	 *
7255
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7256
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7257
	 * @param boolean $send_state_messages          Whether to send state messages.
7258
	 * @return void
7259
	 */
7260
	public static function handle_post_authorization_actions(
7261
		$activate_sso = false,
7262
		$redirect_on_activation_error = false,
7263
		$send_state_messages = true
7264
	) {
7265
		$other_modules = $activate_sso
7266
			? array( 'sso' )
7267
			: array();
7268
7269
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7270
			Jetpack::delete_active_modules();
7271
7272
			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...
7273
		} else {
7274
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7275
		}
7276
7277
		// Since this is a fresh connection, be sure to clear out IDC options
7278
		Jetpack_IDC::clear_all_idc_options();
7279
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
7280
7281
		// Start nonce cleaner
7282
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
7283
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
7284
7285
		if ( $send_state_messages ) {
7286
			Jetpack::state( 'message', 'authorized' );
7287
		}
7288
	}
7289
7290
	/**
7291
	 * Returns a boolean for whether backups UI should be displayed or not.
7292
	 *
7293
	 * @return bool Should backups UI be displayed?
7294
	 */
7295
	public static function show_backups_ui() {
7296
		/**
7297
		 * Whether UI for backups should be displayed.
7298
		 *
7299
		 * @since 6.5.0
7300
		 *
7301
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7302
		 */
7303
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7304
	}
7305
}
7306