Completed
Push — update/ci-node-install ( 98b6b4...30db8c )
by
unknown
07:10
created

Jetpack::is_function_in_backtrace()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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