Completed
Push — add/bail-on-unsupported-wp ( c702b0...29ae98 )
by
unknown
14:04 queued 07:10
created

Jetpack::validate_onboarding_token_action()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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