Completed
Push — add/user-authentication ( 34ed8f...93b97f )
by
unknown
288:07 queued 279:09
created

class.jetpack.php (72 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Connection\Client;
5
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
6
use Automattic\Jetpack\Connection\REST_Connector as REST_Connector;
7
use Automattic\Jetpack\Connection\XMLRPC_Connector as XMLRPC_Connector;
8
use Automattic\Jetpack\Constants;
9
use Automattic\Jetpack\Tracking;
10
11
/*
12
Options:
13
jetpack_options (array)
14
	An array of options.
15
	@see Jetpack_Options::get_option_names()
16
17
jetpack_register (string)
18
	Temporary verification secrets.
19
20
jetpack_activated (int)
21
	1: the plugin was activated normally
22
	2: the plugin was activated on this site because of a network-wide activation
23
	3: the plugin was auto-installed
24
	4: the plugin was manually disconnected (but is still installed)
25
26
jetpack_active_modules (array)
27
	Array of active module slugs.
28
29
jetpack_do_activate (bool)
30
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
31
*/
32
33
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
34
35
class Jetpack {
36
	public $xmlrpc_server = null;
37
38
	private $xmlrpc_verification = null;
39
	private $rest_authentication_status = null;
40
41
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
42
43
	private $tracking;
44
45
	/**
46
	 * @var array The handles of styles that are concatenated into jetpack.css.
47
	 *
48
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
49
	 */
50
	public $concatenated_style_handles = array(
51
		'jetpack-carousel',
52
		'grunion.css',
53
		'the-neverending-homepage',
54
		'jetpack_likes',
55
		'jetpack_related-posts',
56
		'sharedaddy',
57
		'jetpack-slideshow',
58
		'presentations',
59
		'quiz',
60
		'jetpack-subscriptions',
61
		'jetpack-responsive-videos-style',
62
		'jetpack-social-menu',
63
		'tiled-gallery',
64
		'jetpack_display_posts_widget',
65
		'gravatar-profile-widget',
66
		'goodreads-widget',
67
		'jetpack_social_media_icons_widget',
68
		'jetpack-top-posts-widget',
69
		'jetpack_image_widget',
70
		'jetpack-my-community-widget',
71
		'jetpack-authors-widget',
72
		'wordads',
73
		'eu-cookie-law-style',
74
		'flickr-widget-style',
75
		'jetpack-search-widget',
76
		'jetpack-simple-payments-widget-style',
77
		'jetpack-widget-social-icons-styles',
78
	);
79
80
	/**
81
	 * Contains all assets that have had their URL rewritten to minified versions.
82
	 *
83
	 * @var array
84
	 */
85
	static $min_assets = array();
86
87
	public $plugins_to_deactivate = array(
88
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
89
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
90
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
91
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
92
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
93
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
94
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
95
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
96
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
97
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
98
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
99
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
100
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
101
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
102
	);
103
104
	static $capability_translations = array(
105
		'administrator' => 'manage_options',
106
		'editor'        => 'edit_others_posts',
107
		'author'        => 'publish_posts',
108
		'contributor'   => 'edit_posts',
109
		'subscriber'    => 'read',
110
	);
111
112
	/**
113
	 * Map of modules that have conflicts with plugins and should not be auto-activated
114
	 * if the plugins are active.  Used by filter_default_modules
115
	 *
116
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
117
	 * change `module-slug` and add this to your plugin:
118
	 *
119
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
120
	 * function my_jetpack_get_default_modules( $modules ) {
121
	 *     return array_diff( $modules, array( 'module-slug' ) );
122
	 * }
123
	 *
124
	 * @var array
125
	 */
126
	private $conflicting_plugins = array(
127
		'comments'          => array(
128
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
129
			'Disqus'                               => 'disqus-comment-system/disqus.php',
130
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
131
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
132
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
133
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
134
		),
135
		'comment-likes' => array(
136
			'Epoch'                                => 'epoch/plugincore.php',
137
		),
138
		'contact-form'      => array(
139
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
140
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
141
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
142
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
143
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
144
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
145
		),
146
		'minileven'         => array(
147
			'WPtouch'                              => 'wptouch/wptouch.php',
148
		),
149
		'latex'             => array(
150
			'LaTeX for WordPress'                  => 'latex/latex.php',
151
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
152
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
153
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
154
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
155
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
156
		),
157
		'protect'           => array(
158
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
159
			'Captcha'                              => 'captcha/captcha.php',
160
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
161
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
162
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
163
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
164
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
165
			'Security-protection'                  => 'security-protection/security-protection.php',
166
			'Login Security'                       => 'login-security/login-security.php',
167
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
168
			'Wordfence Security'                   => 'wordfence/wordfence.php',
169
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
170
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
171
		),
172
		'random-redirect'   => array(
173
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
174
		),
175
		'related-posts'     => array(
176
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
177
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
178
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
179
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
180
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
181
			'outbrain'                             => 'outbrain/outbrain.php',
182
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
183
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
184
		),
185
		'sharedaddy'        => array(
186
			'AddThis'                              => 'addthis/addthis_social_widget.php',
187
			'Add To Any'                           => 'add-to-any/add-to-any.php',
188
			'ShareThis'                            => 'share-this/sharethis.php',
189
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
190
		),
191
		'seo-tools' => array(
192
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
193
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
194
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
195
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
196
			'The SEO Framework'                    => 'autodescription/autodescription.php',
197
		),
198
		'verification-tools' => array(
199
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
200
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
201
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
202
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
203
			'The SEO Framework'                    => 'autodescription/autodescription.php',
204
		),
205
		'widget-visibility' => array(
206
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
207
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
208
		),
209
		'sitemaps' => array(
210
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
211
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
212
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
213
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
214
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
215
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'                    => 'autodescription/autodescription.php',
220
			'Sitemap'                              => 'sitemap/sitemap.php',
221
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
222
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
223
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
224
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
225
		),
226
		'lazy-images' => array(
227
			'Lazy Load'              => 'lazy-load/lazy-load.php',
228
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
229
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
230
		),
231
	);
232
233
	/**
234
	 * Plugins for which we turn off our Facebook OG Tags implementation.
235
	 *
236
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
237
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
238
	 *
239
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
240
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
241
	 */
242
	private $open_graph_conflicting_plugins = array(
243
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
244
		                                                         // 2 Click Social Media Buttons
245
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
246
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
247
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
248
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
249
		                                                         // Open Graph Meta Tags by Heateor
250
		'facebook/facebook.php',                                 // Facebook (official plugin)
251
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
252
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
253
		                                                         // Facebook Featured Image & OG Meta Tags
254
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
255
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
256
		                                                         // Facebook Open Graph Meta Tags for WordPress
257
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
258
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
259
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
260
		                                                         // Fedmich's Facebook Open Graph Meta
261
		'network-publisher/networkpub.php',                      // Network Publisher
262
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
263
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
264
		                                                         // NextScripts SNAP
265
		'og-tags/og-tags.php',                                   // OG Tags
266
		'opengraph/opengraph.php',                               // Open Graph
267
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
268
		                                                         // Open Graph Protocol Framework
269
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
270
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
271
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
272
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
273
		'sharepress/sharepress.php',                             // SharePress
274
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
275
		'social-discussions/social-discussions.php',             // Social Discussions
276
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
277
		'socialize/socialize.php',                               // Socialize
278
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
279
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
280
		                                                         // Tweet, Like, Google +1 and Share
281
		'wordbooker/wordbooker.php',                             // Wordbooker
282
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
283
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
284
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
285
		                                                         // WP Facebook Like Send & Open Graph Meta
286
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
287
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
288
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
289
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
290
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
291
	);
292
293
	/**
294
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
295
	 */
296
	private $twitter_cards_conflicting_plugins = array(
297
	//	'twitter/twitter.php',                       // The official one handles this on its own.
298
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
299
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
300
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
301
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
302
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
303
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
304
		'twitter-cards/twitter-cards.php',           // Twitter Cards
305
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
306
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
307
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
308
	);
309
310
	/**
311
	 * Message to display in admin_notice
312
	 * @var string
313
	 */
314
	public $message = '';
315
316
	/**
317
	 * Error to display in admin_notice
318
	 * @var string
319
	 */
320
	public $error = '';
321
322
	/**
323
	 * Modules that need more privacy description.
324
	 * @var string
325
	 */
326
	public $privacy_checks = '';
327
328
	/**
329
	 * Stats to record once the page loads
330
	 *
331
	 * @var array
332
	 */
333
	public $stats = array();
334
335
	/**
336
	 * Jetpack_Sync object
337
	 */
338
	public $sync;
339
340
	/**
341
	 * Verified data for JSON authorization request
342
	 */
343
	public $json_api_authorization_request = array();
344
345
	/**
346
	 * @var \Automattic\Jetpack\Connection\Manager
347
	 */
348
	protected $connection_manager;
349
350
	/**
351
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
352
	 */
353
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
354
355
	/**
356
	 * Holds the singleton instance of this class
357
	 * @since 2.3.3
358
	 * @var Jetpack
359
	 */
360
	static $instance = false;
361
362
	/**
363
	 * Singleton
364
	 * @static
365
	 */
366
	public static function init() {
367
		if ( ! self::$instance ) {
368
			self::$instance = new Jetpack;
369
370
			self::$instance->plugin_upgrade();
371
		}
372
373
		return self::$instance;
374
	}
375
376
	/**
377
	 * Must never be called statically
378
	 */
379
	function plugin_upgrade() {
380
		if ( Jetpack::is_active() ) {
381
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
382
			if ( JETPACK__VERSION != $version ) {
383
				// Prevent multiple upgrades at once - only a single process should trigger
384
				// an upgrade to avoid stampedes
385
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
386
					return;
387
				}
388
389
				// Set a short lock to prevent multiple instances of the upgrade
390
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
391
392
				// check which active modules actually exist and remove others from active_modules list
393
				$unfiltered_modules = Jetpack::get_active_modules();
394
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
395
				if ( array_diff( $unfiltered_modules, $modules ) ) {
396
					Jetpack::update_active_modules( $modules );
397
				}
398
399
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
400
401
				// Upgrade to 4.3.0
402
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
403
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
404
				}
405
406
				// Make sure Markdown for posts gets turned back on
407
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
408
					update_option( 'wpcom_publish_posts_with_markdown', true );
409
				}
410
411
				if ( did_action( 'wp_loaded' ) ) {
412
					self::upgrade_on_load();
413
				} else {
414
					add_action(
415
						'wp_loaded',
416
						array( __CLASS__, 'upgrade_on_load' )
417
					);
418
				}
419
			}
420
		}
421
	}
422
423
	/**
424
	 * Runs upgrade routines that need to have modules loaded.
425
	 */
426
	static function upgrade_on_load() {
427
428
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
429
		// This can happen in case Jetpack has been just upgraded and is
430
		// being initialized late during the page load. In this case we wait
431
		// until the next proper admin page load with Jetpack active.
432
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
433
			delete_transient( self::$plugin_upgrade_lock_key );
434
435
			return;
436
		}
437
438
		Jetpack::maybe_set_version_option();
439
440
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
441
			Jetpack_Widget_Conditions::migrate_post_type_rules();
442
		}
443
444
		if (
445
			class_exists( 'Jetpack_Sitemap_Manager' )
446
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
447
		) {
448
			do_action( 'jetpack_sitemaps_purge_data' );
449
		}
450
451
		delete_transient( self::$plugin_upgrade_lock_key );
452
	}
453
454
	/**
455
	 * Saves all the currently active modules to options.
456
	 * Also fires Action hooks for each newly activated and deactivated module.
457
	 *
458
	 * @param $modules Array Array of active modules to be saved in options.
459
	 *
460
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
The doc-type $success could not be parsed: Unknown type name "$success" 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...
461
	 */
462
	static function update_active_modules( $modules ) {
463
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
464
		$active_modules       = Jetpack::get_active_modules();
465
		$new_active_modules   = array_diff( $modules, $current_modules );
466
		$new_inactive_modules = array_diff( $active_modules, $modules );
467
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
468
		$reindexed_modules    = array_values( $new_current_modules );
469
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
470
471
		foreach ( $new_active_modules as $module ) {
472
			/**
473
			 * Fires when a specific module is activated.
474
			 *
475
			 * @since 1.9.0
476
			 *
477
			 * @param string $module Module slug.
478
			 * @param boolean $success whether the module was activated. @since 4.2
479
			 */
480
			do_action( 'jetpack_activate_module', $module, $success );
481
			/**
482
			 * Fires when a module is activated.
483
			 * The dynamic part of the filter, $module, is the module slug.
484
			 *
485
			 * @since 1.9.0
486
			 *
487
			 * @param string $module Module slug.
488
			 */
489
			do_action( "jetpack_activate_module_$module", $module );
490
		}
491
492
		foreach ( $new_inactive_modules as $module ) {
493
			/**
494
			 * Fired after a module has been deactivated.
495
			 *
496
			 * @since 4.2.0
497
			 *
498
			 * @param string $module Module slug.
499
			 * @param boolean $success whether the module was deactivated.
500
			 */
501
			do_action( 'jetpack_deactivate_module', $module, $success );
502
			/**
503
			 * Fires when a module is deactivated.
504
			 * The dynamic part of the filter, $module, is the module slug.
505
			 *
506
			 * @since 1.9.0
507
			 *
508
			 * @param string $module Module slug.
509
			 */
510
			do_action( "jetpack_deactivate_module_$module", $module );
511
		}
512
513
		return $success;
514
	}
515
516
	static function delete_active_modules() {
517
		self::update_active_modules( array() );
518
	}
519
520
	/**
521
	 * Constructor.  Initializes WordPress hooks
522
	 */
523
	private function __construct() {
524
		/*
525
		 * Check for and alert any deprecated hooks
526
		 */
527
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
528
529
		/*
530
		 * Enable enhanced handling of previewing sites in Calypso
531
		 */
532
		if ( Jetpack::is_active() ) {
533
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
534
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
535
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
536
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
537
		}
538
539
		if ( self::jetpack_tos_agreed() ) {
540
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
541
			add_action( 'init', array( $tracking, 'init' ) );
542
		}
543
544
		/*
545
		 * Load things that should only be in Network Admin.
546
		 *
547
		 * For now blow away everything else until a more full
548
		 * understanding of what is needed at the network level is
549
		 * available
550
		 */
551
		if ( is_multisite() ) {
552
			Jetpack_Network::init();
553
		}
554
555
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
556
			return function() {
557
				return wp_generate_password( 32, false );
558
			};
559
		} );
560
561
		$this->connection_manager = new Connection_Manager();
562
		$this->connection_manager->init();
563
564
		add_filter(
565
			'jetpack_signature_check_token',
566
			array( __CLASS__, 'verify_onboarding_token' ),
567
			10,
568
			3
569
		);
570
571
		/**
572
		 * Prepare Gutenberg Editor functionality
573
		 */
574
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
575
		Jetpack_Gutenberg::init();
576
		Jetpack_Gutenberg::load_independent_blocks();
577
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
578
579
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
580
581
		// Unlink user before deleting the user from .com
582
		add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
583
		add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
584
585
		if ( Jetpack::is_active() ) {
586
			Jetpack_Heartbeat::init();
587
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
588
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
589
				Jetpack_Search_Performance_Logger::init();
590
			}
591
		}
592
593
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
594
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
595
596
		add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
597
		if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
598
			wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
599
		}
600
601
		add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
602
603
		add_action( 'admin_init', array( $this, 'admin_init' ) );
604
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
605
606
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
607
608
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
609
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
610
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
611
612
		// returns HTTPS support status
613
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
614
615
		// JITM AJAX callback function
616
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
617
618
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
619
620
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
621
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
622
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
623
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
624
625
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
626
627
		/**
628
		 * These actions run checks to load additional files.
629
		 * They check for external files or plugins, so they need to run as late as possible.
630
		 */
631
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
632
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
633
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
634
635
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
636
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
637
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
638
639
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
640
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
641
642
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
643
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
644
645
		// A filter to control all just in time messages
646
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
647
648
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
649
650
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
651
		// We should make sure to only do this for front end links.
652
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
653
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
654
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
655
656
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
657
			//so they point moderation links on emails to Calypso
658
			jetpack_require_lib( 'functions.wp-notify' );
659
		}
660
661
		// Update the Jetpack plan from API on heartbeats
662
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
663
664
		/**
665
		 * This is the hack to concatenate all css files into one.
666
		 * For description and reasoning see the implode_frontend_css method
667
		 *
668
		 * Super late priority so we catch all the registered styles
669
		 */
670
		if( !is_admin() ) {
671
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
672
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
673
		}
674
675
676
		/**
677
		 * These are sync actions that we need to keep track of for jitms
678
		 */
679
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
680
681
		// Actually push the stats on shutdown.
682
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
683
			add_action( 'shutdown', array( $this, 'push_stats' ) );
684
		}
685
686
	}
687
688
	/**
689
	 * This is ported over from the manage module, which has been deprecated and baked in here.
690
	 *
691
	 * @param $domains
692
	 */
693
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
694
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
695
	}
696
697
	/**
698
	 * Return $domains, with 'wordpress.com' appended.
699
	 * This is ported over from the manage module, which has been deprecated and baked in here.
700
	 *
701
	 * @param $domains
702
	 * @return array
703
	 */
704
	function allow_wpcom_domain( $domains ) {
705
		if ( empty( $domains ) ) {
706
			$domains = array();
707
		}
708
		$domains[] = 'wordpress.com';
709
		return array_unique( $domains );
710
	}
711
712
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
713
		$post = get_post( $post_id );
714
715
		if ( empty( $post ) ) {
716
			return $default_url;
717
		}
718
719
		$post_type = $post->post_type;
720
721
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
722
		// https://en.support.wordpress.com/custom-post-types/
723
		$allowed_post_types = array(
724
			'post' => 'post',
725
			'page' => 'page',
726
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
727
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
728
		);
729
730
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
731
			return $default_url;
732
		}
733
734
		$path_prefix = $allowed_post_types[ $post_type ];
735
736
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
737
738
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
739
	}
740
741
	function point_edit_comment_links_to_calypso( $url ) {
742
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
743
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
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...
744
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
745
			Jetpack::build_raw_urls( get_home_url() ),
746
			$query_args['amp;c']
747
		) );
748
	}
749
750
	function jetpack_track_last_sync_callback( $params ) {
751
		/**
752
		 * Filter to turn off jitm caching
753
		 *
754
		 * @since 5.4.0
755
		 *
756
		 * @param bool false Whether to cache just in time messages
757
		 */
758
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
759
			return $params;
760
		}
761
762
		if ( is_array( $params ) && isset( $params[0] ) ) {
763
			$option = $params[0];
764
			if ( 'active_plugins' === $option ) {
765
				// use the cache if we can, but not terribly important if it gets evicted
766
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
767
			}
768
		}
769
770
		return $params;
771
	}
772
773
	function jetpack_connection_banner_callback() {
774
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
775
776
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
777
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
778
			wp_send_json_success();
779
		}
780
781
		wp_die();
782
	}
783
784
	/**
785
	 * The callback for the JITM ajax requests.
786
	 */
787
	function jetpack_jitm_ajax_callback() {
788
		// Check for nonce
789
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
790
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
791
		}
792
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
793
			$module_slug = $_REQUEST['jitmModule'];
794
			Jetpack::log( 'activate', $module_slug );
795
			Jetpack::activate_module( $module_slug, false, false );
796
			Jetpack::state( 'message', 'no_message' );
797
798
			//A Jetpack module is being activated through a JITM, track it
799
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
800
			$this->do_stats( 'server_side' );
801
802
			wp_send_json_success();
803
		}
804
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
805
			// get the hide_jitm options array
806
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
807
			$module_slug = $_REQUEST['jitmModule'];
808
809
			if( ! $jetpack_hide_jitm ) {
810
				$jetpack_hide_jitm = array(
811
					$module_slug => 'hide'
812
				);
813
			} else {
814
				$jetpack_hide_jitm[$module_slug] = 'hide';
815
			}
816
817
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
818
819
			//jitm is being dismissed forever, track it
820
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
821
			$this->do_stats( 'server_side' );
822
823
			wp_send_json_success();
824
		}
825 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
826
			$module_slug = $_REQUEST['jitmModule'];
827
828
			// User went to WordPress.com, track this
829
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
830
			$this->do_stats( 'server_side' );
831
832
			wp_send_json_success();
833
		}
834 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
835
			$track = $_REQUEST['jitmModule'];
836
837
			// User is viewing JITM, track it.
838
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
839
			$this->do_stats( 'server_side' );
840
841
			wp_send_json_success();
842
		}
843
	}
844
845
	/**
846
	 * If there are any stats that need to be pushed, but haven't been, push them now.
847
	 */
848
	function push_stats() {
849
		if ( ! empty( $this->stats ) ) {
850
			$this->do_stats( 'server_side' );
851
		}
852
	}
853
854
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
855
		switch( $cap ) {
856
			case 'jetpack_connect' :
857
			case 'jetpack_reconnect' :
858
				if ( Jetpack::is_development_mode() ) {
859
					$caps = array( 'do_not_allow' );
860
					break;
861
				}
862
				/**
863
				 * Pass through. If it's not development mode, these should match disconnect.
864
				 * Let users disconnect if it's development mode, just in case things glitch.
865
				 */
866
			case 'jetpack_disconnect' :
867
				/**
868
				 * In multisite, can individual site admins manage their own connection?
869
				 *
870
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
871
				 */
872
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
873
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
874
						/**
875
						 * We need to update the option name -- it's terribly unclear which
876
						 * direction the override goes.
877
						 *
878
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
879
						 */
880
						$caps = array( 'do_not_allow' );
881
						break;
882
					}
883
				}
884
885
				$caps = array( 'manage_options' );
886
				break;
887
			case 'jetpack_manage_modules' :
888
			case 'jetpack_activate_modules' :
889
			case 'jetpack_deactivate_modules' :
890
				$caps = array( 'manage_options' );
891
				break;
892
			case 'jetpack_configure_modules' :
893
				$caps = array( 'manage_options' );
894
				break;
895
			case 'jetpack_manage_autoupdates' :
896
				$caps = array(
897
					'manage_options',
898
					'update_plugins',
899
				);
900
				break;
901
			case 'jetpack_network_admin_page':
902
			case 'jetpack_network_settings_page':
903
				$caps = array( 'manage_network_plugins' );
904
				break;
905
			case 'jetpack_network_sites_page':
906
				$caps = array( 'manage_sites' );
907
				break;
908
			case 'jetpack_admin_page' :
909
				if ( Jetpack::is_development_mode() ) {
910
					$caps = array( 'manage_options' );
911
					break;
912
				} else {
913
					$caps = array( 'read' );
914
				}
915
				break;
916
			case 'jetpack_connect_user' :
917
				if ( Jetpack::is_development_mode() ) {
918
					$caps = array( 'do_not_allow' );
919
					break;
920
				}
921
				$caps = array( 'read' );
922
				break;
923
		}
924
		return $caps;
925
	}
926
927
	/**
928
	 * Load language files
929
	 * @action plugins_loaded
930
	 */
931
	public static function plugin_textdomain() {
932
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
933
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
934
	}
935
936
	/**
937
	 * Register assets for use in various modules and the Jetpack admin page.
938
	 *
939
	 * @uses wp_script_is, wp_register_script, plugins_url
940
	 * @action wp_loaded
941
	 * @return null
942
	 */
943
	public function register_assets() {
944
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
945
			wp_register_script(
946
				'spin',
947
				self::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
948
				false,
949
				'1.3'
950
			);
951
		}
952
953
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
954
			wp_register_script(
955
				'jquery.spin',
956
				self::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
957
				array( 'jquery', 'spin' ),
958
				'1.3'
959
			);
960
		}
961
962 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
963
			wp_register_script(
964
				'jetpack-gallery-settings',
965
				self::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
966
				array( 'media-views' ),
967
				'20121225'
968
			);
969
		}
970
971
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
972
			wp_register_script(
973
				'jetpack-twitter-timeline',
974
				self::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
975
				array( 'jquery' ),
976
				'4.0.0',
977
				true
978
			);
979
		}
980
981
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
982
			wp_register_script(
983
				'jetpack-facebook-embed',
984
				self::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
985
				array( 'jquery' ),
986
				null,
987
				true
988
			);
989
990
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
991
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
992
			if ( ! is_numeric( $fb_app_id ) ) {
993
				$fb_app_id = '';
994
			}
995
			wp_localize_script(
996
				'jetpack-facebook-embed',
997
				'jpfbembed',
998
				array(
999
					'appid' => $fb_app_id,
1000
					'locale' => $this->get_locale(),
1001
				)
1002
			);
1003
		}
1004
1005
		/**
1006
		 * As jetpack_register_genericons is by default fired off a hook,
1007
		 * the hook may have already fired by this point.
1008
		 * So, let's just trigger it manually.
1009
		 */
1010
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1011
		jetpack_register_genericons();
1012
1013
		/**
1014
		 * Register the social logos
1015
		 */
1016
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1017
		jetpack_register_social_logos();
1018
1019 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1020
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1021
	}
1022
1023
	/**
1024
	 * Guess locale from language code.
1025
	 *
1026
	 * @param string $lang Language code.
1027
	 * @return string|bool
1028
	 */
1029 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1030
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1031
			return 'en_US';
1032
		}
1033
1034
		if ( ! class_exists( 'GP_Locales' ) ) {
1035
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1036
				return false;
1037
			}
1038
1039
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1040
		}
1041
1042
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1043
			// WP.com: get_locale() returns 'it'
1044
			$locale = GP_Locales::by_slug( $lang );
1045
		} else {
1046
			// Jetpack: get_locale() returns 'it_IT';
1047
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1048
		}
1049
1050
		if ( ! $locale ) {
1051
			return false;
1052
		}
1053
1054
		if ( empty( $locale->facebook_locale ) ) {
1055
			if ( empty( $locale->wp_locale ) ) {
1056
				return false;
1057
			} else {
1058
				// Facebook SDK is smart enough to fall back to en_US if a
1059
				// locale isn't supported. Since supported Facebook locales
1060
				// can fall out of sync, we'll attempt to use the known
1061
				// wp_locale value and rely on said fallback.
1062
				return $locale->wp_locale;
1063
			}
1064
		}
1065
1066
		return $locale->facebook_locale;
1067
	}
1068
1069
	/**
1070
	 * Get the locale.
1071
	 *
1072
	 * @return string|bool
1073
	 */
1074
	function get_locale() {
1075
		$locale = $this->guess_locale_from_lang( get_locale() );
1076
1077
		if ( ! $locale ) {
1078
			$locale = 'en_US';
1079
		}
1080
1081
		return $locale;
1082
	}
1083
1084
	/**
1085
	 * Device Pixels support
1086
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1087
	 */
1088
	function devicepx() {
1089
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1090
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1091
		}
1092
	}
1093
1094
	/**
1095
	 * Return the network_site_url so that .com knows what network this site is a part of.
1096
	 * @param  bool $option
1097
	 * @return string
1098
	 */
1099
	public function jetpack_main_network_site_option( $option ) {
1100
		return network_site_url();
1101
	}
1102
	/**
1103
	 * Network Name.
1104
	 */
1105
	static function network_name( $option = null ) {
1106
		global $current_site;
1107
		return $current_site->site_name;
1108
	}
1109
	/**
1110
	 * Does the network allow new user and site registrations.
1111
	 * @return string
1112
	 */
1113
	static function network_allow_new_registrations( $option = null ) {
1114
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1115
	}
1116
	/**
1117
	 * Does the network allow admins to add new users.
1118
	 * @return boolian
1119
	 */
1120
	static function network_add_new_users( $option = null ) {
1121
		return (bool) get_site_option( 'add_new_users' );
1122
	}
1123
	/**
1124
	 * File upload psace left per site in MB.
1125
	 *  -1 means NO LIMIT.
1126
	 * @return number
1127
	 */
1128
	static function network_site_upload_space( $option = null ) {
1129
		// value in MB
1130
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1131
	}
1132
1133
	/**
1134
	 * Network allowed file types.
1135
	 * @return string
1136
	 */
1137
	static function network_upload_file_types( $option = null ) {
1138
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1139
	}
1140
1141
	/**
1142
	 * Maximum file upload size set by the network.
1143
	 * @return number
1144
	 */
1145
	static function network_max_upload_file_size( $option = null ) {
1146
		// value in KB
1147
		return get_site_option( 'fileupload_maxk', 300 );
1148
	}
1149
1150
	/**
1151
	 * Lets us know if a site allows admins to manage the network.
1152
	 * @return array
1153
	 */
1154
	static function network_enable_administration_menus( $option = null ) {
1155
		return get_site_option( 'menu_items' );
1156
	}
1157
1158
	/**
1159
	 * If a user has been promoted to or demoted from admin, we need to clear the
1160
	 * jetpack_other_linked_admins transient.
1161
	 *
1162
	 * @since 4.3.2
1163
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1164
	 *
1165
	 * @param int    $user_id   The user ID whose role changed.
1166
	 * @param string $role      The new role.
1167
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
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...
1168
	 */
1169
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1170
		if ( 'administrator' == $role
1171
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1172
			|| is_null( $old_roles )
1173
		) {
1174
			delete_transient( 'jetpack_other_linked_admins' );
1175
		}
1176
	}
1177
1178
	/**
1179
	 * Checks to see if there are any other users available to become primary
1180
	 * Users must both:
1181
	 * - Be linked to wpcom
1182
	 * - Be an admin
1183
	 *
1184
	 * @return mixed False if no other users are linked, Int if there are.
1185
	 */
1186
	static function get_other_linked_admins() {
1187
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1188
1189
		if ( false === $other_linked_users ) {
1190
			$admins = get_users( array( 'role' => 'administrator' ) );
1191
			if ( count( $admins ) > 1 ) {
1192
				$available = array();
1193
				foreach ( $admins as $admin ) {
1194
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1195
						$available[] = $admin->ID;
1196
					}
1197
				}
1198
1199
				$count_connected_admins = count( $available );
1200
				if ( count( $available ) > 1 ) {
1201
					$other_linked_users = $count_connected_admins;
1202
				} else {
1203
					$other_linked_users = 0;
1204
				}
1205
			} else {
1206
				$other_linked_users = 0;
1207
			}
1208
1209
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1210
		}
1211
1212
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1213
	}
1214
1215
	/**
1216
	 * Return whether we are dealing with a multi network setup or not.
1217
	 * The reason we are type casting this is because we want to avoid the situation where
1218
	 * the result is false since when is_main_network_option return false it cases
1219
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1220
	 * database which could be set to anything as opposed to what this function returns.
1221
	 * @param  bool  $option
1222
	 *
1223
	 * @return boolean
1224
	 */
1225
	public function is_main_network_option( $option ) {
1226
		// return '1' or ''
1227
		return (string) (bool) Jetpack::is_multi_network();
1228
	}
1229
1230
	/**
1231
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1232
	 *
1233
	 * @param  string  $option
1234
	 * @return boolean
1235
	 */
1236
	public function is_multisite( $option ) {
1237
		return (string) (bool) is_multisite();
1238
	}
1239
1240
	/**
1241
	 * Implemented since there is no core is multi network function
1242
	 * Right now there is no way to tell if we which network is the dominant network on the system
1243
	 *
1244
	 * @since  3.3
1245
	 * @return boolean
1246
	 */
1247
	public static function is_multi_network() {
1248
		global  $wpdb;
1249
1250
		// if we don't have a multi site setup no need to do any more
1251
		if ( ! is_multisite() ) {
1252
			return false;
1253
		}
1254
1255
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1256
		if ( $num_sites > 1 ) {
1257
			return true;
1258
		} else {
1259
			return false;
1260
		}
1261
	}
1262
1263
	/**
1264
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1265
	 * @return null
1266
	 */
1267
	function update_jetpack_main_network_site_option() {
1268
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1269
	}
1270
	/**
1271
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1272
	 *
1273
	 */
1274
	function update_jetpack_network_settings() {
1275
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1276
		// Only sync this info for the main network site.
1277
	}
1278
1279
	/**
1280
	 * Get back if the current site is single user site.
1281
	 *
1282
	 * @return bool
1283
	 */
1284
	public static function is_single_user_site() {
1285
		global $wpdb;
1286
1287 View Code Duplication
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1288
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1289
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1290
		}
1291
		return 1 === (int) $some_users;
1292
	}
1293
1294
	/**
1295
	 * Returns true if the site has file write access false otherwise.
1296
	 * @return string ( '1' | '0' )
1297
	 **/
1298
	public static function file_system_write_access() {
1299
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1300
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1301
		}
1302
1303
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1304
1305
		$filesystem_method = get_filesystem_method();
1306
		if ( $filesystem_method === 'direct' ) {
1307
			return 1;
1308
		}
1309
1310
		ob_start();
1311
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1312
		ob_end_clean();
1313
		if ( $filesystem_credentials_are_stored ) {
1314
			return 1;
1315
		}
1316
		return 0;
1317
	}
1318
1319
	/**
1320
	 * Finds out if a site is using a version control system.
1321
	 * @return string ( '1' | '0' )
1322
	 **/
1323
	public static function is_version_controlled() {
1324
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
1325
		return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
1326
	}
1327
1328
	/**
1329
	 * Determines whether the current theme supports featured images or not.
1330
	 * @return string ( '1' | '0' )
1331
	 */
1332
	public static function featured_images_enabled() {
1333
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1334
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1335
	}
1336
1337
	/**
1338
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1339
	 *
1340
	 * @deprecated 4.7 use get_avatar_url instead.
1341
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1342
	 * @param int $size Size of the avatar image
1343
	 * @param string $default URL to a default image to use if no avatar is available
1344
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1345
	 *
1346
	 * @return array
1347
	 */
1348
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1349
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1350
		return get_avatar_url( $id_or_email, array(
1351
			'size' => $size,
1352
			'default' => $default,
1353
			'force_default' => $force_display,
1354
		) );
1355
	}
1356
1357
	/**
1358
	 * jetpack_updates is saved in the following schema:
1359
	 *
1360
	 * array (
1361
	 *      'plugins'                       => (int) Number of plugin updates available.
1362
	 *      'themes'                        => (int) Number of theme updates available.
1363
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1364
	 *      'translations'                  => (int) Number of translation updates available.
1365
	 *      'total'                         => (int) Total of all available updates.
1366
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1367
	 * )
1368
	 * @return array
1369
	 */
1370
	public static function get_updates() {
1371
		$update_data = wp_get_update_data();
1372
1373
		// Stores the individual update counts as well as the total count.
1374
		if ( isset( $update_data['counts'] ) ) {
1375
			$updates = $update_data['counts'];
1376
		}
1377
1378
		// If we need to update WordPress core, let's find the latest version number.
1379 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1380
			$cur = get_preferred_from_update_core();
1381
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1382
				$updates['wp_update_version'] = $cur->current;
1383
			}
1384
		}
1385
		return isset( $updates ) ? $updates : array();
1386
	}
1387
1388
	public static function get_update_details() {
1389
		$update_details = array(
1390
			'update_core' => get_site_transient( 'update_core' ),
1391
			'update_plugins' => get_site_transient( 'update_plugins' ),
1392
			'update_themes' => get_site_transient( 'update_themes' ),
1393
		);
1394
		return $update_details;
1395
	}
1396
1397
	public static function refresh_update_data() {
1398
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1399
1400
	}
1401
1402
	public static function refresh_theme_data() {
1403
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1404
	}
1405
1406
	/**
1407
	 * Is Jetpack active?
1408
	 */
1409
	public static function is_active() {
1410
		return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1411
	}
1412
1413
	/**
1414
	 * Make an API call to WordPress.com for plan status
1415
	 *
1416
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1417
	 *
1418
	 * @return bool True if plan is updated, false if no update
1419
	 */
1420
	public static function refresh_active_plan_from_wpcom() {
1421
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1422
		return Jetpack_Plan::refresh_from_wpcom();
1423
	}
1424
1425
	/**
1426
	 * Get the plan that this Jetpack site is currently using
1427
	 *
1428
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1429
	 * @return array Active Jetpack plan details.
1430
	 */
1431
	public static function get_active_plan() {
1432
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1433
		return Jetpack_Plan::get();
1434
	}
1435
1436
	/**
1437
	 * Determine whether the active plan supports a particular feature
1438
	 *
1439
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1440
	 * @return bool True if plan supports feature, false if not.
1441
	 */
1442
	public static function active_plan_supports( $feature ) {
1443
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1444
		return Jetpack_Plan::supports( $feature );
1445
	}
1446
1447
	/**
1448
	 * Is Jetpack in development (offline) mode?
1449
	 */
1450 View Code Duplication
	public static function is_development_mode() {
1451
		$development_mode = false;
1452
1453
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1454
			$development_mode = JETPACK_DEV_DEBUG;
1455
		} elseif ( $site_url = site_url() ) {
1456
			$development_mode = false === strpos( $site_url, '.' );
1457
		}
1458
1459
		/**
1460
		 * Filters Jetpack's development mode.
1461
		 *
1462
		 * @see https://jetpack.com/support/development-mode/
1463
		 *
1464
		 * @since 2.2.1
1465
		 *
1466
		 * @param bool $development_mode Is Jetpack's development mode active.
1467
		 */
1468
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1469
		return $development_mode;
1470
	}
1471
1472
	/**
1473
	 * Whether the site is currently onboarding or not.
1474
	 * A site is considered as being onboarded if it currently has an onboarding token.
1475
	 *
1476
	 * @since 5.8
1477
	 *
1478
	 * @access public
1479
	 * @static
1480
	 *
1481
	 * @return bool True if the site is currently onboarding, false otherwise
1482
	 */
1483
	public static function is_onboarding() {
1484
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1485
	}
1486
1487
	/**
1488
	 * Determines reason for Jetpack development mode.
1489
	 */
1490
	public static function development_mode_trigger_text() {
1491
		if ( ! Jetpack::is_development_mode() ) {
1492
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1493
		}
1494
1495
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1496
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1497
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1498
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1499
		} else {
1500
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1501
		}
1502
1503
		return $notice;
1504
1505
	}
1506
	/**
1507
	* Get Jetpack development mode notice text and notice class.
1508
	*
1509
	* Mirrors the checks made in Jetpack::is_development_mode
1510
	*
1511
	*/
1512
	public static function show_development_mode_notice() {
1513 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1514
			$notice = sprintf(
1515
			/* translators: %s is a URL */
1516
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1517
				'https://jetpack.com/support/development-mode/'
1518
			);
1519
1520
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1521
1522
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1523
		}
1524
1525
		// Throw up a notice if using a development version and as for feedback.
1526
		if ( Jetpack::is_development_version() ) {
1527
			/* translators: %s is a URL */
1528
			$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/' );
1529
1530
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1531
		}
1532
		// Throw up a notice if using staging mode
1533
		if ( Jetpack::is_staging_site() ) {
1534
			/* translators: %s is a URL */
1535
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1536
1537
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1538
		}
1539
	}
1540
1541
	/**
1542
	 * Whether Jetpack's version maps to a public release, or a development version.
1543
	 */
1544
	public static function is_development_version() {
1545
		/**
1546
		 * Allows filtering whether this is a development version of Jetpack.
1547
		 *
1548
		 * This filter is especially useful for tests.
1549
		 *
1550
		 * @since 4.3.0
1551
		 *
1552
		 * @param bool $development_version Is this a develoment version of Jetpack?
1553
		 */
1554
		return (bool) apply_filters(
1555
			'jetpack_development_version',
1556
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1557
		);
1558
	}
1559
1560
	/**
1561
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1562
	 */
1563
	public static function is_user_connected( $user_id = false ) {
1564
		return self::connection()->is_user_connected( $user_id );
1565
	}
1566
1567
	/**
1568
	 * Get the wpcom user data of the current|specified connected user.
1569
	 */
1570 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1571
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1572
		if ( ! $user_id ) {
1573
			$user_id = get_current_user_id();
1574
		}
1575
1576
		$transient_key = "jetpack_connected_user_data_$user_id";
1577
1578
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1579
			return $cached_user_data;
1580
		}
1581
1582
		Jetpack::load_xml_rpc_client();
1583
		$xml = new Jetpack_IXR_Client( array(
1584
			'user_id' => $user_id,
1585
		) );
1586
		$xml->query( 'wpcom.getUser' );
1587
		if ( ! $xml->isError() ) {
1588
			$user_data = $xml->getResponse();
1589
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1590
			return $user_data;
1591
		}
1592
1593
		return false;
1594
	}
1595
1596
	/**
1597
	 * Get the wpcom email of the current|specified connected user.
1598
	 */
1599 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1600
		if ( ! $user_id ) {
1601
			$user_id = get_current_user_id();
1602
		}
1603
		Jetpack::load_xml_rpc_client();
1604
		$xml = new Jetpack_IXR_Client( array(
1605
			'user_id' => $user_id,
1606
		) );
1607
		$xml->query( 'wpcom.getUserEmail' );
1608
		if ( ! $xml->isError() ) {
1609
			return $xml->getResponse();
1610
		}
1611
		return false;
1612
	}
1613
1614
	/**
1615
	 * Get the wpcom email of the master user.
1616
	 */
1617
	public static function get_master_user_email() {
1618
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1619
		if ( $master_user_id ) {
1620
			return self::get_connected_user_email( $master_user_id );
1621
		}
1622
		return '';
1623
	}
1624
1625
	function current_user_is_connection_owner() {
1626
		$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
1627
		return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
1628
	}
1629
1630
	/**
1631
	 * Gets current user IP address.
1632
	 *
1633
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1634
	 *
1635
	 * @return string                  Current user IP address.
1636
	 */
1637
	public static function current_user_ip( $check_all_headers = false ) {
1638
		if ( $check_all_headers ) {
1639
			foreach ( array(
1640
				'HTTP_CF_CONNECTING_IP',
1641
				'HTTP_CLIENT_IP',
1642
				'HTTP_X_FORWARDED_FOR',
1643
				'HTTP_X_FORWARDED',
1644
				'HTTP_X_CLUSTER_CLIENT_IP',
1645
				'HTTP_FORWARDED_FOR',
1646
				'HTTP_FORWARDED',
1647
				'HTTP_VIA',
1648
			) as $key ) {
1649
				if ( ! empty( $_SERVER[ $key ] ) ) {
1650
					return $_SERVER[ $key ];
1651
				}
1652
			}
1653
		}
1654
1655
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1656
	}
1657
1658
	/**
1659
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1660
	 */
1661
	function extra_oembed_providers() {
1662
		// Cloudup: https://dev.cloudup.com/#oembed
1663
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1664
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1665
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1666
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1667
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1668
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1669
	}
1670
1671
	/**
1672
	 * Synchronize connected user role changes
1673
	 */
1674
	function user_role_change( $user_id ) {
1675
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
1676
		Jetpack_Sync_Users::user_role_change( $user_id );
1677
	}
1678
1679
	/**
1680
	 * Loads the currently active modules.
1681
	 */
1682
	public static function load_modules() {
1683
		if (
1684
			! self::is_active()
1685
			&& ! self::is_development_mode()
1686
			&& ! self::is_onboarding()
1687
			&& (
1688
				! is_multisite()
1689
				|| ! get_site_option( 'jetpack_protect_active' )
1690
			)
1691
		) {
1692
			return;
1693
		}
1694
1695
		$version = Jetpack_Options::get_option( 'version' );
1696 View Code Duplication
		if ( ! $version ) {
1697
			$version = $old_version = JETPACK__VERSION . ':' . time();
1698
			/** This action is documented in class.jetpack.php */
1699
			do_action( 'updating_jetpack_version', $version, false );
1700
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1701
		}
1702
		list( $version ) = explode( ':', $version );
1703
1704
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1705
1706
		$modules_data = array();
1707
1708
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1709
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1710
			$updated_modules = array();
1711
			foreach ( $modules as $module ) {
1712
				$modules_data[ $module ] = Jetpack::get_module( $module );
1713
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1714
					continue;
1715
				}
1716
1717
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1718
					continue;
1719
				}
1720
1721
				$updated_modules[] = $module;
1722
			}
1723
1724
			$modules = array_diff( $modules, $updated_modules );
1725
		}
1726
1727
		$is_development_mode = Jetpack::is_development_mode();
1728
1729
		foreach ( $modules as $index => $module ) {
1730
			// If we're in dev mode, disable modules requiring a connection
1731
			if ( $is_development_mode ) {
1732
				// Prime the pump if we need to
1733
				if ( empty( $modules_data[ $module ] ) ) {
1734
					$modules_data[ $module ] = Jetpack::get_module( $module );
1735
				}
1736
				// If the module requires a connection, but we're in local mode, don't include it.
1737
				if ( $modules_data[ $module ]['requires_connection'] ) {
1738
					continue;
1739
				}
1740
			}
1741
1742
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1743
				continue;
1744
			}
1745
1746
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1747
				unset( $modules[ $index ] );
1748
				self::update_active_modules( array_values( $modules ) );
1749
				continue;
1750
			}
1751
1752
			/**
1753
			 * Fires when a specific module is loaded.
1754
			 * The dynamic part of the hook, $module, is the module slug.
1755
			 *
1756
			 * @since 1.1.0
1757
			 */
1758
			do_action( 'jetpack_module_loaded_' . $module );
1759
		}
1760
1761
		/**
1762
		 * Fires when all the modules are loaded.
1763
		 *
1764
		 * @since 1.1.0
1765
		 */
1766
		do_action( 'jetpack_modules_loaded' );
1767
1768
		// 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.
1769
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1770
	}
1771
1772
	/**
1773
	 * Check if Jetpack's REST API compat file should be included
1774
	 * @action plugins_loaded
1775
	 * @return null
1776
	 */
1777
	public function check_rest_api_compat() {
1778
		/**
1779
		 * Filters the list of REST API compat files to be included.
1780
		 *
1781
		 * @since 2.2.5
1782
		 *
1783
		 * @param array $args Array of REST API compat files to include.
1784
		 */
1785
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1786
1787
		if ( function_exists( 'bbpress' ) )
1788
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1789
1790
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1791
			require_once $_jetpack_rest_api_compat_include;
1792
	}
1793
1794
	/**
1795
	 * Gets all plugins currently active in values, regardless of whether they're
1796
	 * traditionally activated or network activated.
1797
	 *
1798
	 * @todo Store the result in core's object cache maybe?
1799
	 */
1800
	public static function get_active_plugins() {
1801
		$active_plugins = (array) get_option( 'active_plugins', array() );
1802
1803
		if ( is_multisite() ) {
1804
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1805
			// whereas active_plugins stores them in the values.
1806
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1807
			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...
1808
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1809
			}
1810
		}
1811
1812
		sort( $active_plugins );
1813
1814
		return array_unique( $active_plugins );
1815
	}
1816
1817
	/**
1818
	 * Gets and parses additional plugin data to send with the heartbeat data
1819
	 *
1820
	 * @since 3.8.1
1821
	 *
1822
	 * @return array Array of plugin data
1823
	 */
1824
	public static function get_parsed_plugin_data() {
1825
		if ( ! function_exists( 'get_plugins' ) ) {
1826
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1827
		}
1828
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1829
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1830
		$active_plugins = Jetpack::get_active_plugins();
1831
1832
		$plugins = array();
1833
		foreach ( $all_plugins as $path => $plugin_data ) {
1834
			$plugins[ $path ] = array(
1835
					'is_active' => in_array( $path, $active_plugins ),
1836
					'file'      => $path,
1837
					'name'      => $plugin_data['Name'],
1838
					'version'   => $plugin_data['Version'],
1839
					'author'    => $plugin_data['Author'],
1840
			);
1841
		}
1842
1843
		return $plugins;
1844
	}
1845
1846
	/**
1847
	 * Gets and parses theme data to send with the heartbeat data
1848
	 *
1849
	 * @since 3.8.1
1850
	 *
1851
	 * @return array Array of theme data
1852
	 */
1853
	public static function get_parsed_theme_data() {
1854
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1855
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1856
1857
		$themes = array();
1858
		foreach ( $all_themes as $slug => $theme_data ) {
1859
			$theme_headers = array();
1860
			foreach ( $header_keys as $header_key ) {
1861
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1862
			}
1863
1864
			$themes[ $slug ] = array(
1865
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1866
					'slug' => $slug,
1867
					'theme_root' => $theme_data->get_theme_root_uri(),
1868
					'parent' => $theme_data->parent(),
1869
					'headers' => $theme_headers
1870
			);
1871
		}
1872
1873
		return $themes;
1874
	}
1875
1876
	/**
1877
	 * Checks whether a specific plugin is active.
1878
	 *
1879
	 * We don't want to store these in a static variable, in case
1880
	 * there are switch_to_blog() calls involved.
1881
	 */
1882
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1883
		return in_array( $plugin, self::get_active_plugins() );
1884
	}
1885
1886
	/**
1887
	 * Check if Jetpack's Open Graph tags should be used.
1888
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1889
	 *
1890
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1891
	 * @action plugins_loaded
1892
	 * @return null
1893
	 */
1894
	public function check_open_graph() {
1895
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1896
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1897
		}
1898
1899
		$active_plugins = self::get_active_plugins();
1900
1901
		if ( ! empty( $active_plugins ) ) {
1902
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
1903
				if ( in_array( $plugin, $active_plugins ) ) {
1904
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
1905
					break;
1906
				}
1907
			}
1908
		}
1909
1910
		/**
1911
		 * Allow the addition of Open Graph Meta Tags to all pages.
1912
		 *
1913
		 * @since 2.0.3
1914
		 *
1915
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
1916
		 */
1917
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
1918
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
1919
		}
1920
	}
1921
1922
	/**
1923
	 * Check if Jetpack's Twitter tags should be used.
1924
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
1925
	 *
1926
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1927
	 * @action plugins_loaded
1928
	 * @return null
1929
	 */
1930
	public function check_twitter_tags() {
1931
1932
		$active_plugins = self::get_active_plugins();
1933
1934
		if ( ! empty( $active_plugins ) ) {
1935
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
1936
				if ( in_array( $plugin, $active_plugins ) ) {
1937
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
1938
					break;
1939
				}
1940
			}
1941
		}
1942
1943
		/**
1944
		 * Allow Twitter Card Meta tags to be disabled.
1945
		 *
1946
		 * @since 2.6.0
1947
		 *
1948
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
1949
		 */
1950
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
1951
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
1952
		}
1953
	}
1954
1955
	/**
1956
	 * Allows plugins to submit security reports.
1957
 	 *
1958
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
1959
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
1960
	 * @param array   $args         See definitions above
1961
	 */
1962
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
1963
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
1964
	}
1965
1966
/* Jetpack Options API */
1967
1968
	public static function get_option_names( $type = 'compact' ) {
1969
		return Jetpack_Options::get_option_names( $type );
1970
	}
1971
1972
	/**
1973
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
1974
 	 *
1975
	 * @param string $name    Option name
1976
	 * @param mixed  $default (optional)
1977
	 */
1978
	public static function get_option( $name, $default = false ) {
1979
		return Jetpack_Options::get_option( $name, $default );
1980
	}
1981
1982
	/**
1983
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
1984
 	 *
1985
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
1986
	 * @param string $name  Option name
1987
	 * @param mixed  $value Option value
1988
	 */
1989
	public static function update_option( $name, $value ) {
1990
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
1991
		return Jetpack_Options::update_option( $name, $value );
1992
	}
1993
1994
	/**
1995
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
1996
 	 *
1997
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
1998
	 * @param array $array array( option name => option value, ... )
1999
	 */
2000
	public static function update_options( $array ) {
2001
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2002
		return Jetpack_Options::update_options( $array );
2003
	}
2004
2005
	/**
2006
	 * Deletes the given option.  May be passed multiple option names as an array.
2007
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2008
	 *
2009
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2010
	 * @param string|array $names
2011
	 */
2012
	public static function delete_option( $names ) {
2013
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2014
		return Jetpack_Options::delete_option( $names );
2015
	}
2016
2017
	/**
2018
	 * Enters a user token into the user_tokens option
2019
	 *
2020
	 * @param int $user_id
2021
	 * @param string $token
2022
	 * return bool
2023
	 */
2024
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2025
		// not designed for concurrent updates
2026
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2027
		if ( ! is_array( $user_tokens ) )
2028
			$user_tokens = array();
2029
		$user_tokens[$user_id] = $token;
2030
		if ( $is_master_user ) {
2031
			$master_user = $user_id;
2032
			$options     = compact( 'user_tokens', 'master_user' );
2033
		} else {
2034
			$options = compact( 'user_tokens' );
2035
		}
2036
		return Jetpack_Options::update_options( $options );
2037
	}
2038
2039
	/**
2040
	 * Returns an array of all PHP files in the specified absolute path.
2041
	 * Equivalent to glob( "$absolute_path/*.php" ).
2042
	 *
2043
	 * @param string $absolute_path The absolute path of the directory to search.
2044
	 * @return array Array of absolute paths to the PHP files.
2045
	 */
2046
	public static function glob_php( $absolute_path ) {
2047
		if ( function_exists( 'glob' ) ) {
2048
			return glob( "$absolute_path/*.php" );
2049
		}
2050
2051
		$absolute_path = untrailingslashit( $absolute_path );
2052
		$files = array();
2053
		if ( ! $dir = @opendir( $absolute_path ) ) {
2054
			return $files;
2055
		}
2056
2057
		while ( false !== $file = readdir( $dir ) ) {
2058
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2059
				continue;
2060
			}
2061
2062
			$file = "$absolute_path/$file";
2063
2064
			if ( ! is_file( $file ) ) {
2065
				continue;
2066
			}
2067
2068
			$files[] = $file;
2069
		}
2070
2071
		closedir( $dir );
2072
2073
		return $files;
2074
	}
2075
2076
	public static function activate_new_modules( $redirect = false ) {
2077
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2078
			return;
2079
		}
2080
2081
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2082 View Code Duplication
		if ( ! $jetpack_old_version ) {
2083
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2084
			/** This action is documented in class.jetpack.php */
2085
			do_action( 'updating_jetpack_version', $version, false );
2086
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2087
		}
2088
2089
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2090
2091
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2092
			return;
2093
		}
2094
2095
		$active_modules     = Jetpack::get_active_modules();
2096
		$reactivate_modules = array();
2097
		foreach ( $active_modules as $active_module ) {
2098
			$module = Jetpack::get_module( $active_module );
2099
			if ( ! isset( $module['changed'] ) ) {
2100
				continue;
2101
			}
2102
2103
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2104
				continue;
2105
			}
2106
2107
			$reactivate_modules[] = $active_module;
2108
			Jetpack::deactivate_module( $active_module );
2109
		}
2110
2111
		$new_version = JETPACK__VERSION . ':' . time();
2112
		/** This action is documented in class.jetpack.php */
2113
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2114
		Jetpack_Options::update_options(
2115
			array(
2116
				'version'     => $new_version,
2117
				'old_version' => $jetpack_old_version,
2118
			)
2119
		);
2120
2121
		Jetpack::state( 'message', 'modules_activated' );
2122
		Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
0 ignored issues
show
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...
2123
2124
		if ( $redirect ) {
2125
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2126
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2127
				$page = $_GET['page'];
2128
			}
2129
2130
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2131
			exit;
2132
		}
2133
	}
2134
2135
	/**
2136
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2137
	 * Make sure to tuck away module "library" files in a sub-directory.
2138
	 */
2139
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2140
		static $modules = null;
2141
2142
		if ( ! isset( $modules ) ) {
2143
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2144
			// Use the cache if we're on the front-end and it's available...
2145
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2146
				$modules = $available_modules_option[ JETPACK__VERSION ];
2147
			} else {
2148
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2149
2150
				$modules = array();
2151
2152
				foreach ( $files as $file ) {
2153
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2154
						continue;
2155
					}
2156
2157
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2158
				}
2159
2160
				Jetpack_Options::update_option( 'available_modules', array(
2161
					JETPACK__VERSION => $modules,
2162
				) );
2163
			}
2164
		}
2165
2166
		/**
2167
		 * Filters the array of modules available to be activated.
2168
		 *
2169
		 * @since 2.4.0
2170
		 *
2171
		 * @param array $modules Array of available modules.
2172
		 * @param string $min_version Minimum version number required to use modules.
2173
		 * @param string $max_version Maximum version number required to use modules.
2174
		 */
2175
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2176
2177
		if ( ! $min_version && ! $max_version ) {
2178
			return array_keys( $mods );
2179
		}
2180
2181
		$r = array();
2182
		foreach ( $mods as $slug => $introduced ) {
2183
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2184
				continue;
2185
			}
2186
2187
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2188
				continue;
2189
			}
2190
2191
			$r[] = $slug;
2192
		}
2193
2194
		return $r;
2195
	}
2196
2197
	/**
2198
	 * Default modules loaded on activation.
2199
	 */
2200
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2201
		$return = array();
2202
2203
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2204
			$module_data = Jetpack::get_module( $module );
2205
2206
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2207
				case 'yes' :
2208
					$return[] = $module;
2209
					break;
2210
				case 'public' :
2211
					if ( Jetpack_Options::get_option( 'public' ) ) {
2212
						$return[] = $module;
2213
					}
2214
					break;
2215
				case 'no' :
2216
				default :
2217
					break;
2218
			}
2219
		}
2220
		/**
2221
		 * Filters the array of default modules.
2222
		 *
2223
		 * @since 2.5.0
2224
		 *
2225
		 * @param array $return Array of default modules.
2226
		 * @param string $min_version Minimum version number required to use modules.
2227
		 * @param string $max_version Maximum version number required to use modules.
2228
		 */
2229
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2230
	}
2231
2232
	/**
2233
	 * Checks activated modules during auto-activation to determine
2234
	 * if any of those modules are being deprecated.  If so, close
2235
	 * them out, and add any replacement modules.
2236
	 *
2237
	 * Runs at priority 99 by default.
2238
	 *
2239
	 * This is run late, so that it can still activate a module if
2240
	 * the new module is a replacement for another that the user
2241
	 * currently has active, even if something at the normal priority
2242
	 * would kibosh everything.
2243
	 *
2244
	 * @since 2.6
2245
	 * @uses jetpack_get_default_modules filter
2246
	 * @param array $modules
2247
	 * @return array
2248
	 */
2249
	function handle_deprecated_modules( $modules ) {
2250
		$deprecated_modules = array(
2251
			'debug'            => null,  // Closed out and moved to the debugger library.
2252
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2253
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2254
		);
2255
2256
		// Don't activate SSO if they never completed activating WPCC.
2257
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2258
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2259
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2260
				$deprecated_modules['wpcc'] = null;
2261
			}
2262
		}
2263
2264
		foreach ( $deprecated_modules as $module => $replacement ) {
2265
			if ( Jetpack::is_module_active( $module ) ) {
2266
				self::deactivate_module( $module );
2267
				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...
2268
					$modules[] = $replacement;
2269
				}
2270
			}
2271
		}
2272
2273
		return array_unique( $modules );
2274
	}
2275
2276
	/**
2277
	 * Checks activated plugins during auto-activation to determine
2278
	 * if any of those plugins are in the list with a corresponding module
2279
	 * that is not compatible with the plugin. The module will not be allowed
2280
	 * to auto-activate.
2281
	 *
2282
	 * @since 2.6
2283
	 * @uses jetpack_get_default_modules filter
2284
	 * @param array $modules
2285
	 * @return array
2286
	 */
2287
	function filter_default_modules( $modules ) {
2288
2289
		$active_plugins = self::get_active_plugins();
2290
2291
		if ( ! empty( $active_plugins ) ) {
2292
2293
			// For each module we'd like to auto-activate...
2294
			foreach ( $modules as $key => $module ) {
2295
				// If there are potential conflicts for it...
2296
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2297
					// For each potential conflict...
2298
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2299
						// If that conflicting plugin is active...
2300
						if ( in_array( $plugin, $active_plugins ) ) {
2301
							// Remove that item from being auto-activated.
2302
							unset( $modules[ $key ] );
2303
						}
2304
					}
2305
				}
2306
			}
2307
		}
2308
2309
		return $modules;
2310
	}
2311
2312
	/**
2313
	 * Extract a module's slug from its full path.
2314
	 */
2315
	public static function get_module_slug( $file ) {
2316
		return str_replace( '.php', '', basename( $file ) );
2317
	}
2318
2319
	/**
2320
	 * Generate a module's path from its slug.
2321
	 */
2322
	public static function get_module_path( $slug ) {
2323
		/**
2324
		 * Filters the path of a modules.
2325
		 *
2326
		 * @since 7.4.0
2327
		 *
2328
		 * @param array $return The absolute path to a module's root php file
2329
		 * @param string $slug The module slug
2330
		 */
2331
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2332
	}
2333
2334
	/**
2335
	 * Load module data from module file. Headers differ from WordPress
2336
	 * plugin headers to avoid them being identified as standalone
2337
	 * plugins on the WordPress plugins page.
2338
	 */
2339
	public static function get_module( $module ) {
2340
		$headers = array(
2341
			'name'                      => 'Module Name',
2342
			'description'               => 'Module Description',
2343
			'jumpstart_desc'            => 'Jumpstart Description',
2344
			'sort'                      => 'Sort Order',
2345
			'recommendation_order'      => 'Recommendation Order',
2346
			'introduced'                => 'First Introduced',
2347
			'changed'                   => 'Major Changes In',
2348
			'deactivate'                => 'Deactivate',
2349
			'free'                      => 'Free',
2350
			'requires_connection'       => 'Requires Connection',
2351
			'auto_activate'             => 'Auto Activate',
2352
			'module_tags'               => 'Module Tags',
2353
			'feature'                   => 'Feature',
2354
			'additional_search_queries' => 'Additional Search Queries',
2355
			'plan_classes'              => 'Plans',
2356
		);
2357
2358
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2359
2360
		$mod = Jetpack::get_file_data( $file, $headers );
2361
		if ( empty( $mod['name'] ) ) {
2362
			return false;
2363
		}
2364
2365
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2366
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2367
		$mod['deactivate']              = empty( $mod['deactivate'] );
2368
		$mod['free']                    = empty( $mod['free'] );
2369
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2370
2371
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2372
			$mod['auto_activate'] = 'No';
2373
		} else {
2374
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2375
		}
2376
2377
		if ( $mod['module_tags'] ) {
2378
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2379
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2380
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2381
		} else {
2382
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2383
		}
2384
2385 View Code Duplication
		if ( $mod['plan_classes'] ) {
2386
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2387
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2388
		} else {
2389
			$mod['plan_classes'] = array( 'free' );
2390
		}
2391
2392 View Code Duplication
		if ( $mod['feature'] ) {
2393
			$mod['feature'] = explode( ',', $mod['feature'] );
2394
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2395
		} else {
2396
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2397
		}
2398
2399
		/**
2400
		 * Filters the feature array on a module.
2401
		 *
2402
		 * This filter allows you to control where each module is filtered: Recommended,
2403
		 * Jumpstart, and the default "Other" listing.
2404
		 *
2405
		 * @since 3.5.0
2406
		 *
2407
		 * @param array   $mod['feature'] The areas to feature this module:
2408
		 *     'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
2409
		 *     'Recommended' shows on the main Jetpack admin screen.
2410
		 *     'Other' should be the default if no other value is in the array.
2411
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2412
		 * @param array   $mod All the currently assembled module data.
2413
		 */
2414
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2415
2416
		/**
2417
		 * Filter the returned data about a module.
2418
		 *
2419
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2420
		 * so please be careful.
2421
		 *
2422
		 * @since 3.6.0
2423
		 *
2424
		 * @param array   $mod    The details of the requested module.
2425
		 * @param string  $module The slug of the module, e.g. sharedaddy
2426
		 * @param string  $file   The path to the module source file.
2427
		 */
2428
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2429
	}
2430
2431
	/**
2432
	 * Like core's get_file_data implementation, but caches the result.
2433
	 */
2434
	public static function get_file_data( $file, $headers ) {
2435
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2436
		$file_name = basename( $file );
2437
2438
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2439
2440
		$file_data_option = get_transient( $cache_key );
2441
2442
		if ( false === $file_data_option ) {
2443
			$file_data_option = array();
2444
		}
2445
2446
		$key           = md5( $file_name . serialize( $headers ) );
2447
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2448
2449
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2450
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2451
			return $file_data_option[ $key ];
2452
		}
2453
2454
		$data = get_file_data( $file, $headers );
2455
2456
		$file_data_option[ $key ] = $data;
2457
2458
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2459
2460
		return $data;
2461
	}
2462
2463
2464
	/**
2465
	 * Return translated module tag.
2466
	 *
2467
	 * @param string $tag Tag as it appears in each module heading.
2468
	 *
2469
	 * @return mixed
2470
	 */
2471
	public static function translate_module_tag( $tag ) {
2472
		return jetpack_get_module_i18n_tag( $tag );
2473
	}
2474
2475
	/**
2476
	 * Get i18n strings as a JSON-encoded string
2477
	 *
2478
	 * @return string The locale as JSON
2479
	 */
2480
	public static function get_i18n_data_json() {
2481
2482
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2483
		// JSON files with the file they should be included for. This is an md5
2484
		// of '_inc/build/admin.js'.
2485
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2486
2487
		$i18n_json =
2488
				   JETPACK__PLUGIN_DIR
2489
				   . 'languages/json/jetpack-'
2490
				   . get_user_locale()
2491
				   . '-'
2492
				   . $path_md5
2493
				   . '.json';
2494
2495
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2496
			$locale_data = @file_get_contents( $i18n_json );
2497
			if ( $locale_data ) {
2498
				return $locale_data;
2499
			}
2500
		}
2501
2502
		// Return valid empty Jed locale
2503
		return '{ "locale_data": { "messages": { "": {} } } }';
2504
	}
2505
2506
	/**
2507
	 * Add locale data setup to wp-i18n
2508
	 *
2509
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2510
	 *
2511
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2512
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2513
	 *
2514
	 * This method provides a safe way to request the setup multiple times but add the script at
2515
	 * most once.
2516
	 *
2517
	 * @since 6.7.0
2518
	 *
2519
	 * @return void
2520
	 */
2521
	public static function setup_wp_i18n_locale_data() {
2522
		static $script_added = false;
2523
		if ( ! $script_added ) {
2524
			$script_added = true;
2525
			wp_add_inline_script(
2526
				'wp-i18n',
2527
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2528
			);
2529
		}
2530
	}
2531
2532
	/**
2533
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2534
	 *
2535
	 * @since 3.9.2
2536
	 *
2537
	 * @param array $modules
2538
	 *
2539
	 * @return string|void
2540
	 */
2541
	public static function get_translated_modules( $modules ) {
2542
		foreach ( $modules as $index => $module ) {
2543
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2544
			if ( isset( $module['name'] ) ) {
2545
				$modules[ $index ]['name'] = $i18n_module['name'];
2546
			}
2547
			if ( isset( $module['description'] ) ) {
2548
				$modules[ $index ]['description'] = $i18n_module['description'];
2549
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2550
			}
2551
		}
2552
		return $modules;
2553
	}
2554
2555
	/**
2556
	 * Get a list of activated modules as an array of module slugs.
2557
	 */
2558
	public static function get_active_modules() {
2559
		$active = Jetpack_Options::get_option( 'active_modules' );
2560
2561
		if ( ! is_array( $active ) ) {
2562
			$active = array();
2563
		}
2564
2565
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2566
			$active[] = 'vaultpress';
2567
		} else {
2568
			$active = array_diff( $active, array( 'vaultpress' ) );
2569
		}
2570
2571
		//If protect is active on the main site of a multisite, it should be active on all sites.
2572
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2573
			$active[] = 'protect';
2574
		}
2575
2576
		/**
2577
		 * Allow filtering of the active modules.
2578
		 *
2579
		 * Gives theme and plugin developers the power to alter the modules that
2580
		 * are activated on the fly.
2581
		 *
2582
		 * @since 5.8.0
2583
		 *
2584
		 * @param array $active Array of active module slugs.
2585
		 */
2586
		$active = apply_filters( 'jetpack_active_modules', $active );
2587
2588
		return array_unique( $active );
2589
	}
2590
2591
	/**
2592
	 * Check whether or not a Jetpack module is active.
2593
	 *
2594
	 * @param string $module The slug of a Jetpack module.
2595
	 * @return bool
2596
	 *
2597
	 * @static
2598
	 */
2599
	public static function is_module_active( $module ) {
2600
		return in_array( $module, self::get_active_modules() );
2601
	}
2602
2603
	public static function is_module( $module ) {
2604
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2605
	}
2606
2607
	/**
2608
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2609
	 *
2610
	 * @param bool $catch True to start catching, False to stop.
2611
	 *
2612
	 * @static
2613
	 */
2614
	public static function catch_errors( $catch ) {
2615
		static $display_errors, $error_reporting;
2616
2617
		if ( $catch ) {
2618
			$display_errors  = @ini_set( 'display_errors', 1 );
2619
			$error_reporting = @error_reporting( E_ALL );
2620
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2621
		} else {
2622
			@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...
2623
			@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...
2624
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2625
		}
2626
	}
2627
2628
	/**
2629
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2630
	 */
2631
	public static function catch_errors_on_shutdown() {
2632
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2633
	}
2634
2635
	/**
2636
	 * Rewrite any string to make paths easier to read.
2637
	 *
2638
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2639
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2640
	 *
2641
	 * @param $string
2642
	 * @return mixed
2643
	 */
2644
	public static function alias_directories( $string ) {
2645
		// ABSPATH has a trailing slash.
2646
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2647
		// WP_CONTENT_DIR does not have a trailing slash.
2648
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2649
2650
		return $string;
2651
	}
2652
2653
	public static function activate_default_modules(
2654
		$min_version = false,
2655
		$max_version = false,
2656
		$other_modules = array(),
2657
		$redirect = true,
2658
		$send_state_messages = true
2659
	) {
2660
		$jetpack = Jetpack::init();
2661
2662
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2663
		$modules = array_merge( $other_modules, $modules );
2664
2665
		// Look for standalone plugins and disable if active.
2666
2667
		$to_deactivate = array();
2668
		foreach ( $modules as $module ) {
2669
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2670
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2671
			}
2672
		}
2673
2674
		$deactivated = array();
2675
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2676
			list( $probable_file, $probable_title ) = $deactivate_me;
2677
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2678
				$deactivated[] = $module;
2679
			}
2680
		}
2681
2682
		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...
2683
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2684
2685
			$url = add_query_arg(
2686
				array(
2687
					'action'   => 'activate_default_modules',
2688
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2689
				),
2690
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2691
			);
2692
			wp_safe_redirect( $url );
2693
			exit;
2694
		}
2695
2696
		/**
2697
		 * Fires before default modules are activated.
2698
		 *
2699
		 * @since 1.9.0
2700
		 *
2701
		 * @param string $min_version Minimum version number required to use modules.
2702
		 * @param string $max_version Maximum version number required to use modules.
2703
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2704
		 */
2705
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2706
2707
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2708
		if ( $send_state_messages ) {
2709
			Jetpack::restate();
2710
			Jetpack::catch_errors( true );
2711
		}
2712
2713
		$active = Jetpack::get_active_modules();
2714
2715
		foreach ( $modules as $module ) {
2716
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2717
				$active[] = $module;
2718
				self::update_active_modules( $active );
2719
				continue;
2720
			}
2721
2722
			if ( $send_state_messages && in_array( $module, $active ) ) {
2723
				$module_info = Jetpack::get_module( $module );
2724 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2725
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2726
					if ( $active_state = Jetpack::state( $state ) ) {
2727
						$active_state = explode( ',', $active_state );
2728
					} else {
2729
						$active_state = array();
2730
					}
2731
					$active_state[] = $module;
2732
					Jetpack::state( $state, implode( ',', $active_state ) );
2733
				}
2734
				continue;
2735
			}
2736
2737
			$file = Jetpack::get_module_path( $module );
2738
			if ( ! file_exists( $file ) ) {
2739
				continue;
2740
			}
2741
2742
			// we'll override this later if the plugin can be included without fatal error
2743
			if ( $redirect ) {
2744
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2745
			}
2746
2747
			if ( $send_state_messages ) {
2748
				Jetpack::state( 'error', 'module_activation_failed' );
2749
				Jetpack::state( 'module', $module );
2750
			}
2751
2752
			ob_start();
2753
			require_once $file;
2754
2755
			$active[] = $module;
2756
2757 View Code Duplication
			if ( $send_state_messages ) {
2758
2759
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2760
				if ( $active_state = Jetpack::state( $state ) ) {
2761
					$active_state = explode( ',', $active_state );
2762
				} else {
2763
					$active_state = array();
2764
				}
2765
				$active_state[] = $module;
2766
				Jetpack::state( $state, implode( ',', $active_state ) );
2767
			}
2768
2769
			Jetpack::update_active_modules( $active );
2770
2771
			ob_end_clean();
2772
		}
2773
2774
		if ( $send_state_messages ) {
2775
			Jetpack::state( 'error', false );
0 ignored issues
show
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...
2776
			Jetpack::state( 'module', false );
0 ignored issues
show
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...
2777
		}
2778
2779
		Jetpack::catch_errors( false );
2780
		/**
2781
		 * Fires when default modules are activated.
2782
		 *
2783
		 * @since 1.9.0
2784
		 *
2785
		 * @param string $min_version Minimum version number required to use modules.
2786
		 * @param string $max_version Maximum version number required to use modules.
2787
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2788
		 */
2789
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2790
	}
2791
2792
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2793
		/**
2794
		 * Fires before a module is activated.
2795
		 *
2796
		 * @since 2.6.0
2797
		 *
2798
		 * @param string $module Module slug.
2799
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2800
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2801
		 */
2802
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2803
2804
		$jetpack = Jetpack::init();
2805
2806
		if ( ! strlen( $module ) )
2807
			return false;
2808
2809
		if ( ! Jetpack::is_module( $module ) )
2810
			return false;
2811
2812
		// If it's already active, then don't do it again
2813
		$active = Jetpack::get_active_modules();
2814
		foreach ( $active as $act ) {
2815
			if ( $act == $module )
2816
				return true;
2817
		}
2818
2819
		$module_data = Jetpack::get_module( $module );
2820
2821
		if ( ! Jetpack::is_active() ) {
2822
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2823
				return false;
2824
2825
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2826
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2827
				return false;
2828
		}
2829
2830
		// Check and see if the old plugin is active
2831
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2832
			// Deactivate the old plugin
2833
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2834
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2835
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2836
				Jetpack::state( 'deactivated_plugins', $module );
2837
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2838
				exit;
2839
			}
2840
		}
2841
2842
		// Protect won't work with mis-configured IPs
2843
		if ( 'protect' === $module ) {
2844
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2845
			if ( ! jetpack_protect_get_ip() ) {
2846
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2847
				return false;
2848
			}
2849
		}
2850
2851
		if ( ! Jetpack_Plan::supports( $module ) ) {
2852
			return false;
2853
		}
2854
2855
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2856
		Jetpack::state( 'module', $module );
2857
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2858
2859
		Jetpack::catch_errors( true );
2860
		ob_start();
2861
		require Jetpack::get_module_path( $module );
2862
		/** This action is documented in class.jetpack.php */
2863
		do_action( 'jetpack_activate_module', $module );
2864
		$active[] = $module;
2865
		Jetpack::update_active_modules( $active );
2866
2867
		Jetpack::state( 'error', false ); // the override
0 ignored issues
show
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...
2868
		ob_end_clean();
2869
		Jetpack::catch_errors( false );
2870
2871
		if ( $redirect ) {
2872
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2873
		}
2874
		if ( $exit ) {
2875
			exit;
2876
		}
2877
		return true;
2878
	}
2879
2880
	function activate_module_actions( $module ) {
2881
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2882
	}
2883
2884
	public static function deactivate_module( $module ) {
2885
		/**
2886
		 * Fires when a module is deactivated.
2887
		 *
2888
		 * @since 1.9.0
2889
		 *
2890
		 * @param string $module Module slug.
2891
		 */
2892
		do_action( 'jetpack_pre_deactivate_module', $module );
2893
2894
		$jetpack = Jetpack::init();
0 ignored issues
show
$jetpack 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...
2895
2896
		$active = Jetpack::get_active_modules();
2897
		$new    = array_filter( array_diff( $active, (array) $module ) );
2898
2899
		return self::update_active_modules( $new );
2900
	}
2901
2902
	public static function enable_module_configurable( $module ) {
2903
		$module = Jetpack::get_module_slug( $module );
2904
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2905
	}
2906
2907
	/**
2908
	 * Composes a module configure URL. It uses Jetpack settings search as default value
2909
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
2910
	 *
2911
	 * @param string $module Module slug
2912
	 * @return string $url module configuration URL
2913
	 */
2914
	public static function module_configuration_url( $module ) {
2915
		$module = Jetpack::get_module_slug( $module );
2916
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
2917
		/**
2918
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
2919
		 *
2920
		 * @since 6.9.0
2921
		 *
2922
		 * @param string $default_url Default url, which redirects to jetpack settings page.
2923
		 */
2924
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
2925
2926
		return $url;
2927
	}
2928
2929
/* Installation */
2930
	public static function bail_on_activation( $message, $deactivate = true ) {
2931
?>
2932
<!doctype html>
2933
<html>
2934
<head>
2935
<meta charset="<?php bloginfo( 'charset' ); ?>">
2936
<style>
2937
* {
2938
	text-align: center;
2939
	margin: 0;
2940
	padding: 0;
2941
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2942
}
2943
p {
2944
	margin-top: 1em;
2945
	font-size: 18px;
2946
}
2947
</style>
2948
<body>
2949
<p><?php echo esc_html( $message ); ?></p>
2950
</body>
2951
</html>
2952
<?php
2953
		if ( $deactivate ) {
2954
			$plugins = get_option( 'active_plugins' );
2955
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2956
			$update  = false;
2957
			foreach ( $plugins as $i => $plugin ) {
2958
				if ( $plugin === $jetpack ) {
2959
					$plugins[$i] = false;
2960
					$update = true;
2961
				}
2962
			}
2963
2964
			if ( $update ) {
2965
				update_option( 'active_plugins', array_filter( $plugins ) );
2966
			}
2967
		}
2968
		exit;
2969
	}
2970
2971
	/**
2972
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2973
	 * @static
2974
	 */
2975
	public static function plugin_activation( $network_wide ) {
2976
		Jetpack_Options::update_option( 'activated', 1 );
2977
2978
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2979
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2980
		}
2981
2982
		if ( $network_wide )
2983
			Jetpack::state( 'network_nag', true );
0 ignored issues
show
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...
2984
2985
		// For firing one-off events (notices) immediately after activation
2986
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
2987
2988
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
2989
2990
		Jetpack::plugin_initialize();
2991
	}
2992
2993
	public static function get_activation_source( $referer_url ) {
2994
2995
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
2996
			return array( 'wp-cli', null );
2997
		}
2998
2999
		$referer = parse_url( $referer_url );
3000
3001
		$source_type = 'unknown';
3002
		$source_query = null;
3003
3004
		if ( ! is_array( $referer ) ) {
3005
			return array( $source_type, $source_query );
3006
		}
3007
3008
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3009
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3010
3011
		if ( isset( $referer['query'] ) ) {
3012
			parse_str( $referer['query'], $query_parts );
3013
		} else {
3014
			$query_parts = array();
3015
		}
3016
3017
		if ( $plugins_path === $referer['path'] ) {
3018
			$source_type = 'list';
3019
		} elseif ( $plugins_install_path === $referer['path'] ) {
3020
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3021
			switch( $tab ) {
3022
				case 'popular':
3023
					$source_type = 'popular';
3024
					break;
3025
				case 'recommended':
3026
					$source_type = 'recommended';
3027
					break;
3028
				case 'favorites':
3029
					$source_type = 'favorites';
3030
					break;
3031
				case 'search':
3032
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3033
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3034
					break;
3035
				default:
3036
					$source_type = 'featured';
3037
			}
3038
		}
3039
3040
		return array( $source_type, $source_query );
3041
	}
3042
3043
	/**
3044
	 * Runs before bumping version numbers up to a new version
3045
	 * @param  string $version    Version:timestamp
3046
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3047
	 * @return null              [description]
3048
	 */
3049
	public static function do_version_bump( $version, $old_version ) {
3050
		if ( ! $old_version ) { // For new sites
3051
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3052
		}
3053
	}
3054
3055
	/**
3056
	 * Sets the internal version number and activation state.
3057
	 * @static
3058
	 */
3059
	public static function plugin_initialize() {
3060
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3061
			Jetpack_Options::update_option( 'activated', 2 );
3062
		}
3063
3064 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3065
			$version = $old_version = JETPACK__VERSION . ':' . time();
3066
			/** This action is documented in class.jetpack.php */
3067
			do_action( 'updating_jetpack_version', $version, false );
3068
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3069
		}
3070
3071
		Jetpack::load_modules();
3072
3073
		Jetpack_Options::delete_option( 'do_activate' );
3074
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3075
	}
3076
3077
	/**
3078
	 * Removes all connection options
3079
	 * @static
3080
	 */
3081
	public static function plugin_deactivation( ) {
3082
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3083
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3084
			Jetpack_Network::init()->deactivate();
3085
		} else {
3086
			Jetpack::disconnect( false );
3087
			//Jetpack_Heartbeat::init()->deactivate();
3088
		}
3089
	}
3090
3091
	/**
3092
	 * Disconnects from the Jetpack servers.
3093
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3094
	 * @static
3095
	 */
3096
	public static function disconnect( $update_activated_state = true ) {
3097
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3098
		Jetpack::clean_nonces( true );
3099
3100
		// If the site is in an IDC because sync is not allowed,
3101
		// let's make sure to not disconnect the production site.
3102
		if ( ! self::validate_sync_error_idc_option() ) {
3103
			$tracking = new Tracking();
3104
			$tracking->record_user_event( 'disconnect_site', array() );
3105
			Jetpack::load_xml_rpc_client();
3106
			$xml = new Jetpack_IXR_Client();
3107
			$xml->query( 'jetpack.deregister' );
3108
		}
3109
3110
		Jetpack_Options::delete_option(
3111
			array(
3112
				'blog_token',
3113
				'user_token',
3114
				'user_tokens',
3115
				'master_user',
3116
				'time_diff',
3117
				'fallback_no_verify_ssl_certs',
3118
			)
3119
		);
3120
3121
		Jetpack_IDC::clear_all_idc_options();
3122
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3123
3124
		if ( $update_activated_state ) {
3125
			Jetpack_Options::update_option( 'activated', 4 );
3126
		}
3127
3128
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3129
			// Check then record unique disconnection if site has never been disconnected previously
3130
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3131
				$jetpack_unique_connection['disconnected'] = 1;
3132
			} else {
3133
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3134
					//track unique disconnect
3135
					$jetpack = Jetpack::init();
3136
3137
					$jetpack->stat( 'connections', 'unique-disconnect' );
3138
					$jetpack->do_stats( 'server_side' );
3139
				}
3140
				// increment number of times disconnected
3141
				$jetpack_unique_connection['disconnected'] += 1;
3142
			}
3143
3144
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3145
		}
3146
3147
		// Delete cached connected user data
3148
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3149
		delete_transient( $transient_key );
3150
3151
		// Delete all the sync related data. Since it could be taking up space.
3152
		Jetpack_Sync_Sender::get_instance()->uninstall();
3153
3154
		// Disable the Heartbeat cron
3155
		Jetpack_Heartbeat::init()->deactivate();
3156
	}
3157
3158
	/**
3159
	 * Unlinks the current user from the linked WordPress.com user
3160
	 */
3161
	public static function unlink_user( $user_id = null ) {
3162
		if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
3163
			return false;
3164
3165
		$user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
3166
3167
		if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
3168
			return false;
3169
3170
		if ( ! isset( $tokens[ $user_id ] ) )
3171
			return false;
3172
3173
		Jetpack::load_xml_rpc_client();
3174
		$xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
3175
		$xml->query( 'jetpack.unlink_user', $user_id );
3176
3177
		unset( $tokens[ $user_id ] );
3178
3179
		Jetpack_Options::update_option( 'user_tokens', $tokens );
3180
3181
		/**
3182
		 * Fires after the current user has been unlinked from WordPress.com.
3183
		 *
3184
		 * @since 4.1.0
3185
		 *
3186
		 * @param int $user_id The current user's ID.
3187
		 */
3188
		do_action( 'jetpack_unlinked_user', $user_id );
3189
3190
		return true;
3191
	}
3192
3193
	/**
3194
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3195
	 */
3196
	public static function try_registration() {
3197
		// The user has agreed to the TOS at some point by now.
3198
		Jetpack_Options::update_option( 'tos_agreed', true );
3199
3200
		// Let's get some testing in beta versions and such.
3201
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3202
			// Before attempting to connect, let's make sure that the domains are viable.
3203
			$domains_to_check = array_unique( array(
3204
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3205
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3206
			) );
3207
			foreach ( $domains_to_check as $domain ) {
3208
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3207 can also be of type false; however, Automattic\Jetpack\Conne...ger::is_usable_domain() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
3209
				if ( is_wp_error( $result ) ) {
3210
					return $result;
3211
				}
3212
			}
3213
		}
3214
3215
		$result = Jetpack::register();
3216
3217
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3218
		if ( ! $result || is_wp_error( $result ) ) {
3219
			return $result;
3220
		} else {
3221
			return true;
3222
		}
3223
	}
3224
3225
	/**
3226
	 * Tracking an internal event log. Try not to put too much chaff in here.
3227
	 *
3228
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3229
	 */
3230
	public static function log( $code, $data = null ) {
3231
		// only grab the latest 200 entries
3232
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3233
3234
		// Append our event to the log
3235
		$log_entry = array(
3236
			'time'    => time(),
3237
			'user_id' => get_current_user_id(),
3238
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3239
			'code'    => $code,
3240
		);
3241
		// Don't bother storing it unless we've got some.
3242
		if ( ! is_null( $data ) ) {
3243
			$log_entry['data'] = $data;
3244
		}
3245
		$log[] = $log_entry;
3246
3247
		// Try add_option first, to make sure it's not autoloaded.
3248
		// @todo: Add an add_option method to Jetpack_Options
3249
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3250
			Jetpack_Options::update_option( 'log', $log );
3251
		}
3252
3253
		/**
3254
		 * Fires when Jetpack logs an internal event.
3255
		 *
3256
		 * @since 3.0.0
3257
		 *
3258
		 * @param array $log_entry {
3259
		 *	Array of details about the log entry.
3260
		 *
3261
		 *	@param string time Time of the event.
3262
		 *	@param int user_id ID of the user who trigerred the event.
3263
		 *	@param int blog_id Jetpack Blog ID.
3264
		 *	@param string code Unique name for the event.
3265
		 *	@param string data Data about the event.
3266
		 * }
3267
		 */
3268
		do_action( 'jetpack_log_entry', $log_entry );
3269
	}
3270
3271
	/**
3272
	 * Get the internal event log.
3273
	 *
3274
	 * @param $event (string) - only return the specific log events
3275
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3276
	 *
3277
	 * @return array of log events || WP_Error for invalid params
3278
	 */
3279
	public static function get_log( $event = false, $num = false ) {
3280
		if ( $event && ! is_string( $event ) ) {
3281
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('First param must be ...g or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3282
		}
3283
3284
		if ( $num && ! is_numeric( $num ) ) {
3285
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with __('Second param must be...c or empty', 'jetpack').

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3286
		}
3287
3288
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3289
3290
		// If nothing set - act as it did before, otherwise let's start customizing the output
3291
		if ( ! $num && ! $event ) {
3292
			return $entire_log;
3293
		} else {
3294
			$entire_log = array_reverse( $entire_log );
3295
		}
3296
3297
		$custom_log_output = array();
3298
3299
		if ( $event ) {
3300
			foreach ( $entire_log as $log_event ) {
3301
				if ( $event == $log_event[ 'code' ] ) {
3302
					$custom_log_output[] = $log_event;
3303
				}
3304
			}
3305
		} else {
3306
			$custom_log_output = $entire_log;
3307
		}
3308
3309
		if ( $num ) {
3310
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3311
		}
3312
3313
		return $custom_log_output;
3314
	}
3315
3316
	/**
3317
	 * Log modification of important settings.
3318
	 */
3319
	public static function log_settings_change( $option, $old_value, $value ) {
3320
		switch( $option ) {
3321
			case 'jetpack_sync_non_public_post_stati':
3322
				self::log( $option, $value );
3323
				break;
3324
		}
3325
	}
3326
3327
	/**
3328
	 * Return stat data for WPCOM sync
3329
	 */
3330
	public static function get_stat_data( $encode = true, $extended = true ) {
3331
		$data = Jetpack_Heartbeat::generate_stats_array();
3332
3333
		if ( $extended ) {
3334
			$additional_data = self::get_additional_stat_data();
3335
			$data = array_merge( $data, $additional_data );
3336
		}
3337
3338
		if ( $encode ) {
3339
			return json_encode( $data );
3340
		}
3341
3342
		return $data;
3343
	}
3344
3345
	/**
3346
	 * Get additional stat data to sync to WPCOM
3347
	 */
3348
	public static function get_additional_stat_data( $prefix = '' ) {
3349
		$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...
3350
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3351
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3352
		$return["{$prefix}site-count"]     = 0;
3353
3354
		if ( function_exists( 'get_blog_count' ) ) {
3355
			$return["{$prefix}site-count"] = get_blog_count();
3356
		}
3357
		return $return;
3358
	}
3359
3360
	private static function get_site_user_count() {
3361
		global $wpdb;
3362
3363
		if ( function_exists( 'wp_is_large_network' ) ) {
3364
			if ( wp_is_large_network( 'users' ) ) {
3365
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3366
			}
3367
		}
3368 View Code Duplication
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3369
			// It wasn't there, so regenerate the data and save the transient
3370
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3371
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3372
		}
3373
		return $user_count;
3374
	}
3375
3376
	/* Admin Pages */
3377
3378
	function admin_init() {
3379
		// If the plugin is not connected, display a connect message.
3380
		if (
3381
			// the plugin was auto-activated and needs its candy
3382
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3383
		||
3384
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3385
			! Jetpack_Options::get_option( 'activated' )
3386
		) {
3387
			Jetpack::plugin_initialize();
3388
		}
3389
3390
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3391
			Jetpack_Connection_Banner::init();
3392
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3393
			// Upgrade: 1.1 -> 1.1.1
3394
			// Check and see if host can verify the Jetpack servers' SSL certificate
3395
			$args = array();
3396
			Client::_wp_remote_request(
3397
				Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
3398
				$args,
3399
				true
3400
			);
3401
		}
3402
3403
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3404
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3405
		}
3406
3407
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3408
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3409
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3410
3411
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3412
			// Artificially throw errors in certain whitelisted cases during plugin activation
3413
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3414
		}
3415
3416
		// Add custom column in wp-admin/users.php to show whether user is linked.
3417
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3418
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3419
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3420
	}
3421
3422
	function admin_body_class( $admin_body_class = '' ) {
3423
		$classes = explode( ' ', trim( $admin_body_class ) );
3424
3425
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3426
3427
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3428
		return " $admin_body_class ";
3429
	}
3430
3431
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3432
		return $admin_body_class . ' jetpack-pagestyles ';
3433
	}
3434
3435
	/**
3436
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3437
	 * This function artificially throws errors for such cases (whitelisted).
3438
	 *
3439
	 * @param string $plugin The activated plugin.
3440
	 */
3441
	function throw_error_on_activate_plugin( $plugin ) {
3442
		$active_modules = Jetpack::get_active_modules();
3443
3444
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3445
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3446
			$throw = false;
3447
3448
			// Try and make sure it really was the stats plugin
3449
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3450
				if ( 'stats.php' == basename( $plugin ) ) {
3451
					$throw = true;
3452
				}
3453
			} else {
3454
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3455
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3456
					$throw = true;
3457
				}
3458
			}
3459
3460
			if ( $throw ) {
3461
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3462
			}
3463
		}
3464
	}
3465
3466
	function intercept_plugin_error_scrape_init() {
3467
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3468
	}
3469
3470
	function intercept_plugin_error_scrape( $action, $result ) {
3471
		if ( ! $result ) {
3472
			return;
3473
		}
3474
3475
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3476
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3477
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3478
			}
3479
		}
3480
	}
3481
3482
	function add_remote_request_handlers() {
3483
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3484
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3485
	}
3486
3487
	function remote_request_handlers() {
3488
		$action = current_filter();
0 ignored issues
show
$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...
3489
3490
		switch ( current_filter() ) {
3491
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3492
			$response = $this->upload_handler();
3493
			break;
3494
3495
		case 'wp_ajax_nopriv_jetpack_update_file' :
3496
			$response = $this->upload_handler( true );
3497
			break;
3498
		default :
3499
			$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_handler'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3500
			break;
3501
		}
3502
3503
		if ( ! $response ) {
3504
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3505
		}
3506
3507
		if ( is_wp_error( $response ) ) {
3508
			$status_code       = $response->get_error_data();
0 ignored issues
show
The method get_error_data() does not seem to exist on object<Jetpack_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3509
			$error             = $response->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<Jetpack_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3510
			$error_description = $response->get_error_message();
0 ignored issues
show
The method get_error_message() does not seem to exist on object<Jetpack_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3511
3512
			if ( ! is_int( $status_code ) ) {
3513
				$status_code = 400;
3514
			}
3515
3516
			status_header( $status_code );
3517
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3518
		}
3519
3520
		status_header( 200 );
3521
		if ( true === $response ) {
3522
			exit;
3523
		}
3524
3525
		die( json_encode( (object) $response ) );
3526
	}
3527
3528
	/**
3529
	 * Uploads a file gotten from the global $_FILES.
3530
	 * If `$update_media_item` is true and `post_id` is defined
3531
	 * the attachment file of the media item (gotten through of the post_id)
3532
	 * will be updated instead of add a new one.
3533
	 *
3534
	 * @param  boolean $update_media_item - update media attachment
3535
	 * @return array - An array describing the uploadind files process
3536
	 */
3537
	function upload_handler( $update_media_item = false ) {
3538
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3539
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 405.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3540
		}
3541
3542
		$user = wp_authenticate( '', '' );
3543
		if ( ! $user || is_wp_error( $user ) ) {
3544
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 403.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3545
		}
3546
3547
		wp_set_current_user( $user->ID );
3548
3549
		if ( ! current_user_can( 'upload_files' ) ) {
3550
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'cannot_upload_files'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3551
		}
3552
3553
		if ( empty( $_FILES ) ) {
3554
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'no_files_uploaded'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3555
		}
3556
3557
		foreach ( array_keys( $_FILES ) as $files_key ) {
3558
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3559
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_hmac'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3560
			}
3561
		}
3562
3563
		$media_keys = array_keys( $_FILES['media'] );
3564
3565
		$token = Jetpack_Data::get_access_token( get_current_user_id() );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
3566
		if ( ! $token || is_wp_error( $token ) ) {
3567
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_token'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3568
		}
3569
3570
		$uploaded_files = array();
3571
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3572
		unset( $GLOBALS['post'] );
3573
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3574
			$file = array();
3575
			foreach ( $media_keys as $media_key ) {
3576
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3577
			}
3578
3579
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3580
3581
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3582
			if ( $hmac_provided !== $hmac_file ) {
3583
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3584
				continue;
3585
			}
3586
3587
			$_FILES['.jetpack.upload.'] = $file;
3588
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3589
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3590
				$post_id = 0;
3591
			}
3592
3593
			if ( $update_media_item ) {
3594
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3595
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'invalid_input'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
3596
				}
3597
3598
				$media_array = $_FILES['media'];
3599
3600
				$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...
3601
				$file_array['type'] = $media_array['type'][0];
3602
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3603
				$file_array['error'] = $media_array['error'][0];
3604
				$file_array['size'] = $media_array['size'][0];
3605
3606
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3607
3608
				if ( is_wp_error( $edited_media_item ) ) {
3609
					return $edited_media_item;
3610
				}
3611
3612
				$response = (object) array(
3613
					'id'   => (string) $post_id,
3614
					'file' => (string) $edited_media_item->post_title,
3615
					'url'  => (string) wp_get_attachment_url( $post_id ),
3616
					'type' => (string) $edited_media_item->post_mime_type,
3617
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3618
				);
3619
3620
				return (array) array( $response );
3621
			}
3622
3623
			$attachment_id = media_handle_upload(
3624
				'.jetpack.upload.',
3625
				$post_id,
3626
				array(),
3627
				array(
3628
					'action' => 'jetpack_upload_file',
3629
				)
3630
			);
3631
3632
			if ( ! $attachment_id ) {
3633
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3634
			} elseif ( is_wp_error( $attachment_id ) ) {
3635
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3636
			} else {
3637
				$attachment = get_post( $attachment_id );
3638
				$uploaded_files[$index] = (object) array(
3639
					'id'   => (string) $attachment_id,
3640
					'file' => $attachment->post_title,
3641
					'url'  => wp_get_attachment_url( $attachment_id ),
3642
					'type' => $attachment->post_mime_type,
3643
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3644
				);
3645
				// Zip files uploads are not supported unless they are done for installation purposed
3646
				// lets delete them in case something goes wrong in this whole process
3647
				if ( 'application/zip' === $attachment->post_mime_type ) {
3648
					// Schedule a cleanup for 2 hours from now in case of failed install.
3649
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3650
				}
3651
			}
3652
		}
3653
		if ( ! is_null( $global_post ) ) {
3654
			$GLOBALS['post'] = $global_post;
3655
		}
3656
3657
		return $uploaded_files;
3658
	}
3659
3660
	/**
3661
	 * Add help to the Jetpack page
3662
	 *
3663
	 * @since Jetpack (1.2.3)
3664
	 * @return false if not the Jetpack page
3665
	 */
3666
	function admin_help() {
3667
		$current_screen = get_current_screen();
3668
3669
		// Overview
3670
		$current_screen->add_help_tab(
3671
			array(
3672
				'id'		=> 'home',
3673
				'title'		=> __( 'Home', 'jetpack' ),
3674
				'content'	=>
3675
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3676
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3677
					'<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>',
3678
			)
3679
		);
3680
3681
		// Screen Content
3682
		if ( current_user_can( 'manage_options' ) ) {
3683
			$current_screen->add_help_tab(
3684
				array(
3685
					'id'		=> 'settings',
3686
					'title'		=> __( 'Settings', 'jetpack' ),
3687
					'content'	=>
3688
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3689
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3690
						'<ol>' .
3691
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3692
							'<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>' .
3693
						'</ol>' .
3694
						'<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>'
3695
				)
3696
			);
3697
		}
3698
3699
		// Help Sidebar
3700
		$current_screen->set_help_sidebar(
3701
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3702
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3703
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3704
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3705
		);
3706
	}
3707
3708
	function admin_menu_css() {
3709
		wp_enqueue_style( 'jetpack-icons' );
3710
	}
3711
3712
	function admin_menu_order() {
3713
		return true;
3714
	}
3715
3716 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3717
		$jp_menu_order = array();
3718
3719
		foreach ( $menu_order as $index => $item ) {
3720
			if ( $item != 'jetpack' ) {
3721
				$jp_menu_order[] = $item;
3722
			}
3723
3724
			if ( $index == 0 ) {
3725
				$jp_menu_order[] = 'jetpack';
3726
			}
3727
		}
3728
3729
		return $jp_menu_order;
3730
	}
3731
3732
	function admin_banner_styles() {
3733
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3734
3735
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3736
			wp_register_style(
3737
				'jetpack-dops-style',
3738
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3739
				array(),
3740
				JETPACK__VERSION
3741
			);
3742
		}
3743
3744
		wp_enqueue_style(
3745
			'jetpack',
3746
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3747
			array( 'jetpack-dops-style' ),
3748
			 JETPACK__VERSION . '-20121016'
3749
		);
3750
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3751
		wp_style_add_data( 'jetpack', 'suffix', $min );
3752
	}
3753
3754
	function plugin_action_links( $actions ) {
3755
3756
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3757
3758
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3759
			return array_merge(
3760
				$jetpack_home,
3761
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3762
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3763
				$actions
3764
				);
3765
			}
3766
3767
		return array_merge( $jetpack_home, $actions );
3768
	}
3769
3770
	/*
3771
	 * Registration flow:
3772
	 * 1 - ::admin_page_load() action=register
3773
	 * 2 - ::try_registration()
3774
	 * 3 - ::register()
3775
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3776
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3777
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3778
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3779
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3780
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3781
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3782
	 *       jetpack_id, jetpack_secret, jetpack_public
3783
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3784
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3785
	 * 5 - user logs in with WP.com account
3786
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3787
	 *		- Jetpack_Client_Server::authorize()
3788
	 *		- Jetpack_Client_Server::get_token()
3789
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3790
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3791
	 *			- which responds with access_token, token_type, scope
3792
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3793
	 *		- Jetpack::activate_default_modules()
3794
	 *     		- Deactivates deprecated plugins
3795
	 *     		- Activates all default modules
3796
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3797
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3798
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3799
	 *     Done!
3800
	 */
3801
3802
	/**
3803
	 * Handles the page load events for the Jetpack admin page
3804
	 */
3805
	function admin_page_load() {
3806
		$error = false;
3807
3808
		// Make sure we have the right body class to hook stylings for subpages off of.
3809
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3810
3811
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3812
			// Should only be used in intermediate redirects to preserve state across redirects
3813
			Jetpack::restate();
3814
		}
3815
3816
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3817
			// @todo: Add validation against a known whitelist
3818
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3819
			// User clicked in the iframe to link their accounts
3820
			if ( ! Jetpack::is_user_connected() ) {
3821
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3822
3823
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3824
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3825
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3826
3827
				if ( isset( $_GET['notes_iframe'] ) )
3828
					$connect_url .= '&notes_iframe';
3829
				wp_redirect( $connect_url );
3830
				exit;
3831
			} else {
3832
				if ( ! isset( $_GET['calypso_env'] ) ) {
3833
					Jetpack::state( 'message', 'already_authorized' );
3834
					wp_safe_redirect( Jetpack::admin_url() );
3835
					exit;
3836
				} else {
3837
					$connect_url = $this->build_connect_url( true, false, $from );
3838
					$connect_url .= '&already_authorized=true';
3839
					wp_redirect( $connect_url );
3840
					exit;
3841
				}
3842
			}
3843
		}
3844
3845
3846
		if ( isset( $_GET['action'] ) ) {
3847
			switch ( $_GET['action'] ) {
3848
			case 'authorize':
3849
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3850
					Jetpack::state( 'message', 'already_authorized' );
3851
					wp_safe_redirect( Jetpack::admin_url() );
3852
					exit;
3853
				}
3854
				Jetpack::log( 'authorize' );
3855
				$client_server = new Jetpack_Client_Server;
3856
				$client_server->client_authorize();
3857
				exit;
3858
			case 'register' :
3859
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3860
					$error = 'cheatin';
3861
					break;
3862
				}
3863
				check_admin_referer( 'jetpack-register' );
3864
				Jetpack::log( 'register' );
3865
				Jetpack::maybe_set_version_option();
3866
				$registered = Jetpack::try_registration();
3867
				if ( is_wp_error( $registered ) ) {
3868
					$error = $registered->get_error_code();
0 ignored issues
show
The method get_error_code() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3869
					Jetpack::state( 'error', $error );
3870
					Jetpack::state( 'error', $registered->get_error_message() );
0 ignored issues
show
The method get_error_message() does not seem to exist on object<WP_Error>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
3871
3872
					/**
3873
					 * Jetpack registration Error.
3874
					 *
3875
					 * @since 7.5.0
3876
					 *
3877
					 * @param string|int $error The error code.
3878
					 * @param \WP_Error $registered The error object.
3879
					 */
3880
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3881
					break;
3882
				}
3883
3884
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3885
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3886
3887
				/**
3888
				 * Jetpack registration Success.
3889
				 *
3890
				 * @since 7.5.0
3891
				 *
3892
				 * @param string $from 'from' GET parameter;
3893
				 */
3894
				do_action( 'jetpack_connection_register_success', $from );
3895
3896
				$url = $this->build_connect_url( true, $redirect, $from );
3897
3898
				if ( ! empty( $_GET['onboarding'] ) ) {
3899
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
3900
				}
3901
3902
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
3903
					$url = add_query_arg( 'auth_approved', 'true', $url );
3904
				}
3905
3906
				wp_redirect( $url );
3907
				exit;
3908
			case 'activate' :
3909
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3910
					$error = 'cheatin';
3911
					break;
3912
				}
3913
3914
				$module = stripslashes( $_GET['module'] );
3915
				check_admin_referer( "jetpack_activate-$module" );
3916
				Jetpack::log( 'activate', $module );
3917
				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...
3918
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
3919
				}
3920
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
3921
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3922
				exit;
3923
			case 'activate_default_modules' :
3924
				check_admin_referer( 'activate_default_modules' );
3925
				Jetpack::log( 'activate_default_modules' );
3926
				Jetpack::restate();
3927
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
3928
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
3929
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
3930
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
3931
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3932
				exit;
3933
			case 'disconnect' :
3934
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
3935
					$error = 'cheatin';
3936
					break;
3937
				}
3938
3939
				check_admin_referer( 'jetpack-disconnect' );
3940
				Jetpack::log( 'disconnect' );
3941
				Jetpack::disconnect();
3942
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
3943
				exit;
3944
			case 'reconnect' :
3945
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
3946
					$error = 'cheatin';
3947
					break;
3948
				}
3949
3950
				check_admin_referer( 'jetpack-reconnect' );
3951
				Jetpack::log( 'reconnect' );
3952
				$this->disconnect();
3953
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
3954
				exit;
3955 View Code Duplication
			case 'deactivate' :
3956
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
3957
					$error = 'cheatin';
3958
					break;
3959
				}
3960
3961
				$modules = stripslashes( $_GET['module'] );
3962
				check_admin_referer( "jetpack_deactivate-$modules" );
3963
				foreach ( explode( ',', $modules ) as $module ) {
3964
					Jetpack::log( 'deactivate', $module );
3965
					Jetpack::deactivate_module( $module );
3966
					Jetpack::state( 'message', 'module_deactivated' );
3967
				}
3968
				Jetpack::state( 'module', $modules );
3969
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3970
				exit;
3971
			case 'unlink' :
3972
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
3973
				check_admin_referer( 'jetpack-unlink' );
3974
				Jetpack::log( 'unlink' );
3975
				$this->unlink_user();
3976
				Jetpack::state( 'message', 'unlinked' );
3977
				if ( 'sub-unlink' == $redirect ) {
3978
					wp_safe_redirect( admin_url() );
3979
				} else {
3980
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
3981
				}
3982
				exit;
3983
			case 'onboard' :
3984
				if ( ! current_user_can( 'manage_options' ) ) {
3985
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3986
				} else {
3987
					Jetpack::create_onboarding_token();
3988
					$url = $this->build_connect_url( true );
3989
3990
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
3991
						$url = add_query_arg( 'onboarding', $token, $url );
3992
					}
3993
3994
					$calypso_env = $this->get_calypso_env();
3995
					if ( ! empty( $calypso_env ) ) {
3996
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
3997
					}
3998
3999
					wp_redirect( $url );
4000
					exit;
4001
				}
4002
				exit;
4003
			default:
4004
				/**
4005
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4006
				 *
4007
				 * @since 2.6.0
4008
				 *
4009
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4010
				 */
4011
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4012
			}
4013
		}
4014
4015
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4016
			self::activate_new_modules( true );
4017
		}
4018
4019
		$message_code = Jetpack::state( 'message' );
4020
		if ( Jetpack::state( 'optin-manage' ) ) {
4021
			$activated_manage = $message_code;
4022
			$message_code = 'jetpack-manage';
4023
		}
4024
4025
		switch ( $message_code ) {
4026
		case 'jetpack-manage':
4027
			$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>';
4028
			if ( $activated_manage ) {
0 ignored issues
show
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...
4029
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4030
			}
4031
			break;
4032
4033
		}
4034
4035
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4036
4037
		if ( ! empty( $deactivated_plugins ) ) {
4038
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4039
			$deactivated_titles  = array();
4040
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4041
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4042
					continue;
4043
				}
4044
4045
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4046
			}
4047
4048
			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...
4049
				if ( $this->message ) {
4050
					$this->message .= "<br /><br />\n";
4051
				}
4052
4053
				$this->message .= wp_sprintf(
4054
					_n(
4055
						'Jetpack contains the most recent version of the old %l plugin.',
4056
						'Jetpack contains the most recent versions of the old %l plugins.',
4057
						count( $deactivated_titles ),
4058
						'jetpack'
4059
					),
4060
					$deactivated_titles
4061
				);
4062
4063
				$this->message .= "<br />\n";
4064
4065
				$this->message .= _n(
4066
					'The old version has been deactivated and can be removed from your site.',
4067
					'The old versions have been deactivated and can be removed from your site.',
4068
					count( $deactivated_titles ),
4069
					'jetpack'
4070
				);
4071
			}
4072
		}
4073
4074
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4075
4076
		if ( $this->message || $this->error || $this->privacy_checks ) {
4077
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4078
		}
4079
4080
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4081
	}
4082
4083
	function admin_notices() {
4084
4085
		if ( $this->error ) {
4086
?>
4087
<div id="message" class="jetpack-message jetpack-err">
4088
	<div class="squeezer">
4089
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4090
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4091
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4092
<?php	endif; ?>
4093
	</div>
4094
</div>
4095
<?php
4096
		}
4097
4098
		if ( $this->message ) {
4099
?>
4100
<div id="message" class="jetpack-message">
4101
	<div class="squeezer">
4102
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4103
	</div>
4104
</div>
4105
<?php
4106
		}
4107
4108
		if ( $this->privacy_checks ) :
4109
			$module_names = $module_slugs = array();
4110
4111
			$privacy_checks = explode( ',', $this->privacy_checks );
4112
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4113
			foreach ( $privacy_checks as $module_slug ) {
4114
				$module = Jetpack::get_module( $module_slug );
4115
				if ( ! $module ) {
4116
					continue;
4117
				}
4118
4119
				$module_slugs[] = $module_slug;
4120
				$module_names[] = "<strong>{$module['name']}</strong>";
4121
			}
4122
4123
			$module_slugs = join( ',', $module_slugs );
4124
?>
4125
<div id="message" class="jetpack-message jetpack-err">
4126
	<div class="squeezer">
4127
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4128
		<p><?php
4129
			echo wp_kses(
4130
				wptexturize(
4131
					wp_sprintf(
4132
						_nx(
4133
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4134
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4135
							count( $privacy_checks ),
4136
							'%l = list of Jetpack module/feature names',
4137
							'jetpack'
4138
						),
4139
						$module_names
4140
					)
4141
				),
4142
				array( 'strong' => true )
4143
			);
4144
4145
			echo "\n<br />\n";
4146
4147
			echo wp_kses(
4148
				sprintf(
4149
					_nx(
4150
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4151
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4152
						count( $privacy_checks ),
4153
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4154
						'jetpack'
4155
					),
4156
					wp_nonce_url(
4157
						Jetpack::admin_url(
4158
							array(
4159
								'page'   => 'jetpack',
4160
								'action' => 'deactivate',
4161
								'module' => urlencode( $module_slugs ),
4162
							)
4163
						),
4164
						"jetpack_deactivate-$module_slugs"
4165
					),
4166
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4167
				),
4168
				array( 'a' => array( 'href' => true, 'title' => true ) )
4169
			);
4170
		?></p>
4171
	</div>
4172
</div>
4173
<?php endif;
4174
	}
4175
4176
	/**
4177
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4178
	 */
4179
	function stat( $group, $detail ) {
4180
		if ( ! isset( $this->stats[ $group ] ) )
4181
			$this->stats[ $group ] = array();
4182
		$this->stats[ $group ][] = $detail;
4183
	}
4184
4185
	/**
4186
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4187
	 */
4188
	function do_stats( $method = '' ) {
4189
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4190
			foreach ( $this->stats as $group => $stats ) {
4191
				if ( is_array( $stats ) && count( $stats ) ) {
4192
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4193
					if ( 'server_side' === $method ) {
4194
						self::do_server_side_stat( $args );
4195
					} else {
4196
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4197
					}
4198
				}
4199
				unset( $this->stats[ $group ] );
4200
			}
4201
		}
4202
	}
4203
4204
	/**
4205
	 * Runs stats code for a one-off, server-side.
4206
	 *
4207
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4208
	 *
4209
	 * @return bool If it worked.
4210
	 */
4211
	static function do_server_side_stat( $args ) {
4212
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4213
		if ( is_wp_error( $response ) )
4214
			return false;
4215
4216
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4217
			return false;
4218
4219
		return true;
4220
	}
4221
4222
	/**
4223
	 * Builds the stats url.
4224
	 *
4225
	 * @param $args array|string The arguments to append to the URL.
4226
	 *
4227
	 * @return string The URL to be pinged.
4228
	 */
4229
	static function build_stats_url( $args ) {
4230
		$defaults = array(
4231
			'v'    => 'wpcom2',
4232
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4233
		);
4234
		$args     = wp_parse_args( $args, $defaults );
4235
		/**
4236
		 * Filter the URL used as the Stats tracking pixel.
4237
		 *
4238
		 * @since 2.3.2
4239
		 *
4240
		 * @param string $url Base URL used as the Stats tracking pixel.
4241
		 */
4242
		$base_url = apply_filters(
4243
			'jetpack_stats_base_url',
4244
			'https://pixel.wp.com/g.gif'
4245
		);
4246
		$url      = add_query_arg( $args, $base_url );
4247
		return $url;
4248
	}
4249
4250
	static function translate_current_user_to_role() {
4251
		foreach ( self::$capability_translations as $role => $cap ) {
4252
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
4253
				return $role;
4254
			}
4255
		}
4256
4257
		return false;
4258
	}
4259
4260
	static function translate_user_to_role( $user ) {
4261
		foreach ( self::$capability_translations as $role => $cap ) {
4262
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
4263
				return $role;
4264
			}
4265
		}
4266
4267
		return false;
4268
    }
4269
4270
	static function translate_role_to_cap( $role ) {
4271
		if ( ! isset( self::$capability_translations[$role] ) ) {
4272
			return false;
4273
		}
4274
4275
		return self::$capability_translations[$role];
4276
	}
4277
4278
	static function sign_role( $role, $user_id = null ) {
4279
		if ( empty( $user_id ) ) {
4280
			$user_id = (int) get_current_user_id();
4281
		}
4282
4283
		if ( ! $user_id  ) {
4284
			return false;
4285
		}
4286
4287
		$token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4288
		if ( ! $token || is_wp_error( $token ) ) {
4289
			return false;
4290
		}
4291
4292
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4293
	}
4294
4295
4296
	/**
4297
	 * Builds a URL to the Jetpack connection auth page
4298
	 *
4299
	 * @since 3.9.5
4300
	 *
4301
	 * @param bool $raw If true, URL will not be escaped.
4302
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4303
	 *                              If string, will be a custom redirect.
4304
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4305
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4306
	 *
4307
	 * @return string Connect URL
4308
	 */
4309
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4310
		$site_id = Jetpack_Options::get_option( 'id' );
4311
		$blog_token = Jetpack_Data::get_access_token();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
4312
4313
		if ( $register || ! $blog_token || ! $site_id ) {
4314
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4315
4316
			if ( ! empty( $redirect ) ) {
4317
				$url = add_query_arg(
4318
					'redirect',
4319
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4320
					$url
4321
				);
4322
			}
4323
4324
			if( is_network_admin() ) {
4325
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4326
			}
4327
		} else {
4328
4329
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4330
			// because otherwise this logic can get us in to a loop.
4331
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4332
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4333
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4334
4335
				$response = Client::wpcom_json_api_request_as_blog(
4336
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4337
					'1.1'
4338
				);
4339
4340
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4341
4342
					// Generating a register URL instead to refresh the existing token
4343
					return $this->build_connect_url( $raw, $redirect, $from, true );
4344
				}
4345
			}
4346
4347
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4348
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4349
			}
4350
4351
			$role = self::translate_current_user_to_role();
4352
			$signed_role = self::sign_role( $role );
4353
4354
			$user = wp_get_current_user();
4355
4356
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4357
			$redirect = $redirect
4358
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4359
				: $jetpack_admin_page;
4360
4361
			if( isset( $_REQUEST['is_multisite'] ) ) {
4362
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4363
			}
4364
4365
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4366
4367
			/**
4368
			 * Filter the type of authorization.
4369
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4370
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4371
			 *
4372
			 * @since 4.3.3
4373
			 *
4374
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4375
			 */
4376
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4377
4378
4379
			$tracks = new Tracking();
4380
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4381
4382
			$args = urlencode_deep(
4383
				array(
4384
					'response_type' => 'code',
4385
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4386
					'redirect_uri'  => add_query_arg(
4387
						array(
4388
							'action'   => 'authorize',
4389
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4390
							'redirect' => urlencode( $redirect ),
4391
						),
4392
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4393
					),
4394
					'state'         => $user->ID,
4395
					'scope'         => $signed_role,
4396
					'user_email'    => $user->user_email,
4397
					'user_login'    => $user->user_login,
4398
					'is_active'     => Jetpack::is_active(),
4399
					'jp_version'    => JETPACK__VERSION,
4400
					'auth_type'     => $auth_type,
4401
					'secret'        => $secrets['secret_1'],
4402
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4403
					'blogname'      => get_option( 'blogname' ),
4404
					'site_url'      => site_url(),
4405
					'home_url'      => home_url(),
4406
					'site_icon'     => get_site_icon_url(),
4407
					'site_lang'     => get_locale(),
4408
					'_ui'           => $tracks_identity['_ui'],
4409
					'_ut'           => $tracks_identity['_ut'],
4410
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4411
				)
4412
			);
4413
4414
			self::apply_activation_source_to_args( $args );
4415
4416
			$url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
4417
		}
4418
4419
		if ( $from ) {
4420
			$url = add_query_arg( 'from', $from, $url );
4421
		}
4422
4423
		// Ensure that class to get the affiliate code is loaded
4424
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4425
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4426
		}
4427
		// Get affiliate code and add it to the URL
4428
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4429
4430
		$calypso_env = $this->get_calypso_env();
4431
4432
		if ( ! empty( $calypso_env ) ) {
4433
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4434
		}
4435
4436
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4437
	}
4438
4439
	/**
4440
	 * Get our assumed site creation date.
4441
	 * Calculated based on the earlier date of either:
4442
	 * - Earliest admin user registration date.
4443
	 * - Earliest date of post of any post type.
4444
	 *
4445
	 * @since 7.2.0
4446
	 *
4447
	 * @return string Assumed site creation date and time.
4448
	 */
4449 View Code Duplication
	public static function get_assumed_site_creation_date() {
4450
		$earliest_registered_users = get_users( array(
4451
			'role'    => 'administrator',
4452
			'orderby' => 'user_registered',
4453
			'order'   => 'ASC',
4454
			'fields'  => array( 'user_registered' ),
4455
			'number'  => 1,
4456
		) );
4457
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4458
4459
		$earliest_posts = get_posts( array(
4460
			'posts_per_page' => 1,
4461
			'post_type'      => 'any',
4462
			'post_status'    => 'any',
4463
			'orderby'        => 'date',
4464
			'order'          => 'ASC',
4465
		) );
4466
4467
		// If there are no posts at all, we'll count only on user registration date.
4468
		if ( $earliest_posts ) {
4469
			$earliest_post_date = $earliest_posts[0]->post_date;
4470
		} else {
4471
			$earliest_post_date = PHP_INT_MAX;
4472
		}
4473
4474
		return min( $earliest_registration_date, $earliest_post_date );
4475
	}
4476
4477 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4478
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4479
4480
		if ( $activation_source_name ) {
4481
			$args['_as'] = urlencode( $activation_source_name );
4482
		}
4483
4484
		if ( $activation_source_keyword ) {
4485
			$args['_ak'] = urlencode( $activation_source_keyword );
4486
		}
4487
	}
4488
4489
	function build_reconnect_url( $raw = false ) {
4490
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4491
		return $raw ? $url : esc_url( $url );
4492
	}
4493
4494
	public static function admin_url( $args = null ) {
4495
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4496
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4497
		return $url;
4498
	}
4499
4500
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4501
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4502
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4503
	}
4504
4505
	function dismiss_jetpack_notice() {
4506
4507
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4508
			return;
4509
		}
4510
4511
		switch( $_GET['jetpack-notice'] ) {
4512
			case 'dismiss':
4513
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4514
4515
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4516
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4517
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4518
				}
4519
				break;
4520
			case 'jetpack-protect-multisite-opt-out':
4521
4522
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4523
					// Don't show the banner again
4524
4525
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4526
					// redirect back to the page that had the notice
4527
					if ( wp_get_referer() ) {
4528
						wp_safe_redirect( wp_get_referer() );
4529
					} else {
4530
						// Take me to Jetpack
4531
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4532
					}
4533
				}
4534
				break;
4535
		}
4536
	}
4537
4538
	public static function sort_modules( $a, $b ) {
4539
		if ( $a['sort'] == $b['sort'] )
4540
			return 0;
4541
4542
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4543
	}
4544
4545
	function ajax_recheck_ssl() {
4546
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4547
		$result = Jetpack::permit_ssl( true );
4548
		wp_send_json( array(
4549
			'enabled' => $result,
4550
			'message' => get_transient( 'jetpack_https_test_message' )
4551
		) );
4552
	}
4553
4554
/* Client API */
4555
4556
	/**
4557
	 * Returns the requested Jetpack API URL
4558
	 *
4559
	 * @return string
4560
	 */
4561
	public static function api_url( $relative_url ) {
4562
		return trailingslashit( JETPACK__API_BASE . $relative_url  ) . JETPACK__API_VERSION . '/';
4563
	}
4564
4565
	/**
4566
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4567
	 */
4568
	public static function fix_url_for_bad_hosts( $url ) {
4569
		if ( 0 !== strpos( $url, 'https://' ) ) {
4570
			return $url;
4571
		}
4572
4573
		switch ( JETPACK_CLIENT__HTTPS ) {
4574
			case 'ALWAYS' :
4575
				return $url;
4576
			case 'NEVER' :
4577
				return set_url_scheme( $url, 'http' );
4578
			// default : case 'AUTO' :
4579
		}
4580
4581
		// we now return the unmodified SSL URL by default, as a security precaution
4582
		return $url;
4583
	}
4584
4585
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4586
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4587
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4588
			if ( ! empty( $_GET['onboarding'] ) ) {
4589
				$jpo = $_GET;
4590
			} else {
4591
				$jpo = json_decode( $request_data, true );
4592
			}
4593
4594
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4595
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4596
4597
			if (
4598
				isset( $jpo_user )
4599
				&& isset( $jpo_token )
4600
				&& is_email( $jpo_user )
4601
				&& ctype_alnum( $jpo_token )
4602
				&& isset( $_GET['rest_route'] )
4603
				&& self::validate_onboarding_token_action(
4604
					$jpo_token,
4605
					$_GET['rest_route']
4606
				)
4607
			) {
4608
				$jpUser = get_user_by( 'email', $jpo_user );
4609
				if ( is_a( $jpUser, 'WP_User' ) ) {
4610
					wp_set_current_user( $jpUser->ID );
4611
					$user_can = is_multisite()
4612
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4613
						: current_user_can( 'manage_options' );
4614
					if ( $user_can ) {
4615
						$token_type = 'user';
4616
						$token->external_user_id = $jpUser->ID;
4617
					}
4618
				}
4619
			}
4620
4621
			return array(
4622
				'type'      => $token_type,
0 ignored issues
show
The variable $token_type 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...
4623
				'token_key' => $token_key,
0 ignored issues
show
The variable $token_key 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...
4624
				'user_id'   => $token->external_user_id,
4625
			);
4626
		}
4627
4628
		return $token_data;
4629
	}
4630
4631
	/**
4632
	 * Create a random secret for validating onboarding payload
4633
	 *
4634
	 * @return string Secret token
4635
	 */
4636
	public static function create_onboarding_token() {
4637
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4638
			$token = wp_generate_password( 32, false );
4639
			Jetpack_Options::update_option( 'onboarding', $token );
4640
		}
4641
4642
		return $token;
4643
	}
4644
4645
	/**
4646
	 * Remove the onboarding token
4647
	 *
4648
	 * @return bool True on success, false on failure
4649
	 */
4650
	public static function invalidate_onboarding_token() {
4651
		return Jetpack_Options::delete_option( 'onboarding' );
4652
	}
4653
4654
	/**
4655
	 * Validate an onboarding token for a specific action
4656
	 *
4657
	 * @return boolean True if token/action pair is accepted, false if not
4658
	 */
4659
	public static function validate_onboarding_token_action( $token, $action ) {
4660
		// Compare tokens, bail if tokens do not match
4661
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4662
			return false;
4663
		}
4664
4665
		// List of valid actions we can take
4666
		$valid_actions = array(
4667
			'/jetpack/v4/settings',
4668
		);
4669
4670
		// Whitelist the action
4671
		if ( ! in_array( $action, $valid_actions ) ) {
4672
			return false;
4673
		}
4674
4675
		return true;
4676
	}
4677
4678
	/**
4679
	 * Checks to see if the URL is using SSL to connect with Jetpack
4680
	 *
4681
	 * @since 2.3.3
4682
	 * @return boolean
4683
	 */
4684
	public static function permit_ssl( $force_recheck = false ) {
4685
		// Do some fancy tests to see if ssl is being supported
4686
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4687
			$message = '';
4688
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4689
				$ssl = 0;
4690
			} else {
4691
				switch ( JETPACK_CLIENT__HTTPS ) {
4692
					case 'NEVER':
4693
						$ssl = 0;
4694
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4695
						break;
4696
					case 'ALWAYS':
4697
					case 'AUTO':
4698
					default:
4699
						$ssl = 1;
4700
						break;
4701
				}
4702
4703
				// If it's not 'NEVER', test to see
4704
				if ( $ssl ) {
4705
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4706
						$ssl = 0;
4707
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4708
					} else {
4709
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4710
						if ( is_wp_error( $response ) ) {
4711
							$ssl = 0;
4712
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4713
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4714
							$ssl = 0;
4715
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4716
						}
4717
					}
4718
				}
4719
			}
4720
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4721
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4722
		}
4723
4724
		return (bool) $ssl;
4725
	}
4726
4727
	/*
4728
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4729
	 */
4730
	public function alert_auto_ssl_fail() {
4731
		if ( ! current_user_can( 'manage_options' ) )
4732
			return;
4733
4734
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4735
		?>
4736
4737
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4738
			<div class="jp-banner__content">
4739
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4740
				<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>
4741
				<p>
4742
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4743
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4744
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4745
				</p>
4746
				<p>
4747
					<?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' ),
4748
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4749
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4750
				</p>
4751
			</div>
4752
		</div>
4753
		<style>
4754
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4755
		</style>
4756
		<script type="text/javascript">
4757
			jQuery( document ).ready( function( $ ) {
4758
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4759
					var $this = $( this );
4760
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4761
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4762
					e.preventDefault();
4763
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4764
					$.post( ajaxurl, data )
4765
					  .done( function( response ) {
4766
					  	if ( response.enabled ) {
4767
					  		$( '#jetpack-ssl-warning' ).hide();
4768
					  	} else {
4769
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4770
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4771
					  	}
4772
					  }.bind( $this ) );
4773
				} );
4774
			} );
4775
		</script>
4776
4777
		<?php
4778
	}
4779
4780
	/**
4781
	 * Returns the Jetpack XML-RPC API
4782
	 *
4783
	 * @return string
4784
	 */
4785
	public static function xmlrpc_api_url() {
4786
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4787
		return untrailingslashit( $base ) . '/xmlrpc.php';
4788
	}
4789
4790
	public static function connection() {
4791
		return self::init()->connection_manager;
4792
	}
4793
4794
	/**
4795
	 * Creates two secret tokens and the end of life timestamp for them.
4796
	 *
4797
	 * Note these tokens are unique per call, NOT static per site for connecting.
4798
	 *
4799
	 * @since 2.6
4800
	 * @return array
4801
	 */
4802
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4803
		if ( false === $user_id ) {
4804
			$user_id = get_current_user_id();
4805
		}
4806
4807
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4808
	}
4809
4810
	public static function get_secrets( $action, $user_id ) {
4811
		$secrets = self::connection()->get_secrets( $action, $user_id );
4812
4813
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4814
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_missing'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4815
		}
4816
4817
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4818
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'verify_secrets_expired'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4819
		}
4820
4821
		return $secrets;
4822
	}
4823
4824
	/**
4825
	 * @deprecated 7.5 Use Connection_Manager instead.
4826
	 *
4827
	 * @param $action
4828
	 * @param $user_id
4829
	 */
4830
	public static function delete_secrets( $action, $user_id ) {
4831
		return self::connection()->delete_secrets( $action, $user_id );
4832
	}
4833
4834
	/**
4835
	 * Builds the timeout limit for queries talking with the wpcom servers.
4836
	 *
4837
	 * Based on local php max_execution_time in php.ini
4838
	 *
4839
	 * @since 2.6
4840
	 * @return int
4841
	 * @deprecated
4842
	 **/
4843
	public function get_remote_query_timeout_limit() {
4844
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4845
		return Jetpack::get_max_execution_time();
4846
	}
4847
4848
	/**
4849
	 * Builds the timeout limit for queries talking with the wpcom servers.
4850
	 *
4851
	 * Based on local php max_execution_time in php.ini
4852
	 *
4853
	 * @since 5.4
4854
	 * @return int
4855
	 **/
4856
	public static function get_max_execution_time() {
4857
		$timeout = (int) ini_get( 'max_execution_time' );
4858
4859
		// Ensure exec time set in php.ini
4860
		if ( ! $timeout ) {
4861
			$timeout = 30;
4862
		}
4863
		return $timeout;
4864
	}
4865
4866
	/**
4867
	 * Sets a minimum request timeout, and returns the current timeout
4868
	 *
4869
	 * @since 5.4
4870
	 **/
4871 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
4872
		$timeout = self::get_max_execution_time();
4873
		if ( $timeout < $min_timeout ) {
4874
			$timeout = $min_timeout;
4875
			set_time_limit( $timeout );
4876
		}
4877
		return $timeout;
4878
	}
4879
4880
4881
	/**
4882
	 * Takes the response from the Jetpack register new site endpoint and
4883
	 * verifies it worked properly.
4884
	 *
4885
	 * @since 2.6
4886
	 * @return string|Jetpack_Error A JSON object on success or Jetpack_Error on failures
4887
	 **/
4888
	public function validate_remote_register_response( $response ) {
4889
	  if ( is_wp_error( $response ) ) {
4890
			return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'register_http_request_failed'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4891
		}
4892
4893
		$code   = wp_remote_retrieve_response_code( $response );
4894
		$entity = wp_remote_retrieve_body( $response );
4895
		if ( $entity )
4896
			$registration_response = json_decode( $entity );
4897
		else
4898
			$registration_response = false;
4899
4900
		$code_type = intval( $code / 100 );
4901
		if ( 5 == $code_type ) {
4902
			return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_5??'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4903
		} elseif ( 408 == $code ) {
4904
			return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_408'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4905
		} elseif ( ! empty( $registration_response->error ) ) {
4906
			if ( 'xml_rpc-32700' == $registration_response->error && ! function_exists( 'xml_parser_create' ) ) {
4907
				$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' );
4908
			} else {
4909
				$error_description = isset( $registration_response->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $registration_response->error_description ) : '';
4910
			}
4911
4912
			return new Jetpack_Error( (string) $registration_response->error, $error_description, $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with (string) $registration_response->error.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4913
		} elseif ( 200 != $code ) {
4914
			return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'wpcom_bad_response'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4915
		}
4916
4917
		// Jetpack ID error block
4918 View Code Duplication
		if ( empty( $registration_response->jetpack_id ) ) {
4919
			return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4920
		} elseif ( ! is_scalar( $registration_response->jetpack_id ) ) {
4921
			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 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4922
		} elseif ( preg_match( '/[^0-9]/', $registration_response->jetpack_id ) ) {
4923
			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 );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4924
		}
4925
4926
	    return $registration_response;
4927
	}
4928
	/**
4929
	 * @return bool|WP_Error
4930
	 */
4931
	public static function register() {
4932
		$tracking = new Tracking();
4933
		$tracking->record_user_event( 'jpc_register_begin' );
4934
		add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
4935
		$secrets = Jetpack::generate_secrets( 'register' );
4936
4937 View Code Duplication
		if (
4938
			empty( $secrets['secret_1'] ) ||
4939
			empty( $secrets['secret_2'] ) ||
4940
			empty( $secrets['exp'] )
4941
		) {
4942
			return new Jetpack_Error( 'missing_secrets' );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'missing_secrets'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4943
		}
4944
4945
		// better to try (and fail) to set a higher timeout than this system
4946
		// supports than to have register fail for more users than it should
4947
		$timeout = Jetpack::set_min_time_limit( 60 ) / 2;
4948
4949
		$gmt_offset = get_option( 'gmt_offset' );
4950
		if ( ! $gmt_offset ) {
4951
			$gmt_offset = 0;
4952
		}
4953
4954
		$stats_options = get_option( 'stats_options' );
4955
		$stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
4956
4957
		$tracks = new Tracking();
4958
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4959
4960
		$args = array(
4961
			'method'  => 'POST',
4962
			'body'    => array(
4963
				'siteurl'         => site_url(),
4964
				'home'            => home_url(),
4965
				'gmt_offset'      => $gmt_offset,
4966
				'timezone_string' => (string) get_option( 'timezone_string' ),
4967
				'site_name'       => (string) get_option( 'blogname' ),
4968
				'secret_1'        => $secrets['secret_1'],
4969
				'secret_2'        => $secrets['secret_2'],
4970
				'site_lang'       => get_locale(),
4971
				'timeout'         => $timeout,
4972
				'stats_id'        => $stats_id,
4973
				'state'           => get_current_user_id(),
4974
				'_ui'             => $tracks_identity['_ui'],
4975
				'_ut'             => $tracks_identity['_ut'],
4976
				'site_created'    => Jetpack::get_assumed_site_creation_date(),
4977
				'jetpack_version' => JETPACK__VERSION
4978
			),
4979
			'headers' => array(
4980
				'Accept' => 'application/json',
4981
			),
4982
			'timeout' => $timeout,
4983
		);
4984
4985
		self::apply_activation_source_to_args( $args['body'] );
4986
4987
		$response = Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
4988
4989
		// Make sure the response is valid and does not contain any Jetpack errors
4990
		$registration_details = Jetpack::init()->validate_remote_register_response( $response );
4991
		if ( is_wp_error( $registration_details ) ) {
4992
			return $registration_details;
4993
		} elseif ( ! $registration_details ) {
4994
			return new Jetpack_Error( 'unknown_error', __( 'Unknown error registering your Jetpack site', 'jetpack' ), wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'unknown_error'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4995
		}
4996
4997 View Code Duplication
		if ( empty( $registration_details->jetpack_secret ) || ! is_string( $registration_details->jetpack_secret ) ) {
4998
			return new Jetpack_Error( 'jetpack_secret', '', wp_remote_retrieve_response_code( $response ) );
0 ignored issues
show
The call to Jetpack_Error::__construct() has too many arguments starting with 'jetpack_secret'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
4999
		}
5000
5001
		if ( isset( $registration_details->jetpack_public ) ) {
5002
			$jetpack_public = (int) $registration_details->jetpack_public;
5003
		} else {
5004
			$jetpack_public = false;
5005
		}
5006
5007
		Jetpack_Options::update_options(
5008
			array(
5009
				'id'         => (int)    $registration_details->jetpack_id,
5010
				'blog_token' => (string) $registration_details->jetpack_secret,
5011
				'public'     => $jetpack_public,
5012
			)
5013
		);
5014
5015
		/**
5016
		 * Fires when a site is registered on WordPress.com.
5017
		 *
5018
		 * @since 3.7.0
5019
		 *
5020
		 * @param int $json->jetpack_id Jetpack Blog ID.
5021
		 * @param string $json->jetpack_secret Jetpack Blog Token.
5022
		 * @param int|bool $jetpack_public Is the site public.
5023
		 */
5024
		do_action( 'jetpack_site_registered', $registration_details->jetpack_id, $registration_details->jetpack_secret, $jetpack_public );
5025
5026
		// Initialize Jump Start for the first and only time.
5027
		if ( ! Jetpack_Options::get_option( 'jumpstart' ) ) {
5028
			Jetpack_Options::update_option( 'jumpstart', 'new_connection' );
5029
5030
			$jetpack = Jetpack::init();
5031
5032
			$jetpack->stat( 'jumpstart', 'unique-views' );
5033
			$jetpack->do_stats( 'server_side' );
5034
		};
5035
5036
		return true;
5037
	}
5038
5039
	/**
5040
	 * If the db version is showing something other that what we've got now, bump it to current.
5041
	 *
5042
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
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...
5043
	 */
5044
	public static function maybe_set_version_option() {
5045
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5046
		if ( JETPACK__VERSION != $version ) {
5047
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5048
5049
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5050
				/** This action is documented in class.jetpack.php */
5051
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5052
			}
5053
5054
			return true;
5055
		}
5056
		return false;
5057
	}
5058
5059
/* Client Server API */
5060
5061
	/**
5062
	 * Loads the Jetpack XML-RPC client
5063
	 */
5064
	public static function load_xml_rpc_client() {
5065
		require_once ABSPATH . WPINC . '/class-IXR.php';
5066
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5067
	}
5068
5069
	/**
5070
	 * Resets the saved authentication state in between testing requests.
5071
	 */
5072
	public function reset_saved_auth_state() {
5073
		$this->xmlrpc_verification = null;
5074
		$this->rest_authentication_status = null;
5075
	}
5076
5077
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5078
	// Uses the existing XMLRPC request signing implementation.
5079
	function wp_rest_authenticate( $user ) {
5080
		if ( ! empty( $user ) ) {
5081
			// Another authentication method is in effect.
5082
			return $user;
5083
		}
5084
5085
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5086
			// Nothing to do for this authentication method.
5087
			return null;
5088
		}
5089
5090
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5091
			// Nothing to do for this authentication method.
5092
			return null;
5093
		}
5094
5095
		// Ensure that we always have the request body available.  At this
5096
		// point, the WP REST API code to determine the request body has not
5097
		// run yet.  That code may try to read from 'php://input' later, but
5098
		// this can only be done once per request in PHP versions prior to 5.6.
5099
		// So we will go ahead and perform this read now if needed, and save
5100
		// the request body where both the Jetpack signature verification code
5101
		// and the WP REST API code can see it.
5102
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5103
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5104
		}
5105
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5106
5107
		// Only support specific request parameters that have been tested and
5108
		// are known to work with signature verification.  A different method
5109
		// can be passed to the WP REST API via the '?_method=' parameter if
5110
		// needed.
5111
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5112
			$this->rest_authentication_status = new WP_Error(
5113
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5114
				__( 'This request method is not supported.', 'jetpack' ),
5115
				array( 'status' => 400 )
5116
			);
5117
			return null;
5118
		}
5119
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5120
			$this->rest_authentication_status = new WP_Error(
5121
				'rest_invalid_request',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_request'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5122
				__( 'This request method does not support body parameters.', 'jetpack' ),
5123
				array( 'status' => 400 )
5124
			);
5125
			return null;
5126
		}
5127
5128
		$verified = $this->verify_xml_rpc_signature();
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack::verify_xml_rpc_signature() has been deprecated with message: use Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5129
5130
		if (
5131
			$verified &&
5132
			isset( $verified['type'] ) &&
5133
			'user' === $verified['type'] &&
5134
			! empty( $verified['user_id'] )
5135
		) {
5136
			// Authentication successful.
5137
			$this->rest_authentication_status = true;
5138
			return $verified['user_id'];
5139
		}
5140
5141
		// Something else went wrong.  Probably a signature error.
5142
		$this->rest_authentication_status = new WP_Error(
5143
			'rest_invalid_signature',
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'rest_invalid_signature'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5144
			__( 'The request is not signed correctly.', 'jetpack' ),
5145
			array( 'status' => 400 )
5146
		);
5147
		return null;
5148
	}
5149
5150
	/**
5151
	 * Report authentication status to the WP REST API.
5152
	 *
5153
	 * @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
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...
5154
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5155
	 */
5156
	public function wp_rest_authentication_errors( $value ) {
5157
		if ( $value !== null ) {
5158
			return $value;
5159
		}
5160
		return $this->rest_authentication_status;
5161
	}
5162
5163
	function add_nonce( $timestamp, $nonce ) {
5164
		global $wpdb;
5165
		static $nonces_used_this_request = array();
5166
5167
		if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
5168
			return $nonces_used_this_request["$timestamp:$nonce"];
5169
		}
5170
5171
		// This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
5172
		$timestamp = (int) $timestamp;
5173
		$nonce     = esc_sql( $nonce );
5174
5175
		// Raw query so we can avoid races: add_option will also update
5176
		$show_errors = $wpdb->show_errors( false );
5177
5178
		$old_nonce = $wpdb->get_row(
5179
			$wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
5180
		);
5181
5182
		if ( is_null( $old_nonce ) ) {
5183
			$return = $wpdb->query(
5184
				$wpdb->prepare(
5185
					"INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
5186
					"jetpack_nonce_{$timestamp}_{$nonce}",
5187
					time(),
5188
					'no'
5189
				)
5190
			);
5191
		} else {
5192
			$return = false;
5193
		}
5194
5195
		$wpdb->show_errors( $show_errors );
5196
5197
		$nonces_used_this_request["$timestamp:$nonce"] = $return;
5198
5199
		return $return;
5200
	}
5201
5202
	/**
5203
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5204
	 * Capture it here so we can verify the signature later.
5205
	 */
5206
	function xmlrpc_methods( $methods ) {
5207
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5208
		return $methods;
5209
	}
5210
5211
	function public_xmlrpc_methods( $methods ) {
5212
		if ( array_key_exists( 'wp.getOptions', $methods ) ) {
5213
			$methods['wp.getOptions'] = array( $this, 'jetpack_getOptions' );
5214
		}
5215
		return $methods;
5216
	}
5217
5218
	function jetpack_getOptions( $args ) {
5219
		global $wp_xmlrpc_server;
5220
5221
		$wp_xmlrpc_server->escape( $args );
5222
5223
		$username	= $args[1];
5224
		$password	= $args[2];
5225
5226
		if ( !$user = $wp_xmlrpc_server->login($username, $password) ) {
5227
			return $wp_xmlrpc_server->error;
5228
		}
5229
5230
		$options = array();
5231
		$user_data = $this->get_connected_user_data();
5232
		if ( is_array( $user_data ) ) {
5233
			$options['jetpack_user_id'] = array(
5234
				'desc'          => __( 'The WP.com user ID of the connected user', 'jetpack' ),
5235
				'readonly'      => true,
5236
				'value'         => $user_data['ID'],
5237
			);
5238
			$options['jetpack_user_login'] = array(
5239
				'desc'          => __( 'The WP.com username of the connected user', 'jetpack' ),
5240
				'readonly'      => true,
5241
				'value'         => $user_data['login'],
5242
			);
5243
			$options['jetpack_user_email'] = array(
5244
				'desc'          => __( 'The WP.com user email of the connected user', 'jetpack' ),
5245
				'readonly'      => true,
5246
				'value'         => $user_data['email'],
5247
			);
5248
			$options['jetpack_user_site_count'] = array(
5249
				'desc'          => __( 'The number of sites of the connected WP.com user', 'jetpack' ),
5250
				'readonly'      => true,
5251
				'value'         => $user_data['site_count'],
5252
			);
5253
		}
5254
		$wp_xmlrpc_server->blog_options = array_merge( $wp_xmlrpc_server->blog_options, $options );
5255
		$args = stripslashes_deep( $args );
5256
		return $wp_xmlrpc_server->wp_getOptions( $args );
5257
	}
5258
5259
	function xmlrpc_options( $options ) {
5260
		$jetpack_client_id = false;
5261
		if ( self::is_active() ) {
5262
			$jetpack_client_id = Jetpack_Options::get_option( 'id' );
5263
		}
5264
		$options['jetpack_version'] = array(
5265
				'desc'          => __( 'Jetpack Plugin Version', 'jetpack' ),
5266
				'readonly'      => true,
5267
				'value'         => JETPACK__VERSION,
5268
		);
5269
5270
		$options['jetpack_client_id'] = array(
5271
				'desc'          => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
5272
				'readonly'      => true,
5273
				'value'         => $jetpack_client_id,
5274
		);
5275
		return $options;
5276
	}
5277
5278
	public static function clean_nonces( $all = false ) {
5279
		global $wpdb;
5280
5281
		$sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
5282
		$sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
5283
5284
		if ( true !== $all ) {
5285
			$sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
5286
			$sql_args[] = time() - 3600;
5287
		}
5288
5289
		$sql .= ' ORDER BY `option_id` LIMIT 100';
5290
5291
		$sql = $wpdb->prepare( $sql, $sql_args );
5292
5293
		for ( $i = 0; $i < 1000; $i++ ) {
5294
			if ( ! $wpdb->query( $sql ) ) {
5295
				break;
5296
			}
5297
		}
5298
	}
5299
5300
	/**
5301
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5302
	 * SET: state( $key, $value );
5303
	 * GET: $value = state( $key );
5304
	 *
5305
	 * @param string $key
0 ignored issues
show
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...
5306
	 * @param string $value
0 ignored issues
show
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...
5307
	 * @param bool $restate private
5308
	 */
5309
	public static function state( $key = null, $value = null, $restate = false ) {
5310
		static $state = array();
5311
		static $path, $domain;
5312
		if ( ! isset( $path ) ) {
5313
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5314
			$admin_url = Jetpack::admin_url();
5315
			$bits      = wp_parse_url( $admin_url );
5316
5317
			if ( is_array( $bits ) ) {
5318
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5319
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5320
			} else {
5321
				$path = $domain = null;
5322
			}
5323
		}
5324
5325
		// Extract state from cookies and delete cookies
5326
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5327
			$yum = $_COOKIE[ 'jetpackState' ];
5328
			unset( $_COOKIE[ 'jetpackState' ] );
5329
			foreach ( $yum as $k => $v ) {
5330
				if ( strlen( $v ) )
5331
					$state[ $k ] = $v;
5332
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5333
			}
5334
		}
5335
5336
		if ( $restate ) {
5337
			foreach ( $state as $k => $v ) {
5338
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5339
			}
5340
			return;
5341
		}
5342
5343
		// Get a state variable
5344
		if ( isset( $key ) && ! isset( $value ) ) {
5345
			if ( array_key_exists( $key, $state ) )
5346
				return $state[ $key ];
5347
			return null;
5348
		}
5349
5350
		// Set a state variable
5351
		if ( isset ( $key ) && isset( $value ) ) {
5352
			if( is_array( $value ) && isset( $value[0] ) ) {
5353
				$value = $value[0];
5354
			}
5355
			$state[ $key ] = $value;
5356
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5357
		}
5358
	}
5359
5360
	public static function restate() {
5361
		Jetpack::state( null, null, true );
5362
	}
5363
5364
	public static function check_privacy( $file ) {
5365
		static $is_site_publicly_accessible = null;
5366
5367
		if ( is_null( $is_site_publicly_accessible ) ) {
5368
			$is_site_publicly_accessible = false;
5369
5370
			Jetpack::load_xml_rpc_client();
5371
			$rpc = new Jetpack_IXR_Client();
5372
5373
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5374
			if ( $success ) {
5375
				$response = $rpc->getResponse();
5376
				if ( $response ) {
5377
					$is_site_publicly_accessible = true;
5378
				}
5379
			}
5380
5381
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5382
		}
5383
5384
		if ( $is_site_publicly_accessible ) {
5385
			return;
5386
		}
5387
5388
		$module_slug = self::get_module_slug( $file );
5389
5390
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5391
		if ( ! $privacy_checks ) {
5392
			$privacy_checks = $module_slug;
5393
		} else {
5394
			$privacy_checks .= ",$module_slug";
5395
		}
5396
5397
		Jetpack::state( 'privacy_checks', $privacy_checks );
5398
	}
5399
5400
	/**
5401
	 * Helper method for multicall XMLRPC.
5402
	 */
5403
	public static function xmlrpc_async_call() {
5404
		global $blog_id;
5405
		static $clients = array();
5406
5407
		$client_blog_id = is_multisite() ? $blog_id : 0;
5408
5409
		if ( ! isset( $clients[$client_blog_id] ) ) {
5410
			Jetpack::load_xml_rpc_client();
5411
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5412
			if ( function_exists( 'ignore_user_abort' ) ) {
5413
				ignore_user_abort( true );
5414
			}
5415
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5416
		}
5417
5418
		$args = func_get_args();
5419
5420
		if ( ! empty( $args[0] ) ) {
5421
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5422
		} elseif ( is_multisite() ) {
5423
			foreach ( $clients as $client_blog_id => $client ) {
5424
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5425
					continue;
5426
				}
5427
5428
				$switch_success = switch_to_blog( $client_blog_id, true );
5429
				if ( ! $switch_success ) {
5430
					continue;
5431
				}
5432
5433
				flush();
5434
				$client->query();
5435
5436
				restore_current_blog();
5437
			}
5438
		} else {
5439
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5440
				flush();
5441
				$clients[0]->query();
5442
			}
5443
		}
5444
	}
5445
5446
	public static function staticize_subdomain( $url ) {
5447
5448
		// Extract hostname from URL
5449
		$host = parse_url( $url, PHP_URL_HOST );
5450
5451
		// Explode hostname on '.'
5452
		$exploded_host = explode( '.', $host );
5453
5454
		// Retrieve the name and TLD
5455
		if ( count( $exploded_host ) > 1 ) {
5456
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5457
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5458
			// Rebuild domain excluding subdomains
5459
			$domain = $name . '.' . $tld;
5460
		} else {
5461
			$domain = $host;
5462
		}
5463
		// Array of Automattic domains
5464
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5465
5466
		// Return $url if not an Automattic domain
5467
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5468
			return $url;
5469
		}
5470
5471
		if ( is_ssl() ) {
5472
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5473
		}
5474
5475
		srand( crc32( basename( $url ) ) );
5476
		$static_counter = rand( 0, 2 );
5477
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5478
5479
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5480
	}
5481
5482
/* JSON API Authorization */
5483
5484
	/**
5485
	 * Handles the login action for Authorizing the JSON API
5486
	 */
5487
	function login_form_json_api_authorization() {
5488
		$this->verify_json_api_authorization_request();
5489
5490
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5491
5492
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5493
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5494
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5495
	}
5496
5497
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5498
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5499
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5500
			return $url;
5501
		}
5502
5503
		$parsed_url = parse_url( $url );
5504
		$url = strtok( $url, '?' );
5505
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5506
		if ( ! empty( $parsed_url['query'] ) )
5507
			$url .= "&{$parsed_url['query']}";
5508
5509
		return $url;
5510
	}
5511
5512
	// Make sure the POSTed request is handled by the same action
5513
	function preserve_action_in_login_form_for_json_api_authorization() {
5514
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5515
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5516
	}
5517
5518
	// If someone logs in to approve API access, store the Access Code in usermeta
5519
	function store_json_api_authorization_token( $user_login, $user ) {
5520
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5521
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5522
		$token = wp_generate_password( 32, false );
5523
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5524
	}
5525
5526
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5527
	function allow_wpcom_public_api_domain( $domains ) {
5528
		$domains[] = 'public-api.wordpress.com';
5529
		return $domains;
5530
	}
5531
5532
	static function is_redirect_encoded( $redirect_url ) {
5533
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5534
	}
5535
5536
	// Add all wordpress.com environments to the safe redirect whitelist
5537
	function allow_wpcom_environments( $domains ) {
5538
		$domains[] = 'wordpress.com';
5539
		$domains[] = 'wpcalypso.wordpress.com';
5540
		$domains[] = 'horizon.wordpress.com';
5541
		$domains[] = 'calypso.localhost';
5542
		return $domains;
5543
	}
5544
5545
	// Add the Access Code details to the public-api.wordpress.com redirect
5546
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5547
		return add_query_arg(
5548
			urlencode_deep(
5549
				array(
5550
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5551
					'jetpack-user-id' => (int) $user->ID,
5552
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5553
				)
5554
			),
5555
			$redirect_to
5556
		);
5557
	}
5558
5559
5560
	/**
5561
	 * Verifies the request by checking the signature
5562
	 *
5563
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5564
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5565
	 *
5566
	 * @param null|array $environment
5567
	 */
5568
	function verify_json_api_authorization_request( $environment = null ) {
5569
		$environment = is_null( $environment )
5570
			? $_REQUEST
5571
			: $environment;
5572
5573
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
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...
5574
		$token = Jetpack_Data::get_access_token( $envUserId, $envToken );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Data::get_access_token() has been deprecated with message: 7.5 Use Connection_Manager instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
5575
		if ( ! $token || empty( $token->secret ) ) {
5576
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5577
		}
5578
5579
		$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' );
5580
5581
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5582
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5583
			/**
5584
			 * Jetpack authorisation request Error.
5585
			 *
5586
			 * @since 7.5.0
5587
			 *
5588
			 */
5589
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5590
			$die_error = sprintf(
5591
				/* translators: %s is a URL */
5592
				__( 'Your site is incorrectly double-encoding redirects from http to https. This is preventing Jetpack from authenticating your connection. Please visit our <a href="%s">support page</a> for details about how to resolve this.', 'jetpack' ),
5593
				'https://jetpack.com/support/double-encoding/'
5594
			);
5595
		}
5596
5597
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5598
5599
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5600
			$signature = $jetpack_signature->sign_request(
5601
				$environment['token'],
5602
				$environment['timestamp'],
5603
				$environment['nonce'],
5604
				'',
5605
				'GET',
5606
				$environment['jetpack_json_api_original_query'],
5607
				null,
5608
				true
5609
			);
5610
		} else {
5611
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5612
		}
5613
5614
		if ( ! $signature ) {
5615
			wp_die( $die_error );
5616
		} else if ( is_wp_error( $signature ) ) {
5617
			wp_die( $die_error );
5618
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5619
			if ( is_ssl() ) {
5620
				// 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
5621
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5622
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5623
					wp_die( $die_error );
5624
				}
5625
			} else {
5626
				wp_die( $die_error );
5627
			}
5628
		}
5629
5630
		$timestamp = (int) $environment['timestamp'];
5631
		$nonce     = stripslashes( (string) $environment['nonce'] );
5632
5633
		if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
5634
			// De-nonce the nonce, at least for 5 minutes.
5635
			// 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)
5636
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5637
			if ( $old_nonce_time < time() - 300 ) {
5638
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5639
			}
5640
		}
5641
5642
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5643
		$data_filters = array(
5644
			'state'        => 'opaque',
5645
			'client_id'    => 'int',
5646
			'client_title' => 'string',
5647
			'client_image' => 'url',
5648
		);
5649
5650
		foreach ( $data_filters as $key => $sanitation ) {
5651
			if ( ! isset( $data->$key ) ) {
5652
				wp_die( $die_error );
5653
			}
5654
5655
			switch ( $sanitation ) {
5656
			case 'int' :
5657
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5658
				break;
5659
			case 'opaque' :
5660
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5661
				break;
5662
			case 'string' :
5663
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5664
				break;
5665
			case 'url' :
5666
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5667
				break;
5668
			}
5669
		}
5670
5671
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5672
			wp_die( $die_error );
5673
		}
5674
	}
5675
5676
	function login_message_json_api_authorization( $message ) {
5677
		return '<p class="message">' . sprintf(
5678
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5679
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5680
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5681
	}
5682
5683
	/**
5684
	 * Get $content_width, but with a <s>twist</s> filter.
5685
	 */
5686
	public static function get_content_width() {
5687
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5688
			? $GLOBALS['content_width']
5689
			: false;
5690
		/**
5691
		 * Filter the Content Width value.
5692
		 *
5693
		 * @since 2.2.3
5694
		 *
5695
		 * @param string $content_width Content Width value.
5696
		 */
5697
		return apply_filters( 'jetpack_content_width', $content_width );
5698
	}
5699
5700
	/**
5701
	 * Pings the WordPress.com Mirror Site for the specified options.
5702
	 *
5703
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5704
	 *
5705
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5706
	 */
5707
	public function get_cloud_site_options( $option_names ) {
5708
		$option_names = array_filter( (array) $option_names, 'is_string' );
5709
5710
		Jetpack::load_xml_rpc_client();
5711
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5712
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5713
		if ( $xml->isError() ) {
5714
			return array(
5715
				'error_code' => $xml->getErrorCode(),
5716
				'error_msg'  => $xml->getErrorMessage(),
5717
			);
5718
		}
5719
		$cloud_site_options = $xml->getResponse();
5720
5721
		return $cloud_site_options;
5722
	}
5723
5724
	/**
5725
	 * Checks if the site is currently in an identity crisis.
5726
	 *
5727
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5728
	 */
5729
	public static function check_identity_crisis() {
5730
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5731
			return false;
5732
		}
5733
5734
		return Jetpack_Options::get_option( 'sync_error_idc' );
5735
	}
5736
5737
	/**
5738
	 * Checks whether the home and siteurl specifically are whitelisted
5739
	 * Written so that we don't have re-check $key and $value params every time
5740
	 * we want to check if this site is whitelisted, for example in footer.php
5741
	 *
5742
	 * @since  3.8.0
5743
	 * @return bool True = already whitelisted False = not whitelisted
5744
	 */
5745
	public static function is_staging_site() {
5746
		$is_staging = false;
5747
5748
		$known_staging = array(
5749
			'urls' => array(
5750
				'#\.staging\.wpengine\.com$#i', // WP Engine
5751
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5752
				'#\.stage\.site$#i'             // DreamPress
5753
			),
5754
			'constants' => array(
5755
				'IS_WPE_SNAPSHOT',      // WP Engine
5756
				'KINSTA_DEV_ENV',       // Kinsta.com
5757
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5758
				'JETPACK_STAGING_MODE', // Generic
5759
			)
5760
		);
5761
		/**
5762
		 * Filters the flags of known staging sites.
5763
		 *
5764
		 * @since 3.9.0
5765
		 *
5766
		 * @param array $known_staging {
5767
		 *     An array of arrays that each are used to check if the current site is staging.
5768
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5769
		 *     @type array $constants PHP constants of known staging/developement environments.
5770
		 *  }
5771
		 */
5772
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5773
5774
		if ( isset( $known_staging['urls'] ) ) {
5775
			foreach ( $known_staging['urls'] as $url ){
5776
				if ( preg_match( $url, site_url() ) ) {
5777
					$is_staging = true;
5778
					break;
5779
				}
5780
			}
5781
		}
5782
5783
		if ( isset( $known_staging['constants'] ) ) {
5784
			foreach ( $known_staging['constants'] as $constant ) {
5785
				if ( defined( $constant ) && constant( $constant ) ) {
5786
					$is_staging = true;
5787
				}
5788
			}
5789
		}
5790
5791
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5792
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5793
			$is_staging = true;
5794
		}
5795
5796
		/**
5797
		 * Filters is_staging_site check.
5798
		 *
5799
		 * @since 3.9.0
5800
		 *
5801
		 * @param bool $is_staging If the current site is a staging site.
5802
		 */
5803
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5804
	}
5805
5806
	/**
5807
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5808
	 *
5809
	 * @since 4.4.0
5810
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5811
	 *
5812
	 * @return bool
5813
	 */
5814
	public static function validate_sync_error_idc_option() {
5815
		$is_valid = false;
5816
5817
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5818
		if ( false === $idc_allowed ) {
5819
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5820
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5821
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5822
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5823
				$transient_duration = HOUR_IN_SECONDS;
5824
			} else {
5825
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5826
				$idc_allowed = '1';
5827
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5828
			}
5829
5830
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5831
		}
5832
5833
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5834
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5835
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5836
			$local_options = self::get_sync_error_idc_option();
5837
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5838
				$is_valid = true;
5839
			}
5840
		}
5841
5842
		/**
5843
		 * Filters whether the sync_error_idc option is valid.
5844
		 *
5845
		 * @since 4.4.0
5846
		 *
5847
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5848
		 */
5849
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5850
5851
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5852
			// Since the option exists, and did not validate, delete it
5853
			Jetpack_Options::delete_option( 'sync_error_idc' );
5854
		}
5855
5856
		return $is_valid;
5857
	}
5858
5859
	/**
5860
	 * Normalizes a url by doing three things:
5861
	 *  - Strips protocol
5862
	 *  - Strips www
5863
	 *  - Adds a trailing slash
5864
	 *
5865
	 * @since 4.4.0
5866
	 * @param string $url
5867
	 * @return WP_Error|string
5868
	 */
5869
	public static function normalize_url_protocol_agnostic( $url ) {
5870
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5871
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5872
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
The call to WP_Error::__construct() has too many arguments starting with 'cannot_parse_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
5873
		}
5874
5875
		// Strip www and protocols
5876
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5877
		return $url;
5878
	}
5879
5880
	/**
5881
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5882
	 *
5883
	 * @since 4.4.0
5884
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5885
	 *
5886
	 * @param array $response
5887
	 * @return array Array of the local urls, wpcom urls, and error code
5888
	 */
5889
	public static function get_sync_error_idc_option( $response = array() ) {
5890
		// Since the local options will hit the database directly, store the values
5891
		// in a transient to allow for autoloading and caching on subsequent views.
5892
		$local_options = get_transient( 'jetpack_idc_local' );
5893
		if ( false === $local_options ) {
5894
			$local_options = array(
5895
				'home'    => Jetpack_Sync_Functions::home_url(),
5896
				'siteurl' => Jetpack_Sync_Functions::site_url(),
5897
			);
5898
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5899
		}
5900
5901
		$options = array_merge( $local_options, $response );
5902
5903
		$returned_values = array();
5904
		foreach( $options as $key => $option ) {
5905
			if ( 'error_code' === $key ) {
5906
				$returned_values[ $key ] = $option;
5907
				continue;
5908
			}
5909
5910
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5911
				continue;
5912
			}
5913
5914
			$returned_values[ $key ] = $normalized_url;
5915
		}
5916
5917
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5918
5919
		return $returned_values;
5920
	}
5921
5922
	/**
5923
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5924
	 * If set to true, the site will be put into staging mode.
5925
	 *
5926
	 * @since 4.3.2
5927
	 * @return bool
5928
	 */
5929
	public static function sync_idc_optin() {
5930
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5931
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5932
		} else {
5933
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5934
		}
5935
5936
		/**
5937
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5938
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5939
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5940
		 *
5941
		 * @since 4.3.2
5942
		 *
5943
		 * @param bool $default Whether the site is opted in to IDC mitigation.
5944
		 */
5945
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
5946
	}
5947
5948
	/**
5949
	 * Maybe Use a .min.css stylesheet, maybe not.
5950
	 *
5951
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5952
	 */
5953
	public static function maybe_min_asset( $url, $path, $plugin ) {
5954
		// Short out on things trying to find actual paths.
5955
		if ( ! $path || empty( $plugin ) ) {
5956
			return $url;
5957
		}
5958
5959
		$path = ltrim( $path, '/' );
5960
5961
		// Strip out the abspath.
5962
		$base = dirname( plugin_basename( $plugin ) );
5963
5964
		// Short out on non-Jetpack assets.
5965
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
5966
			return $url;
5967
		}
5968
5969
		// File name parsing.
5970
		$file              = "{$base}/{$path}";
5971
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5972
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5973
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5974
		$extension         = array_shift( $file_name_parts_r );
5975
5976
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
5977
			// Already pointing at the minified version.
5978
			if ( 'min' === $file_name_parts_r[0] ) {
5979
				return $url;
5980
			}
5981
5982
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5983
			if ( file_exists( $min_full_path ) ) {
5984
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5985
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5986
				if ( 'css' === $extension ) {
5987
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5988
					self::$min_assets[ $key ] = $path;
5989
				}
5990
			}
5991
		}
5992
5993
		return $url;
5994
	}
5995
5996
	/**
5997
	 * If the asset is minified, let's flag .min as the suffix.
5998
	 *
5999
	 * Attached to `style_loader_src` filter.
6000
	 *
6001
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
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...
6002
	 * @param string $handle The registered handle of the script in question.
6003
	 * @param string $href The url of the asset in question.
0 ignored issues
show
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...
6004
	 */
6005
	public static function set_suffix_on_min( $src, $handle ) {
6006
		if ( false === strpos( $src, '.min.css' ) ) {
6007
			return $src;
6008
		}
6009
6010
		if ( ! empty( self::$min_assets ) ) {
6011
			foreach ( self::$min_assets as $file => $path ) {
6012
				if ( false !== strpos( $src, $file ) ) {
6013
					wp_style_add_data( $handle, 'suffix', '.min' );
6014
					return $src;
6015
				}
6016
			}
6017
		}
6018
6019
		return $src;
6020
	}
6021
6022
	/**
6023
	 * Maybe inlines a stylesheet.
6024
	 *
6025
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6026
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6027
	 *
6028
	 * Attached to `style_loader_tag` filter.
6029
	 *
6030
	 * @param string $tag The tag that would link to the external asset.
6031
	 * @param string $handle The registered handle of the script in question.
6032
	 *
6033
	 * @return string
6034
	 */
6035
	public static function maybe_inline_style( $tag, $handle ) {
6036
		global $wp_styles;
6037
		$item = $wp_styles->registered[ $handle ];
6038
6039
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6040
			return $tag;
6041
		}
6042
6043
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6044
			$href = $matches[1];
6045
			// Strip off query string
6046
			if ( $pos = strpos( $href, '?' ) ) {
6047
				$href = substr( $href, 0, $pos );
6048
			}
6049
			// Strip off fragment
6050
			if ( $pos = strpos( $href, '#' ) ) {
6051
				$href = substr( $href, 0, $pos );
6052
			}
6053
		} else {
6054
			return $tag;
6055
		}
6056
6057
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6058
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6059
			return $tag;
6060
		}
6061
6062
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6063
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6064
			// And this isn't the pass that actually deals with the RTL version...
6065
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6066
				// Short out, as the RTL version will deal with it in a moment.
6067
				return $tag;
6068
			}
6069
		}
6070
6071
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6072
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6073
		if ( $css ) {
6074
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6075
			if ( empty( $item->extra['after'] ) ) {
6076
				wp_add_inline_style( $handle, $css );
6077
			} else {
6078
				array_unshift( $item->extra['after'], $css );
6079
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6080
			}
6081
		}
6082
6083
		return $tag;
6084
	}
6085
6086
	/**
6087
	 * Loads a view file from the views
6088
	 *
6089
	 * Data passed in with the $data parameter will be available in the
6090
	 * template file as $data['value']
6091
	 *
6092
	 * @param string $template - Template file to load
6093
	 * @param array $data - Any data to pass along to the template
6094
	 * @return boolean - If template file was found
6095
	 **/
6096
	public function load_view( $template, $data = array() ) {
6097
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6098
6099
		if( file_exists( $views_dir . $template ) ) {
6100
			require_once( $views_dir . $template );
6101
			return true;
6102
		}
6103
6104
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6105
		return false;
6106
	}
6107
6108
	/**
6109
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6110
	 */
6111
	public function deprecated_hooks() {
6112
		global $wp_filter;
6113
6114
		/*
6115
		 * Format:
6116
		 * deprecated_filter_name => replacement_name
6117
		 *
6118
		 * If there is no replacement, use null for replacement_name
6119
		 */
6120
		$deprecated_list = array(
6121
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6122
			'wpl_sharing_2014_1'                                     => null,
6123
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6124
			'jetpack_identity_crisis_options_to_check'               => null,
6125
			'update_option_jetpack_single_user_site'                 => null,
6126
			'audio_player_default_colors'                            => null,
6127
			'add_option_jetpack_featured_images_enabled'             => null,
6128
			'add_option_jetpack_update_details'                      => null,
6129
			'add_option_jetpack_updates'                             => null,
6130
			'add_option_jetpack_network_name'                        => null,
6131
			'add_option_jetpack_network_allow_new_registrations'     => null,
6132
			'add_option_jetpack_network_add_new_users'               => null,
6133
			'add_option_jetpack_network_site_upload_space'           => null,
6134
			'add_option_jetpack_network_upload_file_types'           => null,
6135
			'add_option_jetpack_network_enable_administration_menus' => null,
6136
			'add_option_jetpack_is_multi_site'                       => null,
6137
			'add_option_jetpack_is_main_network'                     => null,
6138
			'add_option_jetpack_main_network_site'                   => null,
6139
			'jetpack_sync_all_registered_options'                    => null,
6140
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6141
			'jetpack_is_post_mailable'                               => null,
6142
			'jetpack_seo_site_host'                                  => null,
6143
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6144
			'jetpack_holiday_snow_option_name'                       => null,
6145
			'jetpack_holiday_chance_of_snow'                         => null,
6146
			'jetpack_holiday_snow_js_url'                            => null,
6147
			'jetpack_is_holiday_snow_season'                         => null,
6148
			'jetpack_holiday_snow_option_updated'                    => null,
6149
			'jetpack_holiday_snowing'                                => null,
6150
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6151
			'jetpack_cache_plans'                                    => null,
6152
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6153
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6154
			'jetpack_enable_site_verification'                       => null,
6155
			'can_display_jetpack_manage_notice'                      => null,
6156
			// Removed in Jetpack 7.3.0
6157
			'atd_load_scripts'                                       => null,
6158
			'atd_http_post_timeout'                                  => null,
6159
			'atd_http_post_error'                                    => null,
6160
			'atd_service_domain'                                     => null,
6161
		);
6162
6163
		// This is a silly loop depth. Better way?
6164
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6165
			if ( has_action( $hook ) ) {
6166
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6167
					foreach( $values AS $hooked ) {
6168
						if ( is_callable( $hooked['function'] ) ) {
6169
							$function_name = 'an anonymous function';
6170
						} else {
6171
							$function_name = $hooked['function'];
6172
						}
6173
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6174
					}
6175
				}
6176
			}
6177
		}
6178
	}
6179
6180
	/**
6181
	 * Converts any url in a stylesheet, to the correct absolute url.
6182
	 *
6183
	 * Considerations:
6184
	 *  - Normal, relative URLs     `feh.png`
6185
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6186
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6187
	 *  - Absolute URLs             `http://domain.com/feh.png`
6188
	 *  - Domain root relative URLs `/feh.png`
6189
	 *
6190
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6191
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6192
	 *
6193
	 * @return mixed|string
6194
	 */
6195
	public static function absolutize_css_urls( $css, $css_file_url ) {
6196
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6197
		$css_dir = dirname( $css_file_url );
6198
		$p       = parse_url( $css_dir );
6199
		$domain  = sprintf(
6200
					'%1$s//%2$s%3$s%4$s',
6201
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6202
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6203
					$p['host'],
6204
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6205
				);
6206
6207
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6208
			$find = $replace = array();
6209
			foreach ( $matches as $match ) {
6210
				$url = trim( $match['path'], "'\" \t" );
6211
6212
				// If this is a data url, we don't want to mess with it.
6213
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6214
					continue;
6215
				}
6216
6217
				// If this is an absolute or protocol-agnostic url,
6218
				// we don't want to mess with it.
6219
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6220
					continue;
6221
				}
6222
6223
				switch ( substr( $url, 0, 1 ) ) {
6224
					case '/':
6225
						$absolute = $domain . $url;
6226
						break;
6227
					default:
6228
						$absolute = $css_dir . '/' . $url;
6229
				}
6230
6231
				$find[]    = $match[0];
6232
				$replace[] = sprintf( 'url("%s")', $absolute );
6233
			}
6234
			$css = str_replace( $find, $replace, $css );
6235
		}
6236
6237
		return $css;
6238
	}
6239
6240
	/**
6241
	 * This methods removes all of the registered css files on the front end
6242
	 * from Jetpack in favor of using a single file. In effect "imploding"
6243
	 * all the files into one file.
6244
	 *
6245
	 * Pros:
6246
	 * - Uses only ONE css asset connection instead of 15
6247
	 * - Saves a minimum of 56k
6248
	 * - Reduces server load
6249
	 * - Reduces time to first painted byte
6250
	 *
6251
	 * Cons:
6252
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6253
	 *		should not cause any issues with themes.
6254
	 * - Plugins/themes dequeuing styles no longer do anything. See
6255
	 *		jetpack_implode_frontend_css filter for a workaround
6256
	 *
6257
	 * For some situations developers may wish to disable css imploding and
6258
	 * instead operate in legacy mode where each file loads seperately and
6259
	 * can be edited individually or dequeued. This can be accomplished with
6260
	 * the following line:
6261
	 *
6262
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6263
	 *
6264
	 * @since 3.2
6265
	 **/
6266
	public function implode_frontend_css( $travis_test = false ) {
6267
		$do_implode = true;
6268
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6269
			$do_implode = false;
6270
		}
6271
6272
		// Do not implode CSS when the page loads via the AMP plugin.
6273
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6274
			$do_implode = false;
6275
		}
6276
6277
		/**
6278
		 * Allow CSS to be concatenated into a single jetpack.css file.
6279
		 *
6280
		 * @since 3.2.0
6281
		 *
6282
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6283
		 */
6284
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6285
6286
		// Do not use the imploded file when default behavior was altered through the filter
6287
		if ( ! $do_implode ) {
6288
			return;
6289
		}
6290
6291
		// We do not want to use the imploded file in dev mode, or if not connected
6292
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6293
			if ( ! $travis_test ) {
6294
				return;
6295
			}
6296
		}
6297
6298
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6299
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6300
			return;
6301
		}
6302
6303
		/*
6304
		 * Now we assume Jetpack is connected and able to serve the single
6305
		 * file.
6306
		 *
6307
		 * In the future there will be a check here to serve the file locally
6308
		 * or potentially from the Jetpack CDN
6309
		 *
6310
		 * For now:
6311
		 * - Enqueue a single imploded css file
6312
		 * - Zero out the style_loader_tag for the bundled ones
6313
		 * - Be happy, drink scotch
6314
		 */
6315
6316
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6317
6318
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6319
6320
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6321
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6322
	}
6323
6324
	function concat_remove_style_loader_tag( $tag, $handle ) {
6325
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6326
			$tag = '';
6327
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6328
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6329
			}
6330
		}
6331
6332
		return $tag;
6333
	}
6334
6335
	/*
6336
	 * Check the heartbeat data
6337
	 *
6338
	 * Organizes the heartbeat data by severity.  For example, if the site
6339
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6340
	 *
6341
	 * Data will be added to "caution" array, if it either:
6342
	 *  - Out of date Jetpack version
6343
	 *  - Out of date WP version
6344
	 *  - Out of date PHP version
6345
	 *
6346
	 * $return array $filtered_data
6347
	 */
6348
	public static function jetpack_check_heartbeat_data() {
6349
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6350
6351
		$good    = array();
6352
		$caution = array();
6353
		$bad     = array();
6354
6355
		foreach ( $raw_data as $stat => $value ) {
6356
6357
			// Check jetpack version
6358
			if ( 'version' == $stat ) {
6359
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6360
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6361
					continue;
6362
				}
6363
			}
6364
6365
			// Check WP version
6366
			if ( 'wp-version' == $stat ) {
6367
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6368
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6369
					continue;
6370
				}
6371
			}
6372
6373
			// Check PHP version
6374
			if ( 'php-version' == $stat ) {
6375
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6376
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6377
					continue;
6378
				}
6379
			}
6380
6381
			// Check ID crisis
6382
			if ( 'identitycrisis' == $stat ) {
6383
				if ( 'yes' == $value ) {
6384
					$bad[ $stat ] = $value;
6385
					continue;
6386
				}
6387
			}
6388
6389
			// The rest are good :)
6390
			$good[ $stat ] = $value;
6391
		}
6392
6393
		$filtered_data = array(
6394
			'good'    => $good,
6395
			'caution' => $caution,
6396
			'bad'     => $bad
6397
		);
6398
6399
		return $filtered_data;
6400
	}
6401
6402
6403
	/*
6404
	 * This method is used to organize all options that can be reset
6405
	 * without disconnecting Jetpack.
6406
	 *
6407
	 * It is used in class.jetpack-cli.php to reset options
6408
	 *
6409
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6410
	 *
6411
	 * @return array of options to delete.
6412
	 */
6413
	public static function get_jetpack_options_for_reset() {
6414
		return Jetpack_Options::get_options_for_reset();
6415
	}
6416
6417
	/*
6418
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6419
	 * so we can bring them directly to their site in calypso.
6420
	 *
6421
	 * @param string | url
6422
	 * @return string | url without the guff
6423
	 */
6424
	public static function build_raw_urls( $url ) {
6425
		$strip_http = '/.*?:\/\//i';
6426
		$url = preg_replace( $strip_http, '', $url  );
6427
		$url = str_replace( '/', '::', $url );
6428
		return $url;
6429
	}
6430
6431
	/**
6432
	 * Stores and prints out domains to prefetch for page speed optimization.
6433
	 *
6434
	 * @param mixed $new_urls
6435
	 */
6436
	public static function dns_prefetch( $new_urls = null ) {
6437
		static $prefetch_urls = array();
6438
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6439
			echo "\r\n";
6440
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6441
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6442
			}
6443
		} elseif ( ! empty( $new_urls ) ) {
6444
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6445
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6446
			}
6447
			foreach ( (array) $new_urls as $this_new_url ) {
6448
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6449
			}
6450
			$prefetch_urls = array_unique( $prefetch_urls );
6451
		}
6452
	}
6453
6454
	public function wp_dashboard_setup() {
6455
		if ( self::is_active() ) {
6456
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6457
		}
6458
6459
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6460
			$jetpack_logo = new Jetpack_Logo();
6461
			$widget_title = sprintf(
6462
				wp_kses(
6463
					/* translators: Placeholder is a Jetpack logo. */
6464
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6465
					array( 'span' => array() )
6466
				),
6467
				$jetpack_logo->get_jp_emblem( true )
6468
			);
6469
6470
			wp_add_dashboard_widget(
6471
				'jetpack_summary_widget',
6472
				$widget_title,
6473
				array( __CLASS__, 'dashboard_widget' )
6474
			);
6475
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6476
6477
			// If we're inactive and not in development mode, sort our box to the top.
6478
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6479
				global $wp_meta_boxes;
6480
6481
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6482
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6483
6484
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6485
			}
6486
		}
6487
	}
6488
6489
	/**
6490
	 * @param mixed $result Value for the user's option
0 ignored issues
show
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...
6491
	 * @return mixed
6492
	 */
6493
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6494
		if ( ! is_array( $sorted ) ) {
6495
			return $sorted;
6496
		}
6497
6498
		foreach ( $sorted as $box_context => $ids ) {
6499
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6500
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6501
				continue;
6502
			}
6503
6504
			$ids_array = explode( ',', $ids );
6505
			$key = array_search( 'dashboard_stats', $ids_array );
6506
6507
			if ( false !== $key ) {
6508
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6509
				$ids_array[ $key ] = 'jetpack_summary_widget';
6510
				$sorted[ $box_context ] = implode( ',', $ids_array );
6511
				// We've found it, stop searching, and just return.
6512
				break;
6513
			}
6514
		}
6515
6516
		return $sorted;
6517
	}
6518
6519
	public static function dashboard_widget() {
6520
		/**
6521
		 * Fires when the dashboard is loaded.
6522
		 *
6523
		 * @since 3.4.0
6524
		 */
6525
		do_action( 'jetpack_dashboard_widget' );
6526
	}
6527
6528
	public static function dashboard_widget_footer() {
6529
		?>
6530
		<footer>
6531
6532
		<div class="protect">
6533
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6534
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6535
				<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>
6536
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6537
				<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' ); ?>">
6538
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6539
				</a>
6540
			<?php else : ?>
6541
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6542
			<?php endif; ?>
6543
		</div>
6544
6545
		<div class="akismet">
6546
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6547
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6548
				<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>
6549
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6550
				<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">
6551
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6552
				</a>
6553
			<?php else : ?>
6554
				<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>
6555
			<?php endif; ?>
6556
		</div>
6557
6558
		</footer>
6559
		<?php
6560
	}
6561
6562
	/*
6563
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6564
	 */
6565
	function jetpack_icon_user_connected( $columns ) {
6566
		$columns['user_jetpack'] = '';
6567
		return $columns;
6568
	}
6569
6570
	/*
6571
	 * Show Jetpack icon if the user is linked.
6572
	 */
6573
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6574
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6575
			$jetpack_logo = new Jetpack_Logo();
6576
			$emblem_html = sprintf(
6577
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6578
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6579
				$jetpack_logo->get_jp_emblem()
6580
			);
6581
			return $emblem_html;
6582
		}
6583
6584
		return $val;
6585
	}
6586
6587
	/*
6588
	 * Style the Jetpack user column
6589
	 */
6590
	function jetpack_user_col_style() {
6591
		global $current_screen;
6592
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6593
			<style>
6594
				.fixed .column-user_jetpack {
6595
					width: 21px;
6596
				}
6597
				.jp-emblem-user-admin svg {
6598
					width: 20px;
6599
					height: 20px;
6600
				}
6601
				.jp-emblem-user-admin path {
6602
					fill: #00BE28;
6603
				}
6604
			</style>
6605
		<?php }
6606
	}
6607
6608
	/**
6609
	 * Checks if Akismet is active and working.
6610
	 *
6611
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6612
	 * that implied usage of methods present since more recent version.
6613
	 * See https://github.com/Automattic/jetpack/pull/9585
6614
	 *
6615
	 * @since  5.1.0
6616
	 *
6617
	 * @return bool True = Akismet available. False = Aksimet not available.
6618
	 */
6619
	public static function is_akismet_active() {
6620
		static $status = null;
6621
6622
		if ( ! is_null( $status ) ) {
6623
			return $status;
6624
		}
6625
6626
		// Check if a modern version of Akismet is active.
6627
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6628
			$status = false;
6629
			return $status;
6630
		}
6631
6632
		// Make sure there is a key known to Akismet at all before verifying key.
6633
		$akismet_key = Akismet::get_api_key();
6634
		if ( ! $akismet_key ) {
6635
			$status = false;
6636
			return $status;
6637
		}
6638
6639
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6640
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6641
6642
		// Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
6643
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6644
		// We cache the result of the Akismet key verification for ten minutes.
6645
		if ( ! $akismet_key_state || $recheck ) {
6646
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6647
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6648
		}
6649
6650
		$status = 'valid' === $akismet_key_state;
6651
6652
		return $status;
6653
	}
6654
6655
	/**
6656
	 * Checks if one or more function names is in debug_backtrace
6657
	 *
6658
	 * @param $names Mixed string name of function or array of string names of functions
6659
	 *
6660
	 * @return bool
6661
	 */
6662
	public static function is_function_in_backtrace( $names ) {
6663
		$backtrace = debug_backtrace( false ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctionParameters.debug_backtrace_optionsFound
6664
		if ( ! is_array( $names ) ) {
6665
			$names = array( $names );
6666
		}
6667
		$names_as_keys = array_flip( $names );
6668
6669
		//Do check in constant O(1) time for PHP5.5+
6670
		if ( function_exists( 'array_column' ) ) {
6671
			$backtrace_functions = array_column( $backtrace, 'function' ); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.array_columnFound
6672
			$backtrace_functions_as_keys = array_flip( $backtrace_functions );
6673
			$intersection = array_intersect_key( $backtrace_functions_as_keys, $names_as_keys );
6674
			return ! empty ( $intersection );
6675
		}
6676
6677
		//Do check in linear O(n) time for < PHP5.5 ( using isset at least prevents O(n^2) )
6678
		foreach ( $backtrace as $call ) {
6679
			if ( isset( $names_as_keys[ $call['function'] ] ) ) {
6680
				return true;
6681
			}
6682
		}
6683
		return false;
6684
	}
6685
6686
	/**
6687
	 * Given a minified path, and a non-minified path, will return
6688
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6689
	 *
6690
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6691
	 * root Jetpack directory.
6692
	 *
6693
	 * @since 5.6.0
6694
	 *
6695
	 * @param string $min_path
6696
	 * @param string $non_min_path
6697
	 * @return string The URL to the file
6698
	 */
6699
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6700
		$path = ( Constants::is_defined( 'SCRIPT_DEBUG' ) && Constants::get_constant( 'SCRIPT_DEBUG' ) )
6701
			? $non_min_path
6702
			: $min_path;
6703
6704
		return plugins_url( $path, JETPACK__PLUGIN_FILE );
6705
	}
6706
6707
	/**
6708
	 * Checks for whether Jetpack Backup & Scan is enabled.
6709
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6710
	 * @return bool|int|mixed
6711
	 */
6712
	public static function is_rewind_enabled() {
6713
		if ( ! Jetpack::is_active() ) {
6714
			return false;
6715
		}
6716
6717
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6718
		if ( false === $rewind_enabled ) {
6719
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6720
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6721
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6722
				&& ! empty( $rewind_data['state'] )
6723
				&& 'active' === $rewind_data['state'] )
6724
				? 1
6725
				: 0;
6726
6727
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6728
		}
6729
		return $rewind_enabled;
6730
	}
6731
6732
	/**
6733
	 * Return Calypso environment value; used for developing Jetpack and pairing
6734
	 * it with different Calypso enrionments, such as localhost.
6735
	 *
6736
	 * @since 7.4.0
6737
	 *
6738
	 * @return string Calypso environment
6739
	 */
6740
	public static function get_calypso_env() {
6741
		if ( isset( $_GET['calypso_env'] ) ) {
6742
			return sanitize_key( $_GET['calypso_env'] );
6743
		}
6744
6745
		if ( getenv( 'CALYPSO_ENV' ) ) {
6746
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6747
		}
6748
6749
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6750
			return sanitize_key( CALYPSO_ENV );
6751
		}
6752
6753
		return '';
6754
	}
6755
6756
	/**
6757
	 * Checks whether or not TOS has been agreed upon.
6758
	 * Will return true if a user has clicked to register, or is already connected.
6759
	 */
6760
	public static function jetpack_tos_agreed() {
6761
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6762
	}
6763
6764
	/**
6765
	 * Handles activating default modules as well general cleanup for the new connection.
6766
	 *
6767
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6768
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6769
	 * @param boolean $send_state_messages          Whether to send state messages.
6770
	 * @return void
6771
	 */
6772
	public static function handle_post_authorization_actions(
6773
		$activate_sso = false,
6774
		$redirect_on_activation_error = false,
6775
		$send_state_messages = true
6776
	) {
6777
		$other_modules = $activate_sso
6778
			? array( 'sso' )
6779
			: array();
6780
6781
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6782
			Jetpack::delete_active_modules();
6783
6784
			Jetpack::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
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...
6785
		} else {
6786
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6787
		}
6788
6789
		// Since this is a fresh connection, be sure to clear out IDC options
6790
		Jetpack_IDC::clear_all_idc_options();
6791
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6792
6793
		// Start nonce cleaner
6794
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6795
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6796
6797
		if ( $send_state_messages ) {
6798
			Jetpack::state( 'message', 'authorized' );
6799
		}
6800
	}
6801
6802
	/**
6803
	 * Returns a boolean for whether backups UI should be displayed or not.
6804
	 *
6805
	 * @return bool Should backups UI be displayed?
6806
	 */
6807
	public static function show_backups_ui() {
6808
		/**
6809
		 * Whether UI for backups should be displayed.
6810
		 *
6811
		 * @since 6.5.0
6812
		 *
6813
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6814
		 */
6815
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6816
	}
6817
6818
	/*
6819
	 * Deprecated manage functions
6820
	 */
6821
	function prepare_manage_jetpack_notice() {
6822
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6823
	}
6824
	function manage_activate_screen() {
6825
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6826
	}
6827
	function admin_jetpack_manage_notice() {
6828
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6829
	}
6830
	function opt_out_jetpack_manage_url() {
6831
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6832
	}
6833
	function opt_in_jetpack_manage_url() {
6834
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6835
	}
6836
	function opt_in_jetpack_manage_notice() {
6837
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6838
	}
6839
	function can_display_jetpack_manage_notice() {
6840
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6841
	}
6842
6843
	/**
6844
	 * Clean leftoveruser meta.
6845
	 *
6846
	 * Delete Jetpack-related user meta when it is no longer needed.
6847
	 *
6848
	 * @since 7.3.0
6849
	 *
6850
	 * @param int $user_id User ID being updated.
6851
	 */
6852
	public static function user_meta_cleanup( $user_id ) {
6853
		$meta_keys = array(
6854
			// AtD removed from Jetpack 7.3
6855
			'AtD_options',
6856
			'AtD_check_when',
6857
			'AtD_guess_lang',
6858
			'AtD_ignored_phrases',
6859
		);
6860
6861
		foreach ( $meta_keys as $meta_key ) {
6862
			if ( get_user_meta( $user_id, $meta_key ) ) {
6863
				delete_user_meta( $user_id, $meta_key );
6864
			}
6865
		}
6866
	}
6867
6868
	function is_active_and_not_development_mode( $maybe ) {
6869
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6870
			return false;
6871
		}
6872
		return true;
6873
	}
6874
6875
	/**
6876
	 * @deprecated use Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature
6877
	 */
6878
	public static function verify_xml_rpc_signature() {
6879
		return self::connection()->verify_xml_rpc_signature();
6880
	}
6881
}
6882