Completed
Push — master ( 121955...8f9c37 )
by Jon
121:30 queued 114:21
created

Jetpack::setup_wp_i18n_locale_data()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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