Completed
Push — branch-6.8-built ( ab1229...17d608 )
by Jeremy
15:49 queued 07:50
created

Jetpack::is_akismet_active()   B

Complexity

Conditions 9
Paths 11

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

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