Completed
Push — implement/connection-manager-d... ( 75970b )
by Marin
07:43
created

class.jetpack.php (60 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\Roles;
10
use Automattic\Jetpack\Sync\Functions;
11
use Automattic\Jetpack\Sync\Sender;
12
use Automattic\Jetpack\Sync\Users;
13
use Automattic\Jetpack\Tracking;
14
use Automattic\Jetpack\Assets;
15
16
/*
17
Options:
18
jetpack_options (array)
19
	An array of options.
20
	@see Jetpack_Options::get_option_names()
21
22
jetpack_register (string)
23
	Temporary verification secrets.
24
25
jetpack_activated (int)
26
	1: the plugin was activated normally
27
	2: the plugin was activated on this site because of a network-wide activation
28
	3: the plugin was auto-installed
29
	4: the plugin was manually disconnected (but is still installed)
30
31
jetpack_active_modules (array)
32
	Array of active module slugs.
33
34
jetpack_do_activate (bool)
35
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
36
*/
37
38
require_once( JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php' );
39
40
class Jetpack {
41
	public $xmlrpc_server = null;
42
43
	private $rest_authentication_status = null;
44
45
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
46
47
	private $tracking;
48
49
	/**
50
	 * @var array The handles of styles that are concatenated into jetpack.css.
51
	 *
52
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
53
	 */
54
	public $concatenated_style_handles = array(
55
		'jetpack-carousel',
56
		'grunion.css',
57
		'the-neverending-homepage',
58
		'jetpack_likes',
59
		'jetpack_related-posts',
60
		'sharedaddy',
61
		'jetpack-slideshow',
62
		'presentations',
63
		'quiz',
64
		'jetpack-subscriptions',
65
		'jetpack-responsive-videos-style',
66
		'jetpack-social-menu',
67
		'tiled-gallery',
68
		'jetpack_display_posts_widget',
69
		'gravatar-profile-widget',
70
		'goodreads-widget',
71
		'jetpack_social_media_icons_widget',
72
		'jetpack-top-posts-widget',
73
		'jetpack_image_widget',
74
		'jetpack-my-community-widget',
75
		'jetpack-authors-widget',
76
		'wordads',
77
		'eu-cookie-law-style',
78
		'flickr-widget-style',
79
		'jetpack-search-widget',
80
		'jetpack-simple-payments-widget-style',
81
		'jetpack-widget-social-icons-styles',
82
	);
83
84
	/**
85
	 * Contains all assets that have had their URL rewritten to minified versions.
86
	 *
87
	 * @var array
88
	 */
89
	static $min_assets = array();
90
91
	public $plugins_to_deactivate = array(
92
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
93
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
94
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
95
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
96
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
97
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
98
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
99
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
100
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
101
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
102
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
103
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
104
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
105
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
106
	);
107
108
	/**
109
	 * Map of roles we care about, and their corresponding minimum capabilities.
110
	 *
111
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
112
	 *
113
	 * @access public
114
	 * @static
115
	 *
116
	 * @var array
117
	 */
118
	public static $capability_translations = array(
119
		'administrator' => 'manage_options',
120
		'editor'        => 'edit_others_posts',
121
		'author'        => 'publish_posts',
122
		'contributor'   => 'edit_posts',
123
		'subscriber'    => 'read',
124
	);
125
126
	/**
127
	 * Map of modules that have conflicts with plugins and should not be auto-activated
128
	 * if the plugins are active.  Used by filter_default_modules
129
	 *
130
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
131
	 * change `module-slug` and add this to your plugin:
132
	 *
133
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
134
	 * function my_jetpack_get_default_modules( $modules ) {
135
	 *     return array_diff( $modules, array( 'module-slug' ) );
136
	 * }
137
	 *
138
	 * @var array
139
	 */
140
	private $conflicting_plugins = array(
141
		'comments'          => array(
142
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
143
			'Disqus'                               => 'disqus-comment-system/disqus.php',
144
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
145
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
146
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
147
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
148
		),
149
		'comment-likes' => array(
150
			'Epoch'                                => 'epoch/plugincore.php',
151
		),
152
		'contact-form'      => array(
153
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
154
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
155
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
156
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
157
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
158
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
159
		),
160
		'minileven'         => array(
161
			'WPtouch'                              => 'wptouch/wptouch.php',
162
		),
163
		'latex'             => array(
164
			'LaTeX for WordPress'                  => 'latex/latex.php',
165
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
166
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
167
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
168
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
169
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
170
		),
171
		'protect'           => array(
172
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
173
			'Captcha'                              => 'captcha/captcha.php',
174
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
175
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
176
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
177
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
178
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
179
			'Security-protection'                  => 'security-protection/security-protection.php',
180
			'Login Security'                       => 'login-security/login-security.php',
181
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
182
			'Wordfence Security'                   => 'wordfence/wordfence.php',
183
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
184
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
185
		),
186
		'random-redirect'   => array(
187
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
188
		),
189
		'related-posts'     => array(
190
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
191
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
192
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
193
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
194
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
195
			'outbrain'                             => 'outbrain/outbrain.php',
196
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
197
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
198
		),
199
		'sharedaddy'        => array(
200
			'AddThis'                              => 'addthis/addthis_social_widget.php',
201
			'Add To Any'                           => 'add-to-any/add-to-any.php',
202
			'ShareThis'                            => 'share-this/sharethis.php',
203
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
204
		),
205
		'seo-tools' => array(
206
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
207
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
208
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
209
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
210
			'The SEO Framework'                    => 'autodescription/autodescription.php',
211
		),
212
		'verification-tools' => array(
213
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
214
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
215
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
216
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
217
			'The SEO Framework'                    => 'autodescription/autodescription.php',
218
		),
219
		'widget-visibility' => array(
220
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
221
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
222
		),
223
		'sitemaps' => array(
224
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
225
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
226
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
227
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
228
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
229
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
230
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
231
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
232
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
233
			'The SEO Framework'                    => 'autodescription/autodescription.php',
234
			'Sitemap'                              => 'sitemap/sitemap.php',
235
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
236
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
237
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
238
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
239
		),
240
		'lazy-images' => array(
241
			'Lazy Load'              => 'lazy-load/lazy-load.php',
242
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
243
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
244
		),
245
	);
246
247
	/**
248
	 * Plugins for which we turn off our Facebook OG Tags implementation.
249
	 *
250
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
251
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
252
	 *
253
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
254
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
255
	 */
256
	private $open_graph_conflicting_plugins = array(
257
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
258
		                                                         // 2 Click Social Media Buttons
259
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
260
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
261
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
262
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
263
		                                                         // Open Graph Meta Tags by Heateor
264
		'facebook/facebook.php',                                 // Facebook (official plugin)
265
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
266
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
267
		                                                         // Facebook Featured Image & OG Meta Tags
268
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
269
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
270
		                                                         // Facebook Open Graph Meta Tags for WordPress
271
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
272
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
273
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
274
		                                                         // Fedmich's Facebook Open Graph Meta
275
		'network-publisher/networkpub.php',                      // Network Publisher
276
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
277
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
278
		                                                         // NextScripts SNAP
279
		'og-tags/og-tags.php',                                   // OG Tags
280
		'opengraph/opengraph.php',                               // Open Graph
281
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
282
		                                                         // Open Graph Protocol Framework
283
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
284
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
285
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
286
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
287
		'sharepress/sharepress.php',                             // SharePress
288
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
289
		'social-discussions/social-discussions.php',             // Social Discussions
290
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
291
		'socialize/socialize.php',                               // Socialize
292
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
293
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
294
		                                                         // Tweet, Like, Google +1 and Share
295
		'wordbooker/wordbooker.php',                             // Wordbooker
296
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
297
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
298
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
299
		                                                         // WP Facebook Like Send & Open Graph Meta
300
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
301
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
302
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
303
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
304
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
305
	);
306
307
	/**
308
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
309
	 */
310
	private $twitter_cards_conflicting_plugins = array(
311
	//	'twitter/twitter.php',                       // The official one handles this on its own.
312
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
313
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
314
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
315
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
316
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
317
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
318
		'twitter-cards/twitter-cards.php',           // Twitter Cards
319
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
320
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
321
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
322
	);
323
324
	/**
325
	 * Message to display in admin_notice
326
	 * @var string
327
	 */
328
	public $message = '';
329
330
	/**
331
	 * Error to display in admin_notice
332
	 * @var string
333
	 */
334
	public $error = '';
335
336
	/**
337
	 * Modules that need more privacy description.
338
	 * @var string
339
	 */
340
	public $privacy_checks = '';
341
342
	/**
343
	 * Stats to record once the page loads
344
	 *
345
	 * @var array
346
	 */
347
	public $stats = array();
348
349
	/**
350
	 * Jetpack_Sync object
351
	 */
352
	public $sync;
353
354
	/**
355
	 * Verified data for JSON authorization request
356
	 */
357
	public $json_api_authorization_request = array();
358
359
	/**
360
	 * @var \Automattic\Jetpack\Connection\Manager
361
	 */
362
	protected $connection_manager;
363
364
	/**
365
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
366
	 */
367
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
368
369
	/**
370
	 * Holds the singleton instance of this class
371
	 * @since 2.3.3
372
	 * @var Jetpack
373
	 */
374
	static $instance = false;
375
376
	/**
377
	 * Singleton
378
	 * @static
379
	 */
380
	public static function init() {
381
		if ( ! self::$instance ) {
382
			self::$instance = new Jetpack;
383
384
			self::$instance->plugin_upgrade();
385
		}
386
387
		return self::$instance;
388
	}
389
390
	/**
391
	 * Must never be called statically
392
	 */
393
	function plugin_upgrade() {
394
		if ( Jetpack::is_active() ) {
395
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
396
			if ( JETPACK__VERSION != $version ) {
397
				// Prevent multiple upgrades at once - only a single process should trigger
398
				// an upgrade to avoid stampedes
399
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
400
					return;
401
				}
402
403
				// Set a short lock to prevent multiple instances of the upgrade
404
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
405
406
				// check which active modules actually exist and remove others from active_modules list
407
				$unfiltered_modules = Jetpack::get_active_modules();
408
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
409
				if ( array_diff( $unfiltered_modules, $modules ) ) {
410
					Jetpack::update_active_modules( $modules );
411
				}
412
413
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
414
415
				// Upgrade to 4.3.0
416
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
417
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
418
				}
419
420
				// Make sure Markdown for posts gets turned back on
421
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
422
					update_option( 'wpcom_publish_posts_with_markdown', true );
423
				}
424
425
				if ( did_action( 'wp_loaded' ) ) {
426
					self::upgrade_on_load();
427
				} else {
428
					add_action(
429
						'wp_loaded',
430
						array( __CLASS__, 'upgrade_on_load' )
431
					);
432
				}
433
			}
434
		}
435
	}
436
437
	/**
438
	 * Runs upgrade routines that need to have modules loaded.
439
	 */
440
	static function upgrade_on_load() {
441
442
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
443
		// This can happen in case Jetpack has been just upgraded and is
444
		// being initialized late during the page load. In this case we wait
445
		// until the next proper admin page load with Jetpack active.
446
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
447
			delete_transient( self::$plugin_upgrade_lock_key );
448
449
			return;
450
		}
451
452
		Jetpack::maybe_set_version_option();
453
454
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
455
			Jetpack_Widget_Conditions::migrate_post_type_rules();
456
		}
457
458
		if (
459
			class_exists( 'Jetpack_Sitemap_Manager' )
460
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
461
		) {
462
			do_action( 'jetpack_sitemaps_purge_data' );
463
		}
464
465
		// Delete old stats cache
466
		delete_option( 'jetpack_restapi_stats_cache' );
467
468
		delete_transient( self::$plugin_upgrade_lock_key );
469
	}
470
471
	/**
472
	 * Saves all the currently active modules to options.
473
	 * Also fires Action hooks for each newly activated and deactivated module.
474
	 *
475
	 * @param $modules Array Array of active modules to be saved in options.
476
	 *
477
	 * @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...
478
	 */
479
	static function update_active_modules( $modules ) {
480
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
481
		$active_modules       = Jetpack::get_active_modules();
482
		$new_active_modules   = array_diff( $modules, $current_modules );
483
		$new_inactive_modules = array_diff( $active_modules, $modules );
484
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
485
		$reindexed_modules    = array_values( $new_current_modules );
486
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
487
488
		foreach ( $new_active_modules as $module ) {
489
			/**
490
			 * Fires when a specific module is activated.
491
			 *
492
			 * @since 1.9.0
493
			 *
494
			 * @param string $module Module slug.
495
			 * @param boolean $success whether the module was activated. @since 4.2
496
			 */
497
			do_action( 'jetpack_activate_module', $module, $success );
498
			/**
499
			 * Fires when a module is activated.
500
			 * The dynamic part of the filter, $module, is the module slug.
501
			 *
502
			 * @since 1.9.0
503
			 *
504
			 * @param string $module Module slug.
505
			 */
506
			do_action( "jetpack_activate_module_$module", $module );
507
		}
508
509
		foreach ( $new_inactive_modules as $module ) {
510
			/**
511
			 * Fired after a module has been deactivated.
512
			 *
513
			 * @since 4.2.0
514
			 *
515
			 * @param string $module Module slug.
516
			 * @param boolean $success whether the module was deactivated.
517
			 */
518
			do_action( 'jetpack_deactivate_module', $module, $success );
519
			/**
520
			 * Fires when a module is deactivated.
521
			 * The dynamic part of the filter, $module, is the module slug.
522
			 *
523
			 * @since 1.9.0
524
			 *
525
			 * @param string $module Module slug.
526
			 */
527
			do_action( "jetpack_deactivate_module_$module", $module );
528
		}
529
530
		return $success;
531
	}
532
533
	static function delete_active_modules() {
534
		self::update_active_modules( array() );
535
	}
536
537
	/**
538
	 * Constructor.  Initializes WordPress hooks
539
	 */
540
	private function __construct() {
541
		/*
542
		 * Check for and alert any deprecated hooks
543
		 */
544
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
545
546
		/*
547
		 * Enable enhanced handling of previewing sites in Calypso
548
		 */
549
		if ( Jetpack::is_active() ) {
550
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
551
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
552
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
553
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
554
		}
555
556
		if ( self::jetpack_tos_agreed() ) {
557
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
558
			add_action( 'init', array( $tracking, 'init' ) );
559
		}
560
561
562
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
563
			return function() {
564
				return wp_generate_password( 32, false );
565
			};
566
		} );
567
568
		$this->connection_manager = new Connection_Manager();
569
		$this->connection_manager->init();
570
571
		/*
572
		 * Load things that should only be in Network Admin.
573
		 *
574
		 * For now blow away everything else until a more full
575
		 * understanding of what is needed at the network level is
576
		 * available
577
		 */
578
		if ( is_multisite() ) {
579
			$network = Jetpack_Network::init();
580
			$network->set_connection( $this->connection_manager );
581
		}
582
583
		add_filter(
584
			'jetpack_signature_check_token',
585
			array( __CLASS__, 'verify_onboarding_token' ),
586
			10,
587
			3
588
		);
589
590
		/**
591
		 * Prepare Gutenberg Editor functionality
592
		 */
593
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
594
		Jetpack_Gutenberg::init();
595
		Jetpack_Gutenberg::load_independent_blocks();
596
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
597
598
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
599
600
		// Unlink user before deleting the user from WP.com.
601
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
602
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
603
604
		if ( Jetpack::is_active() ) {
605
			Jetpack_Heartbeat::init();
606
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
607
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
608
				Jetpack_Search_Performance_Logger::init();
609
			}
610
		}
611
612
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
613
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
614
615
		add_action( 'admin_init', array( $this, 'admin_init' ) );
616
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
617
618
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
619
620
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
621
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
622
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
623
624
		// returns HTTPS support status
625
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
626
627
		// JITM AJAX callback function
628
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
629
630
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
631
632
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
633
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
634
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
635
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
636
637
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
638
639
		/**
640
		 * These actions run checks to load additional files.
641
		 * They check for external files or plugins, so they need to run as late as possible.
642
		 */
643
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
644
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
645
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
646
647
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
648
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
649
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
650
651
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
652
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
653
654
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
655
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
656
657
		// A filter to control all just in time messages
658
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
659
660
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
661
662
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
663
		// We should make sure to only do this for front end links.
664
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
665
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
666
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
667
668
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
669
			//so they point moderation links on emails to Calypso
670
			jetpack_require_lib( 'functions.wp-notify' );
671
		}
672
673
		// Hide edit post link if mobile app.
674
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
675
			add_filter( 'edit_post_link', '__return_empty_string' );
676
		}
677
678
		// Update the Jetpack plan from API on heartbeats
679
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
680
681
		/**
682
		 * This is the hack to concatenate all css files into one.
683
		 * For description and reasoning see the implode_frontend_css method
684
		 *
685
		 * Super late priority so we catch all the registered styles
686
		 */
687
		if( !is_admin() ) {
688
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
689
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
690
		}
691
692
693
		/**
694
		 * These are sync actions that we need to keep track of for jitms
695
		 */
696
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
697
698
		// Actually push the stats on shutdown.
699
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
700
			add_action( 'shutdown', array( $this, 'push_stats' ) );
701
		}
702
	}
703
704
	/**
705
	 * Sets up the XMLRPC request handlers.
706
	 *
707
	 * @todo Deprecate this method in favor of Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers().
708
	 *
709
	 * @param Array                 $request_params Incoming request parameters.
710
	 * @param Boolean               $is_active      Whether the connection is currently active.
711
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
712
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Should the type for parameter $xmlrpc_server not be null|Jetpack_XMLRPC_Server?

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...
713
	 */
714
	public function setup_xmlrpc_handlers(
715
		$request_params,
716
		$is_active,
717
		$is_signed,
718
		Jetpack_XMLRPC_Server $xmlrpc_server = null
719
	) {
720
		return $this->connection_manager->setup_xmlrpc_handlers(
721
			$request_params,
722
			$is_active,
723
			$is_signed,
724
			$xmlrpc_server
725
		);
726
	}
727
728
	/**
729
	 * Initialize REST API registration connector.
730
	 *
731
	 * @deprecated since 7.7.0
732
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
733
	 */
734
	public function initialize_rest_api_registration_connector() {
735
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
736
		$this->connection_manager->initialize_rest_api_registration_connector();
737
	}
738
739
	/**
740
	 * This is ported over from the manage module, which has been deprecated and baked in here.
741
	 *
742
	 * @param $domains
743
	 */
744
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
745
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
746
	}
747
748
	/**
749
	 * Return $domains, with 'wordpress.com' appended.
750
	 * This is ported over from the manage module, which has been deprecated and baked in here.
751
	 *
752
	 * @param $domains
753
	 * @return array
754
	 */
755
	function allow_wpcom_domain( $domains ) {
756
		if ( empty( $domains ) ) {
757
			$domains = array();
758
		}
759
		$domains[] = 'wordpress.com';
760
		return array_unique( $domains );
761
	}
762
763
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
764
		$post = get_post( $post_id );
765
766
		if ( empty( $post ) ) {
767
			return $default_url;
768
		}
769
770
		$post_type = $post->post_type;
771
772
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
773
		// https://en.support.wordpress.com/custom-post-types/
774
		$allowed_post_types = array(
775
			'post' => 'post',
776
			'page' => 'page',
777
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
778
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
779
		);
780
781
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
782
			return $default_url;
783
		}
784
785
		$path_prefix = $allowed_post_types[ $post_type ];
786
787
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
788
789
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
790
	}
791
792
	function point_edit_comment_links_to_calypso( $url ) {
793
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
794
		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...
795
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
796
			Jetpack::build_raw_urls( get_home_url() ),
797
			$query_args['amp;c']
798
		) );
799
	}
800
801
	function jetpack_track_last_sync_callback( $params ) {
802
		/**
803
		 * Filter to turn off jitm caching
804
		 *
805
		 * @since 5.4.0
806
		 *
807
		 * @param bool false Whether to cache just in time messages
808
		 */
809
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
810
			return $params;
811
		}
812
813
		if ( is_array( $params ) && isset( $params[0] ) ) {
814
			$option = $params[0];
815
			if ( 'active_plugins' === $option ) {
816
				// use the cache if we can, but not terribly important if it gets evicted
817
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
818
			}
819
		}
820
821
		return $params;
822
	}
823
824
	function jetpack_connection_banner_callback() {
825
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
826
827
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
828
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
829
			wp_send_json_success();
830
		}
831
832
		wp_die();
833
	}
834
835
	/**
836
	 * Removes all XML-RPC methods that are not `jetpack.*`.
837
	 * Only used in our alternate XML-RPC endpoint, where we want to
838
	 * ensure that Core and other plugins' methods are not exposed.
839
	 *
840
	 * @deprecated since 7.7.0
841
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
842
	 *
843
	 * @param array $methods A list of registered WordPress XMLRPC methods.
844
	 * @return array Filtered $methods
845
	 */
846
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
847
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
848
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
849
	}
850
851
	/**
852
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
853
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
854
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
855
	 * which is accessible via a different URI. Most of the below is copied directly
856
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
857
	 *
858
	 * @deprecated since 7.7.0
859
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
860
	 */
861
	public function alternate_xmlrpc() {
862
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
863
		$this->connection_manager->alternate_xmlrpc();
864
	}
865
866
	/**
867
	 * The callback for the JITM ajax requests.
868
	 */
869
	function jetpack_jitm_ajax_callback() {
870
		// Check for nonce
871
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
872
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
873
		}
874
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
875
			$module_slug = $_REQUEST['jitmModule'];
876
			Jetpack::log( 'activate', $module_slug );
877
			Jetpack::activate_module( $module_slug, false, false );
878
			Jetpack::state( 'message', 'no_message' );
879
880
			//A Jetpack module is being activated through a JITM, track it
881
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
882
			$this->do_stats( 'server_side' );
883
884
			wp_send_json_success();
885
		}
886
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
887
			// get the hide_jitm options array
888
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
889
			$module_slug = $_REQUEST['jitmModule'];
890
891
			if( ! $jetpack_hide_jitm ) {
892
				$jetpack_hide_jitm = array(
893
					$module_slug => 'hide'
894
				);
895
			} else {
896
				$jetpack_hide_jitm[$module_slug] = 'hide';
897
			}
898
899
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
900
901
			//jitm is being dismissed forever, track it
902
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
903
			$this->do_stats( 'server_side' );
904
905
			wp_send_json_success();
906
		}
907 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
908
			$module_slug = $_REQUEST['jitmModule'];
909
910
			// User went to WordPress.com, track this
911
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
912
			$this->do_stats( 'server_side' );
913
914
			wp_send_json_success();
915
		}
916 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
917
			$track = $_REQUEST['jitmModule'];
918
919
			// User is viewing JITM, track it.
920
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
921
			$this->do_stats( 'server_side' );
922
923
			wp_send_json_success();
924
		}
925
	}
926
927
	/**
928
	 * If there are any stats that need to be pushed, but haven't been, push them now.
929
	 */
930
	function push_stats() {
931
		if ( ! empty( $this->stats ) ) {
932
			$this->do_stats( 'server_side' );
933
		}
934
	}
935
936
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
937
		switch( $cap ) {
938
			case 'jetpack_connect' :
939
			case 'jetpack_reconnect' :
940
				if ( Jetpack::is_development_mode() ) {
941
					$caps = array( 'do_not_allow' );
942
					break;
943
				}
944
				/**
945
				 * Pass through. If it's not development mode, these should match disconnect.
946
				 * Let users disconnect if it's development mode, just in case things glitch.
947
				 */
948
			case 'jetpack_disconnect' :
949
				/**
950
				 * In multisite, can individual site admins manage their own connection?
951
				 *
952
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
953
				 */
954
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
955
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
956
						/**
957
						 * We need to update the option name -- it's terribly unclear which
958
						 * direction the override goes.
959
						 *
960
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
961
						 */
962
						$caps = array( 'do_not_allow' );
963
						break;
964
					}
965
				}
966
967
				$caps = array( 'manage_options' );
968
				break;
969
			case 'jetpack_manage_modules' :
970
			case 'jetpack_activate_modules' :
971
			case 'jetpack_deactivate_modules' :
972
				$caps = array( 'manage_options' );
973
				break;
974
			case 'jetpack_configure_modules' :
975
				$caps = array( 'manage_options' );
976
				break;
977
			case 'jetpack_manage_autoupdates' :
978
				$caps = array(
979
					'manage_options',
980
					'update_plugins',
981
				);
982
				break;
983
			case 'jetpack_network_admin_page':
984
			case 'jetpack_network_settings_page':
985
				$caps = array( 'manage_network_plugins' );
986
				break;
987
			case 'jetpack_network_sites_page':
988
				$caps = array( 'manage_sites' );
989
				break;
990
			case 'jetpack_admin_page' :
991
				if ( Jetpack::is_development_mode() ) {
992
					$caps = array( 'manage_options' );
993
					break;
994
				} else {
995
					$caps = array( 'read' );
996
				}
997
				break;
998
			case 'jetpack_connect_user' :
999
				if ( Jetpack::is_development_mode() ) {
1000
					$caps = array( 'do_not_allow' );
1001
					break;
1002
				}
1003
				$caps = array( 'read' );
1004
				break;
1005
		}
1006
		return $caps;
1007
	}
1008
1009
	/**
1010
	 * Require a Jetpack authentication.
1011
	 *
1012
	 * @deprecated since 7.7.0
1013
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1014
	 */
1015
	public function require_jetpack_authentication() {
1016
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1017
		$this->connection_manager->require_jetpack_authentication();
1018
	}
1019
1020
	/**
1021
	 * Load language files
1022
	 * @action plugins_loaded
1023
	 */
1024
	public static function plugin_textdomain() {
1025
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1026
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1027
	}
1028
1029
	/**
1030
	 * Register assets for use in various modules and the Jetpack admin page.
1031
	 *
1032
	 * @uses wp_script_is, wp_register_script, plugins_url
1033
	 * @action wp_loaded
1034
	 * @return null
1035
	 */
1036
	public function register_assets() {
1037
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1038
			wp_register_script(
1039
				'spin',
1040
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1041
				false,
1042
				'1.3'
1043
			);
1044
		}
1045
1046 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1047
			wp_register_script(
1048
				'jquery.spin',
1049
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1050
				array( 'jquery', 'spin' ),
1051
				'1.3'
1052
			);
1053
		}
1054
1055 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1056
			wp_register_script(
1057
				'jetpack-gallery-settings',
1058
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1059
				array( 'media-views' ),
1060
				'20121225'
1061
			);
1062
		}
1063
1064 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1065
			wp_register_script(
1066
				'jetpack-twitter-timeline',
1067
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1068
				array( 'jquery' ),
1069
				'4.0.0',
1070
				true
1071
			);
1072
		}
1073
1074
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1075
			wp_register_script(
1076
				'jetpack-facebook-embed',
1077
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1078
				array( 'jquery' ),
1079
				null,
1080
				true
1081
			);
1082
1083
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1084
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1085
			if ( ! is_numeric( $fb_app_id ) ) {
1086
				$fb_app_id = '';
1087
			}
1088
			wp_localize_script(
1089
				'jetpack-facebook-embed',
1090
				'jpfbembed',
1091
				array(
1092
					'appid' => $fb_app_id,
1093
					'locale' => $this->get_locale(),
1094
				)
1095
			);
1096
		}
1097
1098
		/**
1099
		 * As jetpack_register_genericons is by default fired off a hook,
1100
		 * the hook may have already fired by this point.
1101
		 * So, let's just trigger it manually.
1102
		 */
1103
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1104
		jetpack_register_genericons();
1105
1106
		/**
1107
		 * Register the social logos
1108
		 */
1109
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1110
		jetpack_register_social_logos();
1111
1112 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1113
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1114
	}
1115
1116
	/**
1117
	 * Guess locale from language code.
1118
	 *
1119
	 * @param string $lang Language code.
1120
	 * @return string|bool
1121
	 */
1122 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1123
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1124
			return 'en_US';
1125
		}
1126
1127
		if ( ! class_exists( 'GP_Locales' ) ) {
1128
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1129
				return false;
1130
			}
1131
1132
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1133
		}
1134
1135
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1136
			// WP.com: get_locale() returns 'it'
1137
			$locale = GP_Locales::by_slug( $lang );
1138
		} else {
1139
			// Jetpack: get_locale() returns 'it_IT';
1140
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1141
		}
1142
1143
		if ( ! $locale ) {
1144
			return false;
1145
		}
1146
1147
		if ( empty( $locale->facebook_locale ) ) {
1148
			if ( empty( $locale->wp_locale ) ) {
1149
				return false;
1150
			} else {
1151
				// Facebook SDK is smart enough to fall back to en_US if a
1152
				// locale isn't supported. Since supported Facebook locales
1153
				// can fall out of sync, we'll attempt to use the known
1154
				// wp_locale value and rely on said fallback.
1155
				return $locale->wp_locale;
1156
			}
1157
		}
1158
1159
		return $locale->facebook_locale;
1160
	}
1161
1162
	/**
1163
	 * Get the locale.
1164
	 *
1165
	 * @return string|bool
1166
	 */
1167
	function get_locale() {
1168
		$locale = $this->guess_locale_from_lang( get_locale() );
1169
1170
		if ( ! $locale ) {
1171
			$locale = 'en_US';
1172
		}
1173
1174
		return $locale;
1175
	}
1176
1177
	/**
1178
	 * Device Pixels support
1179
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1180
	 */
1181
	function devicepx() {
1182
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1183
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1184
		}
1185
	}
1186
1187
	/**
1188
	 * Return the network_site_url so that .com knows what network this site is a part of.
1189
	 * @param  bool $option
1190
	 * @return string
1191
	 */
1192
	public function jetpack_main_network_site_option( $option ) {
1193
		return network_site_url();
1194
	}
1195
	/**
1196
	 * Network Name.
1197
	 */
1198
	static function network_name( $option = null ) {
1199
		global $current_site;
1200
		return $current_site->site_name;
1201
	}
1202
	/**
1203
	 * Does the network allow new user and site registrations.
1204
	 * @return string
1205
	 */
1206
	static function network_allow_new_registrations( $option = null ) {
1207
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1208
	}
1209
	/**
1210
	 * Does the network allow admins to add new users.
1211
	 * @return boolian
1212
	 */
1213
	static function network_add_new_users( $option = null ) {
1214
		return (bool) get_site_option( 'add_new_users' );
1215
	}
1216
	/**
1217
	 * File upload psace left per site in MB.
1218
	 *  -1 means NO LIMIT.
1219
	 * @return number
1220
	 */
1221
	static function network_site_upload_space( $option = null ) {
1222
		// value in MB
1223
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1224
	}
1225
1226
	/**
1227
	 * Network allowed file types.
1228
	 * @return string
1229
	 */
1230
	static function network_upload_file_types( $option = null ) {
1231
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1232
	}
1233
1234
	/**
1235
	 * Maximum file upload size set by the network.
1236
	 * @return number
1237
	 */
1238
	static function network_max_upload_file_size( $option = null ) {
1239
		// value in KB
1240
		return get_site_option( 'fileupload_maxk', 300 );
1241
	}
1242
1243
	/**
1244
	 * Lets us know if a site allows admins to manage the network.
1245
	 * @return array
1246
	 */
1247
	static function network_enable_administration_menus( $option = null ) {
1248
		return get_site_option( 'menu_items' );
1249
	}
1250
1251
	/**
1252
	 * If a user has been promoted to or demoted from admin, we need to clear the
1253
	 * jetpack_other_linked_admins transient.
1254
	 *
1255
	 * @since 4.3.2
1256
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1257
	 *
1258
	 * @param int    $user_id   The user ID whose role changed.
1259
	 * @param string $role      The new role.
1260
	 * @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...
1261
	 */
1262
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1263
		if ( 'administrator' == $role
1264
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1265
			|| is_null( $old_roles )
1266
		) {
1267
			delete_transient( 'jetpack_other_linked_admins' );
1268
		}
1269
	}
1270
1271
	/**
1272
	 * Checks to see if there are any other users available to become primary
1273
	 * Users must both:
1274
	 * - Be linked to wpcom
1275
	 * - Be an admin
1276
	 *
1277
	 * @return mixed False if no other users are linked, Int if there are.
1278
	 */
1279
	static function get_other_linked_admins() {
1280
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1281
1282
		if ( false === $other_linked_users ) {
1283
			$admins = get_users( array( 'role' => 'administrator' ) );
1284
			if ( count( $admins ) > 1 ) {
1285
				$available = array();
1286
				foreach ( $admins as $admin ) {
1287
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1288
						$available[] = $admin->ID;
1289
					}
1290
				}
1291
1292
				$count_connected_admins = count( $available );
1293
				if ( count( $available ) > 1 ) {
1294
					$other_linked_users = $count_connected_admins;
1295
				} else {
1296
					$other_linked_users = 0;
1297
				}
1298
			} else {
1299
				$other_linked_users = 0;
1300
			}
1301
1302
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1303
		}
1304
1305
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1306
	}
1307
1308
	/**
1309
	 * Return whether we are dealing with a multi network setup or not.
1310
	 * The reason we are type casting this is because we want to avoid the situation where
1311
	 * the result is false since when is_main_network_option return false it cases
1312
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1313
	 * database which could be set to anything as opposed to what this function returns.
1314
	 * @param  bool  $option
1315
	 *
1316
	 * @return boolean
1317
	 */
1318
	public function is_main_network_option( $option ) {
1319
		// return '1' or ''
1320
		return (string) (bool) Jetpack::is_multi_network();
1321
	}
1322
1323
	/**
1324
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1325
	 *
1326
	 * @param  string  $option
1327
	 * @return boolean
1328
	 */
1329
	public function is_multisite( $option ) {
1330
		return (string) (bool) is_multisite();
1331
	}
1332
1333
	/**
1334
	 * Implemented since there is no core is multi network function
1335
	 * Right now there is no way to tell if we which network is the dominant network on the system
1336
	 *
1337
	 * @since  3.3
1338
	 * @return boolean
1339
	 */
1340 View Code Duplication
	public static function is_multi_network() {
1341
		global  $wpdb;
1342
1343
		// if we don't have a multi site setup no need to do any more
1344
		if ( ! is_multisite() ) {
1345
			return false;
1346
		}
1347
1348
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1349
		if ( $num_sites > 1 ) {
1350
			return true;
1351
		} else {
1352
			return false;
1353
		}
1354
	}
1355
1356
	/**
1357
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1358
	 * @return null
1359
	 */
1360
	function update_jetpack_main_network_site_option() {
1361
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1362
	}
1363
	/**
1364
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1365
	 *
1366
	 */
1367
	function update_jetpack_network_settings() {
1368
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1369
		// Only sync this info for the main network site.
1370
	}
1371
1372
	/**
1373
	 * Get back if the current site is single user site.
1374
	 *
1375
	 * @return bool
1376
	 */
1377 View Code Duplication
	public static function is_single_user_site() {
1378
		global $wpdb;
1379
1380
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1381
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1382
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1383
		}
1384
		return 1 === (int) $some_users;
1385
	}
1386
1387
	/**
1388
	 * Returns true if the site has file write access false otherwise.
1389
	 * @return string ( '1' | '0' )
1390
	 **/
1391
	public static function file_system_write_access() {
1392
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1393
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1394
		}
1395
1396
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1397
1398
		$filesystem_method = get_filesystem_method();
1399
		if ( $filesystem_method === 'direct' ) {
1400
			return 1;
1401
		}
1402
1403
		ob_start();
1404
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1405
		ob_end_clean();
1406
		if ( $filesystem_credentials_are_stored ) {
1407
			return 1;
1408
		}
1409
		return 0;
1410
	}
1411
1412
	/**
1413
	 * Finds out if a site is using a version control system.
1414
	 * @return string ( '1' | '0' )
1415
	 **/
1416
	public static function is_version_controlled() {
1417
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1418
		return (string) (int) Functions::is_version_controlled();
1419
	}
1420
1421
	/**
1422
	 * Determines whether the current theme supports featured images or not.
1423
	 * @return string ( '1' | '0' )
1424
	 */
1425
	public static function featured_images_enabled() {
1426
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1427
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1428
	}
1429
1430
	/**
1431
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1432
	 *
1433
	 * @deprecated 4.7 use get_avatar_url instead.
1434
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1435
	 * @param int $size Size of the avatar image
1436
	 * @param string $default URL to a default image to use if no avatar is available
1437
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1438
	 *
1439
	 * @return array
1440
	 */
1441
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1442
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1443
		return get_avatar_url( $id_or_email, array(
1444
			'size' => $size,
1445
			'default' => $default,
1446
			'force_default' => $force_display,
1447
		) );
1448
	}
1449
1450
	/**
1451
	 * jetpack_updates is saved in the following schema:
1452
	 *
1453
	 * array (
1454
	 *      'plugins'                       => (int) Number of plugin updates available.
1455
	 *      'themes'                        => (int) Number of theme updates available.
1456
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1457
	 *      'translations'                  => (int) Number of translation updates available.
1458
	 *      'total'                         => (int) Total of all available updates.
1459
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1460
	 * )
1461
	 * @return array
1462
	 */
1463
	public static function get_updates() {
1464
		$update_data = wp_get_update_data();
1465
1466
		// Stores the individual update counts as well as the total count.
1467
		if ( isset( $update_data['counts'] ) ) {
1468
			$updates = $update_data['counts'];
1469
		}
1470
1471
		// If we need to update WordPress core, let's find the latest version number.
1472 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1473
			$cur = get_preferred_from_update_core();
1474
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1475
				$updates['wp_update_version'] = $cur->current;
1476
			}
1477
		}
1478
		return isset( $updates ) ? $updates : array();
1479
	}
1480
1481
	public static function get_update_details() {
1482
		$update_details = array(
1483
			'update_core' => get_site_transient( 'update_core' ),
1484
			'update_plugins' => get_site_transient( 'update_plugins' ),
1485
			'update_themes' => get_site_transient( 'update_themes' ),
1486
		);
1487
		return $update_details;
1488
	}
1489
1490
	public static function refresh_update_data() {
1491
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1492
1493
	}
1494
1495
	public static function refresh_theme_data() {
1496
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1497
	}
1498
1499
	/**
1500
	 * Is Jetpack active?
1501
	 */
1502
	public static function is_active() {
1503
		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...
1504
	}
1505
1506
	/**
1507
	 * Make an API call to WordPress.com for plan status
1508
	 *
1509
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1510
	 *
1511
	 * @return bool True if plan is updated, false if no update
1512
	 */
1513
	public static function refresh_active_plan_from_wpcom() {
1514
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1515
		return Jetpack_Plan::refresh_from_wpcom();
1516
	}
1517
1518
	/**
1519
	 * Get the plan that this Jetpack site is currently using
1520
	 *
1521
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1522
	 * @return array Active Jetpack plan details.
1523
	 */
1524
	public static function get_active_plan() {
1525
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1526
		return Jetpack_Plan::get();
1527
	}
1528
1529
	/**
1530
	 * Determine whether the active plan supports a particular feature
1531
	 *
1532
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1533
	 * @return bool True if plan supports feature, false if not.
1534
	 */
1535
	public static function active_plan_supports( $feature ) {
1536
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1537
		return Jetpack_Plan::supports( $feature );
1538
	}
1539
1540
	/**
1541
	 * Is Jetpack in development (offline) mode?
1542
	 */
1543 View Code Duplication
	public static function is_development_mode() {
1544
		$development_mode = false;
1545
1546
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1547
			$development_mode = JETPACK_DEV_DEBUG;
1548
		} elseif ( $site_url = site_url() ) {
1549
			$development_mode = false === strpos( $site_url, '.' );
1550
		}
1551
1552
		/**
1553
		 * Filters Jetpack's development mode.
1554
		 *
1555
		 * @see https://jetpack.com/support/development-mode/
1556
		 *
1557
		 * @since 2.2.1
1558
		 *
1559
		 * @param bool $development_mode Is Jetpack's development mode active.
1560
		 */
1561
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1562
		return $development_mode;
1563
	}
1564
1565
	/**
1566
	 * Whether the site is currently onboarding or not.
1567
	 * A site is considered as being onboarded if it currently has an onboarding token.
1568
	 *
1569
	 * @since 5.8
1570
	 *
1571
	 * @access public
1572
	 * @static
1573
	 *
1574
	 * @return bool True if the site is currently onboarding, false otherwise
1575
	 */
1576
	public static function is_onboarding() {
1577
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1578
	}
1579
1580
	/**
1581
	 * Determines reason for Jetpack development mode.
1582
	 */
1583
	public static function development_mode_trigger_text() {
1584
		if ( ! Jetpack::is_development_mode() ) {
1585
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1586
		}
1587
1588
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1589
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1590
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1591
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1592
		} else {
1593
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1594
		}
1595
1596
		return $notice;
1597
1598
	}
1599
	/**
1600
	* Get Jetpack development mode notice text and notice class.
1601
	*
1602
	* Mirrors the checks made in Jetpack::is_development_mode
1603
	*
1604
	*/
1605
	public static function show_development_mode_notice() {
1606 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1607
			$notice = sprintf(
1608
			/* translators: %s is a URL */
1609
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1610
				'https://jetpack.com/support/development-mode/'
1611
			);
1612
1613
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1614
1615
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1616
		}
1617
1618
		// Throw up a notice if using a development version and as for feedback.
1619
		if ( Jetpack::is_development_version() ) {
1620
			/* translators: %s is a URL */
1621
			$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/' );
1622
1623
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1624
		}
1625
		// Throw up a notice if using staging mode
1626
		if ( Jetpack::is_staging_site() ) {
1627
			/* translators: %s is a URL */
1628
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1629
1630
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1631
		}
1632
	}
1633
1634
	/**
1635
	 * Whether Jetpack's version maps to a public release, or a development version.
1636
	 */
1637
	public static function is_development_version() {
1638
		/**
1639
		 * Allows filtering whether this is a development version of Jetpack.
1640
		 *
1641
		 * This filter is especially useful for tests.
1642
		 *
1643
		 * @since 4.3.0
1644
		 *
1645
		 * @param bool $development_version Is this a develoment version of Jetpack?
1646
		 */
1647
		return (bool) apply_filters(
1648
			'jetpack_development_version',
1649
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1650
		);
1651
	}
1652
1653
	/**
1654
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1655
	 */
1656
	public static function is_user_connected( $user_id = false ) {
1657
		return self::connection()->is_user_connected( $user_id );
1658
	}
1659
1660
	/**
1661
	 * Get the wpcom user data of the current|specified connected user.
1662
	 */
1663 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1664
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1665
		if ( ! $user_id ) {
1666
			$user_id = get_current_user_id();
1667
		}
1668
1669
		$transient_key = "jetpack_connected_user_data_$user_id";
1670
1671
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1672
			return $cached_user_data;
1673
		}
1674
1675
		Jetpack::load_xml_rpc_client();
1676
		$xml = new Jetpack_IXR_Client( array(
1677
			'user_id' => $user_id,
1678
		) );
1679
		$xml->query( 'wpcom.getUser' );
1680
		if ( ! $xml->isError() ) {
1681
			$user_data = $xml->getResponse();
1682
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1683
			return $user_data;
1684
		}
1685
1686
		return false;
1687
	}
1688
1689
	/**
1690
	 * Get the wpcom email of the current|specified connected user.
1691
	 */
1692 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1693
		if ( ! $user_id ) {
1694
			$user_id = get_current_user_id();
1695
		}
1696
		Jetpack::load_xml_rpc_client();
1697
		$xml = new Jetpack_IXR_Client( array(
1698
			'user_id' => $user_id,
1699
		) );
1700
		$xml->query( 'wpcom.getUserEmail' );
1701
		if ( ! $xml->isError() ) {
1702
			return $xml->getResponse();
1703
		}
1704
		return false;
1705
	}
1706
1707
	/**
1708
	 * Get the wpcom email of the master user.
1709
	 */
1710
	public static function get_master_user_email() {
1711
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1712
		if ( $master_user_id ) {
1713
			return self::get_connected_user_email( $master_user_id );
1714
		}
1715
		return '';
1716
	}
1717
1718
	/**
1719
	 * Whether the current user is the connection owner.
1720
	 *
1721
	 * @deprecated since 7.7
1722
	 *
1723
	 * @return bool Whether the current user is the connection owner.
1724
	 */
1725
	public function current_user_is_connection_owner() {
1726
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1727
		return self::connection()->is_connection_owner();
1728
	}
1729
1730
	/**
1731
	 * Gets current user IP address.
1732
	 *
1733
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1734
	 *
1735
	 * @return string                  Current user IP address.
1736
	 */
1737
	public static function current_user_ip( $check_all_headers = false ) {
1738
		if ( $check_all_headers ) {
1739
			foreach ( array(
1740
				'HTTP_CF_CONNECTING_IP',
1741
				'HTTP_CLIENT_IP',
1742
				'HTTP_X_FORWARDED_FOR',
1743
				'HTTP_X_FORWARDED',
1744
				'HTTP_X_CLUSTER_CLIENT_IP',
1745
				'HTTP_FORWARDED_FOR',
1746
				'HTTP_FORWARDED',
1747
				'HTTP_VIA',
1748
			) as $key ) {
1749
				if ( ! empty( $_SERVER[ $key ] ) ) {
1750
					return $_SERVER[ $key ];
1751
				}
1752
			}
1753
		}
1754
1755
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1756
	}
1757
1758
	/**
1759
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1760
	 */
1761
	function extra_oembed_providers() {
1762
		// Cloudup: https://dev.cloudup.com/#oembed
1763
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1764
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1765
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1766
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1767
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1768
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1769
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1770
	}
1771
1772
	/**
1773
	 * Synchronize connected user role changes
1774
	 */
1775
	function user_role_change( $user_id ) {
1776
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1777
		Users::user_role_change( $user_id );
1778
	}
1779
1780
	/**
1781
	 * Loads the currently active modules.
1782
	 */
1783
	public static function load_modules() {
1784
		if (
1785
			! self::is_active()
1786
			&& ! self::is_development_mode()
1787
			&& ! self::is_onboarding()
1788
			&& (
1789
				! is_multisite()
1790
				|| ! get_site_option( 'jetpack_protect_active' )
1791
			)
1792
		) {
1793
			return;
1794
		}
1795
1796
		$version = Jetpack_Options::get_option( 'version' );
1797 View Code Duplication
		if ( ! $version ) {
1798
			$version = $old_version = JETPACK__VERSION . ':' . time();
1799
			/** This action is documented in class.jetpack.php */
1800
			do_action( 'updating_jetpack_version', $version, false );
1801
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1802
		}
1803
		list( $version ) = explode( ':', $version );
1804
1805
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1806
1807
		$modules_data = array();
1808
1809
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1810
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1811
			$updated_modules = array();
1812
			foreach ( $modules as $module ) {
1813
				$modules_data[ $module ] = Jetpack::get_module( $module );
1814
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1815
					continue;
1816
				}
1817
1818
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1819
					continue;
1820
				}
1821
1822
				$updated_modules[] = $module;
1823
			}
1824
1825
			$modules = array_diff( $modules, $updated_modules );
1826
		}
1827
1828
		$is_development_mode = Jetpack::is_development_mode();
1829
1830
		foreach ( $modules as $index => $module ) {
1831
			// If we're in dev mode, disable modules requiring a connection
1832
			if ( $is_development_mode ) {
1833
				// Prime the pump if we need to
1834
				if ( empty( $modules_data[ $module ] ) ) {
1835
					$modules_data[ $module ] = Jetpack::get_module( $module );
1836
				}
1837
				// If the module requires a connection, but we're in local mode, don't include it.
1838
				if ( $modules_data[ $module ]['requires_connection'] ) {
1839
					continue;
1840
				}
1841
			}
1842
1843
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1844
				continue;
1845
			}
1846
1847
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1848
				unset( $modules[ $index ] );
1849
				self::update_active_modules( array_values( $modules ) );
1850
				continue;
1851
			}
1852
1853
			/**
1854
			 * Fires when a specific module is loaded.
1855
			 * The dynamic part of the hook, $module, is the module slug.
1856
			 *
1857
			 * @since 1.1.0
1858
			 */
1859
			do_action( 'jetpack_module_loaded_' . $module );
1860
		}
1861
1862
		/**
1863
		 * Fires when all the modules are loaded.
1864
		 *
1865
		 * @since 1.1.0
1866
		 */
1867
		do_action( 'jetpack_modules_loaded' );
1868
1869
		// 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.
1870
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1871
	}
1872
1873
	/**
1874
	 * Check if Jetpack's REST API compat file should be included
1875
	 * @action plugins_loaded
1876
	 * @return null
1877
	 */
1878
	public function check_rest_api_compat() {
1879
		/**
1880
		 * Filters the list of REST API compat files to be included.
1881
		 *
1882
		 * @since 2.2.5
1883
		 *
1884
		 * @param array $args Array of REST API compat files to include.
1885
		 */
1886
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1887
1888
		if ( function_exists( 'bbpress' ) )
1889
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1890
1891
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1892
			require_once $_jetpack_rest_api_compat_include;
1893
	}
1894
1895
	/**
1896
	 * Gets all plugins currently active in values, regardless of whether they're
1897
	 * traditionally activated or network activated.
1898
	 *
1899
	 * @todo Store the result in core's object cache maybe?
1900
	 */
1901
	public static function get_active_plugins() {
1902
		$active_plugins = (array) get_option( 'active_plugins', array() );
1903
1904
		if ( is_multisite() ) {
1905
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1906
			// whereas active_plugins stores them in the values.
1907
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1908
			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...
1909
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1910
			}
1911
		}
1912
1913
		sort( $active_plugins );
1914
1915
		return array_unique( $active_plugins );
1916
	}
1917
1918
	/**
1919
	 * Gets and parses additional plugin data to send with the heartbeat data
1920
	 *
1921
	 * @since 3.8.1
1922
	 *
1923
	 * @return array Array of plugin data
1924
	 */
1925
	public static function get_parsed_plugin_data() {
1926
		if ( ! function_exists( 'get_plugins' ) ) {
1927
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1928
		}
1929
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1930
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1931
		$active_plugins = Jetpack::get_active_plugins();
1932
1933
		$plugins = array();
1934
		foreach ( $all_plugins as $path => $plugin_data ) {
1935
			$plugins[ $path ] = array(
1936
					'is_active' => in_array( $path, $active_plugins ),
1937
					'file'      => $path,
1938
					'name'      => $plugin_data['Name'],
1939
					'version'   => $plugin_data['Version'],
1940
					'author'    => $plugin_data['Author'],
1941
			);
1942
		}
1943
1944
		return $plugins;
1945
	}
1946
1947
	/**
1948
	 * Gets and parses theme data to send with the heartbeat data
1949
	 *
1950
	 * @since 3.8.1
1951
	 *
1952
	 * @return array Array of theme data
1953
	 */
1954
	public static function get_parsed_theme_data() {
1955
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1956
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1957
1958
		$themes = array();
1959
		foreach ( $all_themes as $slug => $theme_data ) {
1960
			$theme_headers = array();
1961
			foreach ( $header_keys as $header_key ) {
1962
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
1963
			}
1964
1965
			$themes[ $slug ] = array(
1966
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
1967
					'slug' => $slug,
1968
					'theme_root' => $theme_data->get_theme_root_uri(),
1969
					'parent' => $theme_data->parent(),
1970
					'headers' => $theme_headers
1971
			);
1972
		}
1973
1974
		return $themes;
1975
	}
1976
1977
	/**
1978
	 * Checks whether a specific plugin is active.
1979
	 *
1980
	 * We don't want to store these in a static variable, in case
1981
	 * there are switch_to_blog() calls involved.
1982
	 */
1983
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
1984
		return in_array( $plugin, self::get_active_plugins() );
1985
	}
1986
1987
	/**
1988
	 * Check if Jetpack's Open Graph tags should be used.
1989
	 * If certain plugins are active, Jetpack's og tags are suppressed.
1990
	 *
1991
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
1992
	 * @action plugins_loaded
1993
	 * @return null
1994
	 */
1995
	public function check_open_graph() {
1996
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
1997
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
1998
		}
1999
2000
		$active_plugins = self::get_active_plugins();
2001
2002
		if ( ! empty( $active_plugins ) ) {
2003
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2004
				if ( in_array( $plugin, $active_plugins ) ) {
2005
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2006
					break;
2007
				}
2008
			}
2009
		}
2010
2011
		/**
2012
		 * Allow the addition of Open Graph Meta Tags to all pages.
2013
		 *
2014
		 * @since 2.0.3
2015
		 *
2016
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2017
		 */
2018
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2019
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2020
		}
2021
	}
2022
2023
	/**
2024
	 * Check if Jetpack's Twitter tags should be used.
2025
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2026
	 *
2027
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2028
	 * @action plugins_loaded
2029
	 * @return null
2030
	 */
2031
	public function check_twitter_tags() {
2032
2033
		$active_plugins = self::get_active_plugins();
2034
2035
		if ( ! empty( $active_plugins ) ) {
2036
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2037
				if ( in_array( $plugin, $active_plugins ) ) {
2038
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2039
					break;
2040
				}
2041
			}
2042
		}
2043
2044
		/**
2045
		 * Allow Twitter Card Meta tags to be disabled.
2046
		 *
2047
		 * @since 2.6.0
2048
		 *
2049
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2050
		 */
2051
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2052
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2053
		}
2054
	}
2055
2056
	/**
2057
	 * Allows plugins to submit security reports.
2058
 	 *
2059
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2060
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2061
	 * @param array   $args         See definitions above
2062
	 */
2063
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2064
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2065
	}
2066
2067
/* Jetpack Options API */
2068
2069
	public static function get_option_names( $type = 'compact' ) {
2070
		return Jetpack_Options::get_option_names( $type );
2071
	}
2072
2073
	/**
2074
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2075
 	 *
2076
	 * @param string $name    Option name
2077
	 * @param mixed  $default (optional)
2078
	 */
2079
	public static function get_option( $name, $default = false ) {
2080
		return Jetpack_Options::get_option( $name, $default );
2081
	}
2082
2083
	/**
2084
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2085
 	 *
2086
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2087
	 * @param string $name  Option name
2088
	 * @param mixed  $value Option value
2089
	 */
2090
	public static function update_option( $name, $value ) {
2091
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2092
		return Jetpack_Options::update_option( $name, $value );
2093
	}
2094
2095
	/**
2096
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2097
 	 *
2098
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2099
	 * @param array $array array( option name => option value, ... )
2100
	 */
2101
	public static function update_options( $array ) {
2102
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2103
		return Jetpack_Options::update_options( $array );
2104
	}
2105
2106
	/**
2107
	 * Deletes the given option.  May be passed multiple option names as an array.
2108
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2109
	 *
2110
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2111
	 * @param string|array $names
2112
	 */
2113
	public static function delete_option( $names ) {
2114
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2115
		return Jetpack_Options::delete_option( $names );
2116
	}
2117
2118
	/**
2119
	 * Enters a user token into the user_tokens option
2120
	 *
2121
	 * @param int $user_id
2122
	 * @param string $token
2123
	 * return bool
2124
	 */
2125
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2126
		// not designed for concurrent updates
2127
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2128
		if ( ! is_array( $user_tokens ) )
2129
			$user_tokens = array();
2130
		$user_tokens[$user_id] = $token;
2131
		if ( $is_master_user ) {
2132
			$master_user = $user_id;
2133
			$options     = compact( 'user_tokens', 'master_user' );
2134
		} else {
2135
			$options = compact( 'user_tokens' );
2136
		}
2137
		return Jetpack_Options::update_options( $options );
2138
	}
2139
2140
	/**
2141
	 * Returns an array of all PHP files in the specified absolute path.
2142
	 * Equivalent to glob( "$absolute_path/*.php" ).
2143
	 *
2144
	 * @param string $absolute_path The absolute path of the directory to search.
2145
	 * @return array Array of absolute paths to the PHP files.
2146
	 */
2147
	public static function glob_php( $absolute_path ) {
2148
		if ( function_exists( 'glob' ) ) {
2149
			return glob( "$absolute_path/*.php" );
2150
		}
2151
2152
		$absolute_path = untrailingslashit( $absolute_path );
2153
		$files = array();
2154
		if ( ! $dir = @opendir( $absolute_path ) ) {
2155
			return $files;
2156
		}
2157
2158
		while ( false !== $file = readdir( $dir ) ) {
2159
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2160
				continue;
2161
			}
2162
2163
			$file = "$absolute_path/$file";
2164
2165
			if ( ! is_file( $file ) ) {
2166
				continue;
2167
			}
2168
2169
			$files[] = $file;
2170
		}
2171
2172
		closedir( $dir );
2173
2174
		return $files;
2175
	}
2176
2177
	public static function activate_new_modules( $redirect = false ) {
2178
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2179
			return;
2180
		}
2181
2182
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2183 View Code Duplication
		if ( ! $jetpack_old_version ) {
2184
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2185
			/** This action is documented in class.jetpack.php */
2186
			do_action( 'updating_jetpack_version', $version, false );
2187
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2188
		}
2189
2190
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2191
2192
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2193
			return;
2194
		}
2195
2196
		$active_modules     = Jetpack::get_active_modules();
2197
		$reactivate_modules = array();
2198
		foreach ( $active_modules as $active_module ) {
2199
			$module = Jetpack::get_module( $active_module );
2200
			if ( ! isset( $module['changed'] ) ) {
2201
				continue;
2202
			}
2203
2204
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2205
				continue;
2206
			}
2207
2208
			$reactivate_modules[] = $active_module;
2209
			Jetpack::deactivate_module( $active_module );
2210
		}
2211
2212
		$new_version = JETPACK__VERSION . ':' . time();
2213
		/** This action is documented in class.jetpack.php */
2214
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2215
		Jetpack_Options::update_options(
2216
			array(
2217
				'version'     => $new_version,
2218
				'old_version' => $jetpack_old_version,
2219
			)
2220
		);
2221
2222
		Jetpack::state( 'message', 'modules_activated' );
2223
		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...
2224
2225
		if ( $redirect ) {
2226
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2227
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2228
				$page = $_GET['page'];
2229
			}
2230
2231
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2232
			exit;
2233
		}
2234
	}
2235
2236
	/**
2237
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2238
	 * Make sure to tuck away module "library" files in a sub-directory.
2239
	 */
2240
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2241
		static $modules = null;
2242
2243
		if ( ! isset( $modules ) ) {
2244
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2245
			// Use the cache if we're on the front-end and it's available...
2246
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2247
				$modules = $available_modules_option[ JETPACK__VERSION ];
2248
			} else {
2249
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2250
2251
				$modules = array();
2252
2253
				foreach ( $files as $file ) {
2254
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2255
						continue;
2256
					}
2257
2258
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2259
				}
2260
2261
				Jetpack_Options::update_option( 'available_modules', array(
2262
					JETPACK__VERSION => $modules,
2263
				) );
2264
			}
2265
		}
2266
2267
		/**
2268
		 * Filters the array of modules available to be activated.
2269
		 *
2270
		 * @since 2.4.0
2271
		 *
2272
		 * @param array $modules Array of available modules.
2273
		 * @param string $min_version Minimum version number required to use modules.
2274
		 * @param string $max_version Maximum version number required to use modules.
2275
		 */
2276
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2277
2278
		if ( ! $min_version && ! $max_version ) {
2279
			return array_keys( $mods );
2280
		}
2281
2282
		$r = array();
2283
		foreach ( $mods as $slug => $introduced ) {
2284
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2285
				continue;
2286
			}
2287
2288
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2289
				continue;
2290
			}
2291
2292
			$r[] = $slug;
2293
		}
2294
2295
		return $r;
2296
	}
2297
2298
	/**
2299
	 * Default modules loaded on activation.
2300
	 */
2301
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2302
		$return = array();
2303
2304
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2305
			$module_data = Jetpack::get_module( $module );
2306
2307
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2308
				case 'yes' :
2309
					$return[] = $module;
2310
					break;
2311
				case 'public' :
2312
					if ( Jetpack_Options::get_option( 'public' ) ) {
2313
						$return[] = $module;
2314
					}
2315
					break;
2316
				case 'no' :
2317
				default :
2318
					break;
2319
			}
2320
		}
2321
		/**
2322
		 * Filters the array of default modules.
2323
		 *
2324
		 * @since 2.5.0
2325
		 *
2326
		 * @param array $return Array of default modules.
2327
		 * @param string $min_version Minimum version number required to use modules.
2328
		 * @param string $max_version Maximum version number required to use modules.
2329
		 */
2330
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2331
	}
2332
2333
	/**
2334
	 * Checks activated modules during auto-activation to determine
2335
	 * if any of those modules are being deprecated.  If so, close
2336
	 * them out, and add any replacement modules.
2337
	 *
2338
	 * Runs at priority 99 by default.
2339
	 *
2340
	 * This is run late, so that it can still activate a module if
2341
	 * the new module is a replacement for another that the user
2342
	 * currently has active, even if something at the normal priority
2343
	 * would kibosh everything.
2344
	 *
2345
	 * @since 2.6
2346
	 * @uses jetpack_get_default_modules filter
2347
	 * @param array $modules
2348
	 * @return array
2349
	 */
2350
	function handle_deprecated_modules( $modules ) {
2351
		$deprecated_modules = array(
2352
			'debug'            => null,  // Closed out and moved to the debugger library.
2353
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2354
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2355
		);
2356
2357
		// Don't activate SSO if they never completed activating WPCC.
2358
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2359
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2360
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2361
				$deprecated_modules['wpcc'] = null;
2362
			}
2363
		}
2364
2365
		foreach ( $deprecated_modules as $module => $replacement ) {
2366
			if ( Jetpack::is_module_active( $module ) ) {
2367
				self::deactivate_module( $module );
2368
				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...
2369
					$modules[] = $replacement;
2370
				}
2371
			}
2372
		}
2373
2374
		return array_unique( $modules );
2375
	}
2376
2377
	/**
2378
	 * Checks activated plugins during auto-activation to determine
2379
	 * if any of those plugins are in the list with a corresponding module
2380
	 * that is not compatible with the plugin. The module will not be allowed
2381
	 * to auto-activate.
2382
	 *
2383
	 * @since 2.6
2384
	 * @uses jetpack_get_default_modules filter
2385
	 * @param array $modules
2386
	 * @return array
2387
	 */
2388
	function filter_default_modules( $modules ) {
2389
2390
		$active_plugins = self::get_active_plugins();
2391
2392
		if ( ! empty( $active_plugins ) ) {
2393
2394
			// For each module we'd like to auto-activate...
2395
			foreach ( $modules as $key => $module ) {
2396
				// If there are potential conflicts for it...
2397
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2398
					// For each potential conflict...
2399
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2400
						// If that conflicting plugin is active...
2401
						if ( in_array( $plugin, $active_plugins ) ) {
2402
							// Remove that item from being auto-activated.
2403
							unset( $modules[ $key ] );
2404
						}
2405
					}
2406
				}
2407
			}
2408
		}
2409
2410
		return $modules;
2411
	}
2412
2413
	/**
2414
	 * Extract a module's slug from its full path.
2415
	 */
2416
	public static function get_module_slug( $file ) {
2417
		return str_replace( '.php', '', basename( $file ) );
2418
	}
2419
2420
	/**
2421
	 * Generate a module's path from its slug.
2422
	 */
2423
	public static function get_module_path( $slug ) {
2424
		/**
2425
		 * Filters the path of a modules.
2426
		 *
2427
		 * @since 7.4.0
2428
		 *
2429
		 * @param array $return The absolute path to a module's root php file
2430
		 * @param string $slug The module slug
2431
		 */
2432
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2433
	}
2434
2435
	/**
2436
	 * Load module data from module file. Headers differ from WordPress
2437
	 * plugin headers to avoid them being identified as standalone
2438
	 * plugins on the WordPress plugins page.
2439
	 */
2440
	public static function get_module( $module ) {
2441
		$headers = array(
2442
			'name'                      => 'Module Name',
2443
			'description'               => 'Module Description',
2444
			'sort'                      => 'Sort Order',
2445
			'recommendation_order'      => 'Recommendation Order',
2446
			'introduced'                => 'First Introduced',
2447
			'changed'                   => 'Major Changes In',
2448
			'deactivate'                => 'Deactivate',
2449
			'free'                      => 'Free',
2450
			'requires_connection'       => 'Requires Connection',
2451
			'auto_activate'             => 'Auto Activate',
2452
			'module_tags'               => 'Module Tags',
2453
			'feature'                   => 'Feature',
2454
			'additional_search_queries' => 'Additional Search Queries',
2455
			'plan_classes'              => 'Plans',
2456
		);
2457
2458
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2459
2460
		$mod = Jetpack::get_file_data( $file, $headers );
2461
		if ( empty( $mod['name'] ) ) {
2462
			return false;
2463
		}
2464
2465
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2466
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2467
		$mod['deactivate']              = empty( $mod['deactivate'] );
2468
		$mod['free']                    = empty( $mod['free'] );
2469
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2470
2471
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2472
			$mod['auto_activate'] = 'No';
2473
		} else {
2474
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2475
		}
2476
2477
		if ( $mod['module_tags'] ) {
2478
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2479
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2480
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2481
		} else {
2482
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2483
		}
2484
2485 View Code Duplication
		if ( $mod['plan_classes'] ) {
2486
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2487
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2488
		} else {
2489
			$mod['plan_classes'] = array( 'free' );
2490
		}
2491
2492 View Code Duplication
		if ( $mod['feature'] ) {
2493
			$mod['feature'] = explode( ',', $mod['feature'] );
2494
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2495
		} else {
2496
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2497
		}
2498
2499
		/**
2500
		 * Filters the feature array on a module.
2501
		 *
2502
		 * This filter allows you to control where each module is filtered: Recommended,
2503
		 * and the default "Other" listing.
2504
		 *
2505
		 * @since 3.5.0
2506
		 *
2507
		 * @param array   $mod['feature'] The areas to feature this module:
2508
		 *     'Recommended' shows on the main Jetpack admin screen.
2509
		 *     'Other' should be the default if no other value is in the array.
2510
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2511
		 * @param array   $mod All the currently assembled module data.
2512
		 */
2513
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2514
2515
		/**
2516
		 * Filter the returned data about a module.
2517
		 *
2518
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2519
		 * so please be careful.
2520
		 *
2521
		 * @since 3.6.0
2522
		 *
2523
		 * @param array   $mod    The details of the requested module.
2524
		 * @param string  $module The slug of the module, e.g. sharedaddy
2525
		 * @param string  $file   The path to the module source file.
2526
		 */
2527
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2528
	}
2529
2530
	/**
2531
	 * Like core's get_file_data implementation, but caches the result.
2532
	 */
2533
	public static function get_file_data( $file, $headers ) {
2534
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2535
		$file_name = basename( $file );
2536
2537
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2538
2539
		$file_data_option = get_transient( $cache_key );
2540
2541
		if ( false === $file_data_option ) {
2542
			$file_data_option = array();
2543
		}
2544
2545
		$key           = md5( $file_name . serialize( $headers ) );
2546
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2547
2548
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2549
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2550
			return $file_data_option[ $key ];
2551
		}
2552
2553
		$data = get_file_data( $file, $headers );
2554
2555
		$file_data_option[ $key ] = $data;
2556
2557
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2558
2559
		return $data;
2560
	}
2561
2562
2563
	/**
2564
	 * Return translated module tag.
2565
	 *
2566
	 * @param string $tag Tag as it appears in each module heading.
2567
	 *
2568
	 * @return mixed
2569
	 */
2570
	public static function translate_module_tag( $tag ) {
2571
		return jetpack_get_module_i18n_tag( $tag );
2572
	}
2573
2574
	/**
2575
	 * Get i18n strings as a JSON-encoded string
2576
	 *
2577
	 * @return string The locale as JSON
2578
	 */
2579
	public static function get_i18n_data_json() {
2580
2581
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2582
		// JSON files with the file they should be included for. This is an md5
2583
		// of '_inc/build/admin.js'.
2584
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2585
2586
		$i18n_json =
2587
				   JETPACK__PLUGIN_DIR
2588
				   . 'languages/json/jetpack-'
2589
				   . get_user_locale()
2590
				   . '-'
2591
				   . $path_md5
2592
				   . '.json';
2593
2594
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2595
			$locale_data = @file_get_contents( $i18n_json );
2596
			if ( $locale_data ) {
2597
				return $locale_data;
2598
			}
2599
		}
2600
2601
		// Return valid empty Jed locale
2602
		return '{ "locale_data": { "messages": { "": {} } } }';
2603
	}
2604
2605
	/**
2606
	 * Add locale data setup to wp-i18n
2607
	 *
2608
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2609
	 *
2610
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2611
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2612
	 *
2613
	 * This method provides a safe way to request the setup multiple times but add the script at
2614
	 * most once.
2615
	 *
2616
	 * @since 6.7.0
2617
	 *
2618
	 * @return void
2619
	 */
2620
	public static function setup_wp_i18n_locale_data() {
2621
		static $script_added = false;
2622
		if ( ! $script_added ) {
2623
			$script_added = true;
2624
			wp_add_inline_script(
2625
				'wp-i18n',
2626
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2627
			);
2628
		}
2629
	}
2630
2631
	/**
2632
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2633
	 *
2634
	 * @since 3.9.2
2635
	 *
2636
	 * @param array $modules
2637
	 *
2638
	 * @return string|void
2639
	 */
2640
	public static function get_translated_modules( $modules ) {
2641
		foreach ( $modules as $index => $module ) {
2642
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2643
			if ( isset( $module['name'] ) ) {
2644
				$modules[ $index ]['name'] = $i18n_module['name'];
2645
			}
2646
			if ( isset( $module['description'] ) ) {
2647
				$modules[ $index ]['description'] = $i18n_module['description'];
2648
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2649
			}
2650
		}
2651
		return $modules;
2652
	}
2653
2654
	/**
2655
	 * Get a list of activated modules as an array of module slugs.
2656
	 */
2657
	public static function get_active_modules() {
2658
		$active = Jetpack_Options::get_option( 'active_modules' );
2659
2660
		if ( ! is_array( $active ) ) {
2661
			$active = array();
2662
		}
2663
2664
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2665
			$active[] = 'vaultpress';
2666
		} else {
2667
			$active = array_diff( $active, array( 'vaultpress' ) );
2668
		}
2669
2670
		//If protect is active on the main site of a multisite, it should be active on all sites.
2671
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2672
			$active[] = 'protect';
2673
		}
2674
2675
		/**
2676
		 * Allow filtering of the active modules.
2677
		 *
2678
		 * Gives theme and plugin developers the power to alter the modules that
2679
		 * are activated on the fly.
2680
		 *
2681
		 * @since 5.8.0
2682
		 *
2683
		 * @param array $active Array of active module slugs.
2684
		 */
2685
		$active = apply_filters( 'jetpack_active_modules', $active );
2686
2687
		return array_unique( $active );
2688
	}
2689
2690
	/**
2691
	 * Check whether or not a Jetpack module is active.
2692
	 *
2693
	 * @param string $module The slug of a Jetpack module.
2694
	 * @return bool
2695
	 *
2696
	 * @static
2697
	 */
2698
	public static function is_module_active( $module ) {
2699
		return in_array( $module, self::get_active_modules() );
2700
	}
2701
2702
	public static function is_module( $module ) {
2703
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2704
	}
2705
2706
	/**
2707
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2708
	 *
2709
	 * @param bool $catch True to start catching, False to stop.
2710
	 *
2711
	 * @static
2712
	 */
2713
	public static function catch_errors( $catch ) {
2714
		static $display_errors, $error_reporting;
2715
2716
		if ( $catch ) {
2717
			$display_errors  = @ini_set( 'display_errors', 1 );
2718
			$error_reporting = @error_reporting( E_ALL );
2719
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2720
		} else {
2721
			@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...
2722
			@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...
2723
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2724
		}
2725
	}
2726
2727
	/**
2728
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2729
	 */
2730
	public static function catch_errors_on_shutdown() {
2731
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2732
	}
2733
2734
	/**
2735
	 * Rewrite any string to make paths easier to read.
2736
	 *
2737
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2738
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2739
	 *
2740
	 * @param $string
2741
	 * @return mixed
2742
	 */
2743
	public static function alias_directories( $string ) {
2744
		// ABSPATH has a trailing slash.
2745
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2746
		// WP_CONTENT_DIR does not have a trailing slash.
2747
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2748
2749
		return $string;
2750
	}
2751
2752
	public static function activate_default_modules(
2753
		$min_version = false,
2754
		$max_version = false,
2755
		$other_modules = array(),
2756
		$redirect = true,
2757
		$send_state_messages = true
2758
	) {
2759
		$jetpack = Jetpack::init();
2760
2761
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2762
		$modules = array_merge( $other_modules, $modules );
2763
2764
		// Look for standalone plugins and disable if active.
2765
2766
		$to_deactivate = array();
2767
		foreach ( $modules as $module ) {
2768
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2769
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2770
			}
2771
		}
2772
2773
		$deactivated = array();
2774
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2775
			list( $probable_file, $probable_title ) = $deactivate_me;
2776
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2777
				$deactivated[] = $module;
2778
			}
2779
		}
2780
2781
		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...
2782
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2783
2784
			$url = add_query_arg(
2785
				array(
2786
					'action'   => 'activate_default_modules',
2787
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2788
				),
2789
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2790
			);
2791
			wp_safe_redirect( $url );
2792
			exit;
2793
		}
2794
2795
		/**
2796
		 * Fires before default modules are activated.
2797
		 *
2798
		 * @since 1.9.0
2799
		 *
2800
		 * @param string $min_version Minimum version number required to use modules.
2801
		 * @param string $max_version Maximum version number required to use modules.
2802
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2803
		 */
2804
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2805
2806
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2807
		if ( $send_state_messages ) {
2808
			Jetpack::restate();
2809
			Jetpack::catch_errors( true );
2810
		}
2811
2812
		$active = Jetpack::get_active_modules();
2813
2814
		foreach ( $modules as $module ) {
2815
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2816
				$active[] = $module;
2817
				self::update_active_modules( $active );
2818
				continue;
2819
			}
2820
2821
			if ( $send_state_messages && in_array( $module, $active ) ) {
2822
				$module_info = Jetpack::get_module( $module );
2823 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2824
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2825
					if ( $active_state = Jetpack::state( $state ) ) {
2826
						$active_state = explode( ',', $active_state );
2827
					} else {
2828
						$active_state = array();
2829
					}
2830
					$active_state[] = $module;
2831
					Jetpack::state( $state, implode( ',', $active_state ) );
2832
				}
2833
				continue;
2834
			}
2835
2836
			$file = Jetpack::get_module_path( $module );
2837
			if ( ! file_exists( $file ) ) {
2838
				continue;
2839
			}
2840
2841
			// we'll override this later if the plugin can be included without fatal error
2842
			if ( $redirect ) {
2843
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2844
			}
2845
2846
			if ( $send_state_messages ) {
2847
				Jetpack::state( 'error', 'module_activation_failed' );
2848
				Jetpack::state( 'module', $module );
2849
			}
2850
2851
			ob_start();
2852
			require_once $file;
2853
2854
			$active[] = $module;
2855
2856 View Code Duplication
			if ( $send_state_messages ) {
2857
2858
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2859
				if ( $active_state = Jetpack::state( $state ) ) {
2860
					$active_state = explode( ',', $active_state );
2861
				} else {
2862
					$active_state = array();
2863
				}
2864
				$active_state[] = $module;
2865
				Jetpack::state( $state, implode( ',', $active_state ) );
2866
			}
2867
2868
			Jetpack::update_active_modules( $active );
2869
2870
			ob_end_clean();
2871
		}
2872
2873
		if ( $send_state_messages ) {
2874
			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...
2875
			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...
2876
		}
2877
2878
		Jetpack::catch_errors( false );
2879
		/**
2880
		 * Fires when default modules are activated.
2881
		 *
2882
		 * @since 1.9.0
2883
		 *
2884
		 * @param string $min_version Minimum version number required to use modules.
2885
		 * @param string $max_version Maximum version number required to use modules.
2886
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2887
		 */
2888
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2889
	}
2890
2891
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2892
		/**
2893
		 * Fires before a module is activated.
2894
		 *
2895
		 * @since 2.6.0
2896
		 *
2897
		 * @param string $module Module slug.
2898
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2899
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2900
		 */
2901
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2902
2903
		$jetpack = Jetpack::init();
2904
2905
		if ( ! strlen( $module ) )
2906
			return false;
2907
2908
		if ( ! Jetpack::is_module( $module ) )
2909
			return false;
2910
2911
		// If it's already active, then don't do it again
2912
		$active = Jetpack::get_active_modules();
2913
		foreach ( $active as $act ) {
2914
			if ( $act == $module )
2915
				return true;
2916
		}
2917
2918
		$module_data = Jetpack::get_module( $module );
2919
2920
		if ( ! Jetpack::is_active() ) {
2921
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2922
				return false;
2923
2924
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2925
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2926
				return false;
2927
		}
2928
2929
		// Check and see if the old plugin is active
2930
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2931
			// Deactivate the old plugin
2932
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2933
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2934
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2935
				Jetpack::state( 'deactivated_plugins', $module );
2936
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2937
				exit;
2938
			}
2939
		}
2940
2941
		// Protect won't work with mis-configured IPs
2942
		if ( 'protect' === $module ) {
2943
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2944
			if ( ! jetpack_protect_get_ip() ) {
2945
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2946
				return false;
2947
			}
2948
		}
2949
2950
		if ( ! Jetpack_Plan::supports( $module ) ) {
2951
			return false;
2952
		}
2953
2954
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2955
		Jetpack::state( 'module', $module );
2956
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2957
2958
		Jetpack::catch_errors( true );
2959
		ob_start();
2960
		require Jetpack::get_module_path( $module );
2961
		/** This action is documented in class.jetpack.php */
2962
		do_action( 'jetpack_activate_module', $module );
2963
		$active[] = $module;
2964
		Jetpack::update_active_modules( $active );
2965
2966
		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...
2967
		ob_end_clean();
2968
		Jetpack::catch_errors( false );
2969
2970
		if ( $redirect ) {
2971
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2972
		}
2973
		if ( $exit ) {
2974
			exit;
2975
		}
2976
		return true;
2977
	}
2978
2979
	function activate_module_actions( $module ) {
2980
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
2981
	}
2982
2983
	public static function deactivate_module( $module ) {
2984
		/**
2985
		 * Fires when a module is deactivated.
2986
		 *
2987
		 * @since 1.9.0
2988
		 *
2989
		 * @param string $module Module slug.
2990
		 */
2991
		do_action( 'jetpack_pre_deactivate_module', $module );
2992
2993
		$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...
2994
2995
		$active = Jetpack::get_active_modules();
2996
		$new    = array_filter( array_diff( $active, (array) $module ) );
2997
2998
		return self::update_active_modules( $new );
2999
	}
3000
3001
	public static function enable_module_configurable( $module ) {
3002
		$module = Jetpack::get_module_slug( $module );
3003
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3004
	}
3005
3006
	/**
3007
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3008
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3009
	 *
3010
	 * @param string $module Module slug
3011
	 * @return string $url module configuration URL
3012
	 */
3013
	public static function module_configuration_url( $module ) {
3014
		$module = Jetpack::get_module_slug( $module );
3015
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3016
		/**
3017
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3018
		 *
3019
		 * @since 6.9.0
3020
		 *
3021
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3022
		 */
3023
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3024
3025
		return $url;
3026
	}
3027
3028
/* Installation */
3029
	public static function bail_on_activation( $message, $deactivate = true ) {
3030
?>
3031
<!doctype html>
3032
<html>
3033
<head>
3034
<meta charset="<?php bloginfo( 'charset' ); ?>">
3035
<style>
3036
* {
3037
	text-align: center;
3038
	margin: 0;
3039
	padding: 0;
3040
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3041
}
3042
p {
3043
	margin-top: 1em;
3044
	font-size: 18px;
3045
}
3046
</style>
3047
<body>
3048
<p><?php echo esc_html( $message ); ?></p>
3049
</body>
3050
</html>
3051
<?php
3052
		if ( $deactivate ) {
3053
			$plugins = get_option( 'active_plugins' );
3054
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3055
			$update  = false;
3056
			foreach ( $plugins as $i => $plugin ) {
3057
				if ( $plugin === $jetpack ) {
3058
					$plugins[$i] = false;
3059
					$update = true;
3060
				}
3061
			}
3062
3063
			if ( $update ) {
3064
				update_option( 'active_plugins', array_filter( $plugins ) );
3065
			}
3066
		}
3067
		exit;
3068
	}
3069
3070
	/**
3071
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3072
	 * @static
3073
	 */
3074
	public static function plugin_activation( $network_wide ) {
3075
		Jetpack_Options::update_option( 'activated', 1 );
3076
3077
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3078
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3079
		}
3080
3081
		if ( $network_wide )
3082
			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...
3083
3084
		// For firing one-off events (notices) immediately after activation
3085
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3086
3087
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3088
3089
		Jetpack::plugin_initialize();
3090
	}
3091
3092
	public static function get_activation_source( $referer_url ) {
3093
3094
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3095
			return array( 'wp-cli', null );
3096
		}
3097
3098
		$referer = parse_url( $referer_url );
3099
3100
		$source_type = 'unknown';
3101
		$source_query = null;
3102
3103
		if ( ! is_array( $referer ) ) {
3104
			return array( $source_type, $source_query );
3105
		}
3106
3107
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3108
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3109
3110
		if ( isset( $referer['query'] ) ) {
3111
			parse_str( $referer['query'], $query_parts );
3112
		} else {
3113
			$query_parts = array();
3114
		}
3115
3116
		if ( $plugins_path === $referer['path'] ) {
3117
			$source_type = 'list';
3118
		} elseif ( $plugins_install_path === $referer['path'] ) {
3119
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3120
			switch( $tab ) {
3121
				case 'popular':
3122
					$source_type = 'popular';
3123
					break;
3124
				case 'recommended':
3125
					$source_type = 'recommended';
3126
					break;
3127
				case 'favorites':
3128
					$source_type = 'favorites';
3129
					break;
3130
				case 'search':
3131
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3132
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3133
					break;
3134
				default:
3135
					$source_type = 'featured';
3136
			}
3137
		}
3138
3139
		return array( $source_type, $source_query );
3140
	}
3141
3142
	/**
3143
	 * Runs before bumping version numbers up to a new version
3144
	 * @param  string $version    Version:timestamp
3145
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3146
	 * @return null              [description]
3147
	 */
3148
	public static function do_version_bump( $version, $old_version ) {
3149
		if ( ! $old_version ) { // For new sites
3150
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3151
		}
3152
	}
3153
3154
	/**
3155
	 * Sets the internal version number and activation state.
3156
	 * @static
3157
	 */
3158
	public static function plugin_initialize() {
3159
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3160
			Jetpack_Options::update_option( 'activated', 2 );
3161
		}
3162
3163 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3164
			$version = $old_version = JETPACK__VERSION . ':' . time();
3165
			/** This action is documented in class.jetpack.php */
3166
			do_action( 'updating_jetpack_version', $version, false );
3167
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3168
		}
3169
3170
		Jetpack::load_modules();
3171
3172
		Jetpack_Options::delete_option( 'do_activate' );
3173
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3174
	}
3175
3176
	/**
3177
	 * Removes all connection options
3178
	 * @static
3179
	 */
3180
	public static function plugin_deactivation( ) {
3181
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3182
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3183
			Jetpack_Network::init()->deactivate();
3184
		} else {
3185
			Jetpack::disconnect( false );
3186
			//Jetpack_Heartbeat::init()->deactivate();
3187
		}
3188
	}
3189
3190
	/**
3191
	 * Disconnects from the Jetpack servers.
3192
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3193
	 * @static
3194
	 */
3195
	public static function disconnect( $update_activated_state = true ) {
3196
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3197
		$connection = self::connection();
3198
		$connection->clean_nonces( true );
3199
3200
		// If the site is in an IDC because sync is not allowed,
3201
		// let's make sure to not disconnect the production site.
3202
		if ( ! self::validate_sync_error_idc_option() ) {
3203
			$tracking = new Tracking();
3204
			$tracking->record_user_event( 'disconnect_site', array() );
3205
			Jetpack::load_xml_rpc_client();
3206
			$xml = new Jetpack_IXR_Client();
3207
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3208
		}
3209
3210
		Jetpack_Options::delete_option(
3211
			array(
3212
				'blog_token',
3213
				'user_token',
3214
				'user_tokens',
3215
				'master_user',
3216
				'time_diff',
3217
				'fallback_no_verify_ssl_certs',
3218
			)
3219
		);
3220
3221
		Jetpack_IDC::clear_all_idc_options();
3222
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3223
3224
		if ( $update_activated_state ) {
3225
			Jetpack_Options::update_option( 'activated', 4 );
3226
		}
3227
3228
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3229
			// Check then record unique disconnection if site has never been disconnected previously
3230
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3231
				$jetpack_unique_connection['disconnected'] = 1;
3232
			} else {
3233
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3234
					//track unique disconnect
3235
					$jetpack = Jetpack::init();
3236
3237
					$jetpack->stat( 'connections', 'unique-disconnect' );
3238
					$jetpack->do_stats( 'server_side' );
3239
				}
3240
				// increment number of times disconnected
3241
				$jetpack_unique_connection['disconnected'] += 1;
3242
			}
3243
3244
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3245
		}
3246
3247
		// Delete cached connected user data
3248
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3249
		delete_transient( $transient_key );
3250
3251
		// Delete all the sync related data. Since it could be taking up space.
3252
		Sender::get_instance()->uninstall();
3253
3254
		// Disable the Heartbeat cron
3255
		Jetpack_Heartbeat::init()->deactivate();
3256
	}
3257
3258
	/**
3259
	 * Unlinks the current user from the linked WordPress.com user.
3260
	 *
3261
	 * @deprecated since 7.7
3262
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3263
	 *
3264
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Should the type for parameter $user_id not be integer|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...
3265
	 * @return Boolean Whether the disconnection of the user was successful.
3266
	 */
3267
	public static function unlink_user( $user_id = null ) {
3268
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3269
		return Connection_Manager::disconnect_user( $user_id );
3270
	}
3271
3272
	/**
3273
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3274
	 */
3275
	public static function try_registration() {
3276
		// The user has agreed to the TOS at some point by now.
3277
		Jetpack_Options::update_option( 'tos_agreed', true );
3278
3279
		// Let's get some testing in beta versions and such.
3280
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3281
			// Before attempting to connect, let's make sure that the domains are viable.
3282
			$domains_to_check = array_unique( array(
3283
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3284
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3285
			) );
3286
			foreach ( $domains_to_check as $domain ) {
3287
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3286 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...
3288
				if ( is_wp_error( $result ) ) {
3289
					return $result;
3290
				}
3291
			}
3292
		}
3293
3294
		$result = Jetpack::register();
3295
3296
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3297
		if ( ! $result || is_wp_error( $result ) ) {
3298
			return $result;
3299
		} else {
3300
			return true;
3301
		}
3302
	}
3303
3304
	/**
3305
	 * Tracking an internal event log. Try not to put too much chaff in here.
3306
	 *
3307
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3308
	 */
3309
	public static function log( $code, $data = null ) {
3310
		// only grab the latest 200 entries
3311
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3312
3313
		// Append our event to the log
3314
		$log_entry = array(
3315
			'time'    => time(),
3316
			'user_id' => get_current_user_id(),
3317
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3318
			'code'    => $code,
3319
		);
3320
		// Don't bother storing it unless we've got some.
3321
		if ( ! is_null( $data ) ) {
3322
			$log_entry['data'] = $data;
3323
		}
3324
		$log[] = $log_entry;
3325
3326
		// Try add_option first, to make sure it's not autoloaded.
3327
		// @todo: Add an add_option method to Jetpack_Options
3328
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3329
			Jetpack_Options::update_option( 'log', $log );
3330
		}
3331
3332
		/**
3333
		 * Fires when Jetpack logs an internal event.
3334
		 *
3335
		 * @since 3.0.0
3336
		 *
3337
		 * @param array $log_entry {
3338
		 *	Array of details about the log entry.
3339
		 *
3340
		 *	@param string time Time of the event.
3341
		 *	@param int user_id ID of the user who trigerred the event.
3342
		 *	@param int blog_id Jetpack Blog ID.
3343
		 *	@param string code Unique name for the event.
3344
		 *	@param string data Data about the event.
3345
		 * }
3346
		 */
3347
		do_action( 'jetpack_log_entry', $log_entry );
3348
	}
3349
3350
	/**
3351
	 * Get the internal event log.
3352
	 *
3353
	 * @param $event (string) - only return the specific log events
3354
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3355
	 *
3356
	 * @return array of log events || WP_Error for invalid params
3357
	 */
3358
	public static function get_log( $event = false, $num = false ) {
3359
		if ( $event && ! is_string( $event ) ) {
3360
			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...
3361
		}
3362
3363
		if ( $num && ! is_numeric( $num ) ) {
3364
			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...
3365
		}
3366
3367
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3368
3369
		// If nothing set - act as it did before, otherwise let's start customizing the output
3370
		if ( ! $num && ! $event ) {
3371
			return $entire_log;
3372
		} else {
3373
			$entire_log = array_reverse( $entire_log );
3374
		}
3375
3376
		$custom_log_output = array();
3377
3378
		if ( $event ) {
3379
			foreach ( $entire_log as $log_event ) {
3380
				if ( $event == $log_event[ 'code' ] ) {
3381
					$custom_log_output[] = $log_event;
3382
				}
3383
			}
3384
		} else {
3385
			$custom_log_output = $entire_log;
3386
		}
3387
3388
		if ( $num ) {
3389
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3390
		}
3391
3392
		return $custom_log_output;
3393
	}
3394
3395
	/**
3396
	 * Log modification of important settings.
3397
	 */
3398
	public static function log_settings_change( $option, $old_value, $value ) {
3399
		switch( $option ) {
3400
			case 'jetpack_sync_non_public_post_stati':
3401
				self::log( $option, $value );
3402
				break;
3403
		}
3404
	}
3405
3406
	/**
3407
	 * Return stat data for WPCOM sync
3408
	 */
3409
	public static function get_stat_data( $encode = true, $extended = true ) {
3410
		$data = Jetpack_Heartbeat::generate_stats_array();
3411
3412
		if ( $extended ) {
3413
			$additional_data = self::get_additional_stat_data();
3414
			$data = array_merge( $data, $additional_data );
3415
		}
3416
3417
		if ( $encode ) {
3418
			return json_encode( $data );
3419
		}
3420
3421
		return $data;
3422
	}
3423
3424
	/**
3425
	 * Get additional stat data to sync to WPCOM
3426
	 */
3427
	public static function get_additional_stat_data( $prefix = '' ) {
3428
		$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...
3429
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3430
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3431
		$return["{$prefix}site-count"]     = 0;
3432
3433
		if ( function_exists( 'get_blog_count' ) ) {
3434
			$return["{$prefix}site-count"] = get_blog_count();
3435
		}
3436
		return $return;
3437
	}
3438
3439
	private static function get_site_user_count() {
3440
		global $wpdb;
3441
3442
		if ( function_exists( 'wp_is_large_network' ) ) {
3443
			if ( wp_is_large_network( 'users' ) ) {
3444
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3445
			}
3446
		}
3447
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3448
			// It wasn't there, so regenerate the data and save the transient
3449
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3450
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3451
		}
3452
		return $user_count;
3453
	}
3454
3455
	/* Admin Pages */
3456
3457
	function admin_init() {
3458
		// If the plugin is not connected, display a connect message.
3459
		if (
3460
			// the plugin was auto-activated and needs its candy
3461
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3462
		||
3463
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3464
			! Jetpack_Options::get_option( 'activated' )
3465
		) {
3466
			Jetpack::plugin_initialize();
3467
		}
3468
3469
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3470
			Jetpack_Connection_Banner::init();
3471
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3472
			// Upgrade: 1.1 -> 1.1.1
3473
			// Check and see if host can verify the Jetpack servers' SSL certificate
3474
			$args = array();
3475
			$connection = self::connection();
3476
			Client::_wp_remote_request(
3477
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3478
				$args,
3479
				true
3480
			);
3481
		}
3482
3483
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3484
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3485
		}
3486
3487
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3488
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3489
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3490
3491
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3492
			// Artificially throw errors in certain whitelisted cases during plugin activation
3493
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3494
		}
3495
3496
		// Add custom column in wp-admin/users.php to show whether user is linked.
3497
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3498
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3499
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3500
	}
3501
3502
	function admin_body_class( $admin_body_class = '' ) {
3503
		$classes = explode( ' ', trim( $admin_body_class ) );
3504
3505
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3506
3507
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3508
		return " $admin_body_class ";
3509
	}
3510
3511
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3512
		return $admin_body_class . ' jetpack-pagestyles ';
3513
	}
3514
3515
	/**
3516
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3517
	 * This function artificially throws errors for such cases (whitelisted).
3518
	 *
3519
	 * @param string $plugin The activated plugin.
3520
	 */
3521
	function throw_error_on_activate_plugin( $plugin ) {
3522
		$active_modules = Jetpack::get_active_modules();
3523
3524
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3525
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3526
			$throw = false;
3527
3528
			// Try and make sure it really was the stats plugin
3529
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3530
				if ( 'stats.php' == basename( $plugin ) ) {
3531
					$throw = true;
3532
				}
3533
			} else {
3534
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3535
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3536
					$throw = true;
3537
				}
3538
			}
3539
3540
			if ( $throw ) {
3541
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3542
			}
3543
		}
3544
	}
3545
3546
	function intercept_plugin_error_scrape_init() {
3547
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3548
	}
3549
3550
	function intercept_plugin_error_scrape( $action, $result ) {
3551
		if ( ! $result ) {
3552
			return;
3553
		}
3554
3555
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3556
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3557
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3558
			}
3559
		}
3560
	}
3561
3562
	function add_remote_request_handlers() {
3563
		add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
3564
		add_action( 'wp_ajax_nopriv_jetpack_update_file', array( $this, 'remote_request_handlers' ) );
3565
	}
3566
3567
	function remote_request_handlers() {
3568
		$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...
3569
3570
		switch ( current_filter() ) {
3571
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3572
			$response = $this->upload_handler();
3573
			break;
3574
3575
		case 'wp_ajax_nopriv_jetpack_update_file' :
3576
			$response = $this->upload_handler( true );
3577
			break;
3578
		default :
3579
			$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...
3580
			break;
3581
		}
3582
3583
		if ( ! $response ) {
3584
			$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...
3585
		}
3586
3587
		if ( is_wp_error( $response ) ) {
3588
			$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...
3589
			$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...
3590
			$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...
3591
3592
			if ( ! is_int( $status_code ) ) {
3593
				$status_code = 400;
3594
			}
3595
3596
			status_header( $status_code );
3597
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3598
		}
3599
3600
		status_header( 200 );
3601
		if ( true === $response ) {
3602
			exit;
3603
		}
3604
3605
		die( json_encode( (object) $response ) );
3606
	}
3607
3608
	/**
3609
	 * Uploads a file gotten from the global $_FILES.
3610
	 * If `$update_media_item` is true and `post_id` is defined
3611
	 * the attachment file of the media item (gotten through of the post_id)
3612
	 * will be updated instead of add a new one.
3613
	 *
3614
	 * @param  boolean $update_media_item - update media attachment
3615
	 * @return array - An array describing the uploadind files process
3616
	 */
3617
	function upload_handler( $update_media_item = false ) {
3618
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3619
			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...
3620
		}
3621
3622
		$user = wp_authenticate( '', '' );
3623
		if ( ! $user || is_wp_error( $user ) ) {
3624
			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...
3625
		}
3626
3627
		wp_set_current_user( $user->ID );
3628
3629
		if ( ! current_user_can( 'upload_files' ) ) {
3630
			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...
3631
		}
3632
3633
		if ( empty( $_FILES ) ) {
3634
			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...
3635
		}
3636
3637
		foreach ( array_keys( $_FILES ) as $files_key ) {
3638
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3639
				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...
3640
			}
3641
		}
3642
3643
		$media_keys = array_keys( $_FILES['media'] );
3644
3645
		$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...
3646
		if ( ! $token || is_wp_error( $token ) ) {
3647
			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...
3648
		}
3649
3650
		$uploaded_files = array();
3651
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3652
		unset( $GLOBALS['post'] );
3653
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3654
			$file = array();
3655
			foreach ( $media_keys as $media_key ) {
3656
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3657
			}
3658
3659
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3660
3661
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3662
			if ( $hmac_provided !== $hmac_file ) {
3663
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3664
				continue;
3665
			}
3666
3667
			$_FILES['.jetpack.upload.'] = $file;
3668
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3669
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3670
				$post_id = 0;
3671
			}
3672
3673
			if ( $update_media_item ) {
3674
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3675
					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...
3676
				}
3677
3678
				$media_array = $_FILES['media'];
3679
3680
				$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...
3681
				$file_array['type'] = $media_array['type'][0];
3682
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3683
				$file_array['error'] = $media_array['error'][0];
3684
				$file_array['size'] = $media_array['size'][0];
3685
3686
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3687
3688
				if ( is_wp_error( $edited_media_item ) ) {
3689
					return $edited_media_item;
3690
				}
3691
3692
				$response = (object) array(
3693
					'id'   => (string) $post_id,
3694
					'file' => (string) $edited_media_item->post_title,
3695
					'url'  => (string) wp_get_attachment_url( $post_id ),
3696
					'type' => (string) $edited_media_item->post_mime_type,
3697
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3698
				);
3699
3700
				return (array) array( $response );
3701
			}
3702
3703
			$attachment_id = media_handle_upload(
3704
				'.jetpack.upload.',
3705
				$post_id,
3706
				array(),
3707
				array(
3708
					'action' => 'jetpack_upload_file',
3709
				)
3710
			);
3711
3712
			if ( ! $attachment_id ) {
3713
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3714
			} elseif ( is_wp_error( $attachment_id ) ) {
3715
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3716
			} else {
3717
				$attachment = get_post( $attachment_id );
3718
				$uploaded_files[$index] = (object) array(
3719
					'id'   => (string) $attachment_id,
3720
					'file' => $attachment->post_title,
3721
					'url'  => wp_get_attachment_url( $attachment_id ),
3722
					'type' => $attachment->post_mime_type,
3723
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3724
				);
3725
				// Zip files uploads are not supported unless they are done for installation purposed
3726
				// lets delete them in case something goes wrong in this whole process
3727
				if ( 'application/zip' === $attachment->post_mime_type ) {
3728
					// Schedule a cleanup for 2 hours from now in case of failed install.
3729
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3730
				}
3731
			}
3732
		}
3733
		if ( ! is_null( $global_post ) ) {
3734
			$GLOBALS['post'] = $global_post;
3735
		}
3736
3737
		return $uploaded_files;
3738
	}
3739
3740
	/**
3741
	 * Add help to the Jetpack page
3742
	 *
3743
	 * @since Jetpack (1.2.3)
3744
	 * @return false if not the Jetpack page
3745
	 */
3746
	function admin_help() {
3747
		$current_screen = get_current_screen();
3748
3749
		// Overview
3750
		$current_screen->add_help_tab(
3751
			array(
3752
				'id'		=> 'home',
3753
				'title'		=> __( 'Home', 'jetpack' ),
3754
				'content'	=>
3755
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3756
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3757
					'<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>',
3758
			)
3759
		);
3760
3761
		// Screen Content
3762
		if ( current_user_can( 'manage_options' ) ) {
3763
			$current_screen->add_help_tab(
3764
				array(
3765
					'id'		=> 'settings',
3766
					'title'		=> __( 'Settings', 'jetpack' ),
3767
					'content'	=>
3768
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3769
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3770
						'<ol>' .
3771
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3772
							'<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>' .
3773
						'</ol>' .
3774
						'<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>'
3775
				)
3776
			);
3777
		}
3778
3779
		// Help Sidebar
3780
		$current_screen->set_help_sidebar(
3781
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3782
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3783
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3784
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3785
		);
3786
	}
3787
3788
	function admin_menu_css() {
3789
		wp_enqueue_style( 'jetpack-icons' );
3790
	}
3791
3792
	function admin_menu_order() {
3793
		return true;
3794
	}
3795
3796 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3797
		$jp_menu_order = array();
3798
3799
		foreach ( $menu_order as $index => $item ) {
3800
			if ( $item != 'jetpack' ) {
3801
				$jp_menu_order[] = $item;
3802
			}
3803
3804
			if ( $index == 0 ) {
3805
				$jp_menu_order[] = 'jetpack';
3806
			}
3807
		}
3808
3809
		return $jp_menu_order;
3810
	}
3811
3812
	function admin_banner_styles() {
3813
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3814
3815
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3816
			wp_register_style(
3817
				'jetpack-dops-style',
3818
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3819
				array(),
3820
				JETPACK__VERSION
3821
			);
3822
		}
3823
3824
		wp_enqueue_style(
3825
			'jetpack',
3826
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3827
			array( 'jetpack-dops-style' ),
3828
			 JETPACK__VERSION . '-20121016'
3829
		);
3830
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3831
		wp_style_add_data( 'jetpack', 'suffix', $min );
3832
	}
3833
3834
	function plugin_action_links( $actions ) {
3835
3836
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3837
3838
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3839
			return array_merge(
3840
				$jetpack_home,
3841
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3842
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3843
				$actions
3844
				);
3845
			}
3846
3847
		return array_merge( $jetpack_home, $actions );
3848
	}
3849
3850
	/*
3851
	 * Registration flow:
3852
	 * 1 - ::admin_page_load() action=register
3853
	 * 2 - ::try_registration()
3854
	 * 3 - ::register()
3855
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3856
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3857
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3858
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3859
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3860
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3861
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3862
	 *       jetpack_id, jetpack_secret, jetpack_public
3863
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3864
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3865
	 * 5 - user logs in with WP.com account
3866
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3867
	 *		- Jetpack_Client_Server::authorize()
3868
	 *		- Jetpack_Client_Server::get_token()
3869
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3870
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3871
	 *			- which responds with access_token, token_type, scope
3872
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3873
	 *		- Jetpack::activate_default_modules()
3874
	 *     		- Deactivates deprecated plugins
3875
	 *     		- Activates all default modules
3876
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3877
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3878
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3879
	 *     Done!
3880
	 */
3881
3882
	/**
3883
	 * Handles the page load events for the Jetpack admin page
3884
	 */
3885
	function admin_page_load() {
3886
		$error = false;
3887
3888
		// Make sure we have the right body class to hook stylings for subpages off of.
3889
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3890
3891
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3892
			// Should only be used in intermediate redirects to preserve state across redirects
3893
			Jetpack::restate();
3894
		}
3895
3896
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3897
			// @todo: Add validation against a known whitelist
3898
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3899
			// User clicked in the iframe to link their accounts
3900
			if ( ! Jetpack::is_user_connected() ) {
3901
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3902
3903
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3904
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3905
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3906
3907
				if ( isset( $_GET['notes_iframe'] ) )
3908
					$connect_url .= '&notes_iframe';
3909
				wp_redirect( $connect_url );
3910
				exit;
3911
			} else {
3912
				if ( ! isset( $_GET['calypso_env'] ) ) {
3913
					Jetpack::state( 'message', 'already_authorized' );
3914
					wp_safe_redirect( Jetpack::admin_url() );
3915
					exit;
3916
				} else {
3917
					$connect_url = $this->build_connect_url( true, false, $from );
3918
					$connect_url .= '&already_authorized=true';
3919
					wp_redirect( $connect_url );
3920
					exit;
3921
				}
3922
			}
3923
		}
3924
3925
3926
		if ( isset( $_GET['action'] ) ) {
3927
			switch ( $_GET['action'] ) {
3928
			case 'authorize':
3929
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
3930
					Jetpack::state( 'message', 'already_authorized' );
3931
					wp_safe_redirect( Jetpack::admin_url() );
3932
					exit;
3933
				}
3934
				Jetpack::log( 'authorize' );
3935
				$client_server = new Jetpack_Client_Server;
3936
				$client_server->client_authorize();
3937
				exit;
3938
			case 'register' :
3939
				if ( ! current_user_can( 'jetpack_connect' ) ) {
3940
					$error = 'cheatin';
3941
					break;
3942
				}
3943
				check_admin_referer( 'jetpack-register' );
3944
				Jetpack::log( 'register' );
3945
				Jetpack::maybe_set_version_option();
3946
				$registered = Jetpack::try_registration();
3947
				if ( is_wp_error( $registered ) ) {
3948
					$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...
3949
					Jetpack::state( 'error', $error );
3950
					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...
3951
3952
					/**
3953
					 * Jetpack registration Error.
3954
					 *
3955
					 * @since 7.5.0
3956
					 *
3957
					 * @param string|int $error The error code.
3958
					 * @param \WP_Error $registered The error object.
3959
					 */
3960
					do_action( 'jetpack_connection_register_fail', $error, $registered );
3961
					break;
3962
				}
3963
3964
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
3965
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
3966
3967
				/**
3968
				 * Jetpack registration Success.
3969
				 *
3970
				 * @since 7.5.0
3971
				 *
3972
				 * @param string $from 'from' GET parameter;
3973
				 */
3974
				do_action( 'jetpack_connection_register_success', $from );
3975
3976
				$url = $this->build_connect_url( true, $redirect, $from );
3977
3978
				if ( ! empty( $_GET['onboarding'] ) ) {
3979
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
3980
				}
3981
3982
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
3983
					$url = add_query_arg( 'auth_approved', 'true', $url );
3984
				}
3985
3986
				wp_redirect( $url );
3987
				exit;
3988
			case 'activate' :
3989
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
3990
					$error = 'cheatin';
3991
					break;
3992
				}
3993
3994
				$module = stripslashes( $_GET['module'] );
3995
				check_admin_referer( "jetpack_activate-$module" );
3996
				Jetpack::log( 'activate', $module );
3997
				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...
3998
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
3999
				}
4000
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4001
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4002
				exit;
4003
			case 'activate_default_modules' :
4004
				check_admin_referer( 'activate_default_modules' );
4005
				Jetpack::log( 'activate_default_modules' );
4006
				Jetpack::restate();
4007
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4008
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4009
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4010
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4011
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4012
				exit;
4013
			case 'disconnect' :
4014
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4015
					$error = 'cheatin';
4016
					break;
4017
				}
4018
4019
				check_admin_referer( 'jetpack-disconnect' );
4020
				Jetpack::log( 'disconnect' );
4021
				Jetpack::disconnect();
4022
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4023
				exit;
4024
			case 'reconnect' :
4025
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4026
					$error = 'cheatin';
4027
					break;
4028
				}
4029
4030
				check_admin_referer( 'jetpack-reconnect' );
4031
				Jetpack::log( 'reconnect' );
4032
				$this->disconnect();
4033
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4034
				exit;
4035 View Code Duplication
			case 'deactivate' :
4036
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4037
					$error = 'cheatin';
4038
					break;
4039
				}
4040
4041
				$modules = stripslashes( $_GET['module'] );
4042
				check_admin_referer( "jetpack_deactivate-$modules" );
4043
				foreach ( explode( ',', $modules ) as $module ) {
4044
					Jetpack::log( 'deactivate', $module );
4045
					Jetpack::deactivate_module( $module );
4046
					Jetpack::state( 'message', 'module_deactivated' );
4047
				}
4048
				Jetpack::state( 'module', $modules );
4049
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4050
				exit;
4051
			case 'unlink' :
4052
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4053
				check_admin_referer( 'jetpack-unlink' );
4054
				Jetpack::log( 'unlink' );
4055
				Connection_Manager::disconnect_user();
4056
				Jetpack::state( 'message', 'unlinked' );
4057
				if ( 'sub-unlink' == $redirect ) {
4058
					wp_safe_redirect( admin_url() );
4059
				} else {
4060
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4061
				}
4062
				exit;
4063
			case 'onboard' :
4064
				if ( ! current_user_can( 'manage_options' ) ) {
4065
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4066
				} else {
4067
					Jetpack::create_onboarding_token();
4068
					$url = $this->build_connect_url( true );
4069
4070
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4071
						$url = add_query_arg( 'onboarding', $token, $url );
4072
					}
4073
4074
					$calypso_env = $this->get_calypso_env();
4075
					if ( ! empty( $calypso_env ) ) {
4076
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4077
					}
4078
4079
					wp_redirect( $url );
4080
					exit;
4081
				}
4082
				exit;
4083
			default:
4084
				/**
4085
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4086
				 *
4087
				 * @since 2.6.0
4088
				 *
4089
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4090
				 */
4091
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4092
			}
4093
		}
4094
4095
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4096
			self::activate_new_modules( true );
4097
		}
4098
4099
		$message_code = Jetpack::state( 'message' );
4100
		if ( Jetpack::state( 'optin-manage' ) ) {
4101
			$activated_manage = $message_code;
4102
			$message_code = 'jetpack-manage';
4103
		}
4104
4105
		switch ( $message_code ) {
4106
		case 'jetpack-manage':
4107
			$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>';
4108
			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...
4109
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4110
			}
4111
			break;
4112
4113
		}
4114
4115
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4116
4117
		if ( ! empty( $deactivated_plugins ) ) {
4118
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4119
			$deactivated_titles  = array();
4120
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4121
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4122
					continue;
4123
				}
4124
4125
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4126
			}
4127
4128
			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...
4129
				if ( $this->message ) {
4130
					$this->message .= "<br /><br />\n";
4131
				}
4132
4133
				$this->message .= wp_sprintf(
4134
					_n(
4135
						'Jetpack contains the most recent version of the old %l plugin.',
4136
						'Jetpack contains the most recent versions of the old %l plugins.',
4137
						count( $deactivated_titles ),
4138
						'jetpack'
4139
					),
4140
					$deactivated_titles
4141
				);
4142
4143
				$this->message .= "<br />\n";
4144
4145
				$this->message .= _n(
4146
					'The old version has been deactivated and can be removed from your site.',
4147
					'The old versions have been deactivated and can be removed from your site.',
4148
					count( $deactivated_titles ),
4149
					'jetpack'
4150
				);
4151
			}
4152
		}
4153
4154
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4155
4156
		if ( $this->message || $this->error || $this->privacy_checks ) {
4157
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4158
		}
4159
4160
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4161
	}
4162
4163
	function admin_notices() {
4164
4165
		if ( $this->error ) {
4166
?>
4167
<div id="message" class="jetpack-message jetpack-err">
4168
	<div class="squeezer">
4169
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4170
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4171
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4172
<?php	endif; ?>
4173
	</div>
4174
</div>
4175
<?php
4176
		}
4177
4178
		if ( $this->message ) {
4179
?>
4180
<div id="message" class="jetpack-message">
4181
	<div class="squeezer">
4182
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4183
	</div>
4184
</div>
4185
<?php
4186
		}
4187
4188
		if ( $this->privacy_checks ) :
4189
			$module_names = $module_slugs = array();
4190
4191
			$privacy_checks = explode( ',', $this->privacy_checks );
4192
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4193
			foreach ( $privacy_checks as $module_slug ) {
4194
				$module = Jetpack::get_module( $module_slug );
4195
				if ( ! $module ) {
4196
					continue;
4197
				}
4198
4199
				$module_slugs[] = $module_slug;
4200
				$module_names[] = "<strong>{$module['name']}</strong>";
4201
			}
4202
4203
			$module_slugs = join( ',', $module_slugs );
4204
?>
4205
<div id="message" class="jetpack-message jetpack-err">
4206
	<div class="squeezer">
4207
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4208
		<p><?php
4209
			echo wp_kses(
4210
				wptexturize(
4211
					wp_sprintf(
4212
						_nx(
4213
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4214
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4215
							count( $privacy_checks ),
4216
							'%l = list of Jetpack module/feature names',
4217
							'jetpack'
4218
						),
4219
						$module_names
4220
					)
4221
				),
4222
				array( 'strong' => true )
4223
			);
4224
4225
			echo "\n<br />\n";
4226
4227
			echo wp_kses(
4228
				sprintf(
4229
					_nx(
4230
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4231
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4232
						count( $privacy_checks ),
4233
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4234
						'jetpack'
4235
					),
4236
					wp_nonce_url(
4237
						Jetpack::admin_url(
4238
							array(
4239
								'page'   => 'jetpack',
4240
								'action' => 'deactivate',
4241
								'module' => urlencode( $module_slugs ),
4242
							)
4243
						),
4244
						"jetpack_deactivate-$module_slugs"
4245
					),
4246
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4247
				),
4248
				array( 'a' => array( 'href' => true, 'title' => true ) )
4249
			);
4250
		?></p>
4251
	</div>
4252
</div>
4253
<?php endif;
4254
	}
4255
4256
	/**
4257
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4258
	 */
4259
	function stat( $group, $detail ) {
4260
		if ( ! isset( $this->stats[ $group ] ) )
4261
			$this->stats[ $group ] = array();
4262
		$this->stats[ $group ][] = $detail;
4263
	}
4264
4265
	/**
4266
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4267
	 */
4268
	function do_stats( $method = '' ) {
4269
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4270
			foreach ( $this->stats as $group => $stats ) {
4271
				if ( is_array( $stats ) && count( $stats ) ) {
4272
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4273
					if ( 'server_side' === $method ) {
4274
						self::do_server_side_stat( $args );
4275
					} else {
4276
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4277
					}
4278
				}
4279
				unset( $this->stats[ $group ] );
4280
			}
4281
		}
4282
	}
4283
4284
	/**
4285
	 * Runs stats code for a one-off, server-side.
4286
	 *
4287
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4288
	 *
4289
	 * @return bool If it worked.
4290
	 */
4291
	static function do_server_side_stat( $args ) {
4292
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4293
		if ( is_wp_error( $response ) )
4294
			return false;
4295
4296
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4297
			return false;
4298
4299
		return true;
4300
	}
4301
4302
	/**
4303
	 * Builds the stats url.
4304
	 *
4305
	 * @param $args array|string The arguments to append to the URL.
4306
	 *
4307
	 * @return string The URL to be pinged.
4308
	 */
4309
	static function build_stats_url( $args ) {
4310
		$defaults = array(
4311
			'v'    => 'wpcom2',
4312
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4313
		);
4314
		$args     = wp_parse_args( $args, $defaults );
4315
		/**
4316
		 * Filter the URL used as the Stats tracking pixel.
4317
		 *
4318
		 * @since 2.3.2
4319
		 *
4320
		 * @param string $url Base URL used as the Stats tracking pixel.
4321
		 */
4322
		$base_url = apply_filters(
4323
			'jetpack_stats_base_url',
4324
			'https://pixel.wp.com/g.gif'
4325
		);
4326
		$url      = add_query_arg( $args, $base_url );
4327
		return $url;
4328
	}
4329
4330
	/**
4331
	 * Get the role of the current user.
4332
	 *
4333
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4334
	 *
4335
	 * @access public
4336
	 * @static
4337
	 *
4338
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4339
	 */
4340
	public static function translate_current_user_to_role() {
4341
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4342
4343
		$roles = new Roles();
4344
		return $roles->translate_current_user_to_role();
4345
	}
4346
4347
	/**
4348
	 * Get the role of a particular user.
4349
	 *
4350
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4351
	 *
4352
	 * @access public
4353
	 * @static
4354
	 *
4355
	 * @param \WP_User $user User object.
4356
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4357
	 */
4358
	public static function translate_user_to_role( $user ) {
4359
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4360
4361
		$roles = new Roles();
4362
		return $roles->translate_user_to_role( $user );
4363
	}
4364
4365
	/**
4366
	 * Get the minimum capability for a role.
4367
	 *
4368
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4369
	 *
4370
	 * @access public
4371
	 * @static
4372
	 *
4373
	 * @param string $role Role name.
4374
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4375
	 */
4376
	public static function translate_role_to_cap( $role ) {
4377
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4378
4379
		$roles = new Roles();
4380
		return $roles->translate_role_to_cap( $role );
4381
	}
4382
4383
	static function sign_role( $role, $user_id = null ) {
4384
		if ( empty( $user_id ) ) {
4385
			$user_id = (int) get_current_user_id();
4386
		}
4387
4388
		if ( ! $user_id  ) {
4389
			return false;
4390
		}
4391
4392
		$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...
4393
		if ( ! $token || is_wp_error( $token ) ) {
4394
			return false;
4395
		}
4396
4397
		return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
4398
	}
4399
4400
4401
	/**
4402
	 * Builds a URL to the Jetpack connection auth page
4403
	 *
4404
	 * @since 3.9.5
4405
	 *
4406
	 * @param bool $raw If true, URL will not be escaped.
4407
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4408
	 *                              If string, will be a custom redirect.
4409
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4410
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4411
	 *
4412
	 * @return string Connect URL
4413
	 */
4414
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4415
		$site_id = Jetpack_Options::get_option( 'id' );
4416
		$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...
4417
4418
		if ( $register || ! $blog_token || ! $site_id ) {
4419
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4420
4421
			if ( ! empty( $redirect ) ) {
4422
				$url = add_query_arg(
4423
					'redirect',
4424
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4425
					$url
4426
				);
4427
			}
4428
4429
			if( is_network_admin() ) {
4430
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4431
			}
4432
		} else {
4433
4434
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4435
			// because otherwise this logic can get us in to a loop.
4436
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4437
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4438
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4439
4440
				$response = Client::wpcom_json_api_request_as_blog(
4441
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4442
					'1.1'
4443
				);
4444
4445
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4446
4447
					// Generating a register URL instead to refresh the existing token
4448
					return $this->build_connect_url( $raw, $redirect, $from, true );
4449
				}
4450
			}
4451
4452
			if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4453
				$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4454
			}
4455
4456
			$roles       = new Roles();
4457
			$role        = $roles->translate_current_user_to_role();
4458
			$signed_role = self::sign_role( $role );
4459
4460
			$user = wp_get_current_user();
4461
4462
			$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4463
			$redirect = $redirect
4464
				? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4465
				: $jetpack_admin_page;
4466
4467
			if( isset( $_REQUEST['is_multisite'] ) ) {
4468
				$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4469
			}
4470
4471
			$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4472
4473
			/**
4474
			 * Filter the type of authorization.
4475
			 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4476
			 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4477
			 *
4478
			 * @since 4.3.3
4479
			 *
4480
			 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4481
			 */
4482
			$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4483
4484
4485
			$tracks = new Tracking();
4486
			$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4487
4488
			$args = urlencode_deep(
4489
				array(
4490
					'response_type' => 'code',
4491
					'client_id'     => Jetpack_Options::get_option( 'id' ),
4492
					'redirect_uri'  => add_query_arg(
4493
						array(
4494
							'action'   => 'authorize',
4495
							'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4496
							'redirect' => urlencode( $redirect ),
4497
						),
4498
						esc_url( admin_url( 'admin.php?page=jetpack' ) )
4499
					),
4500
					'state'         => $user->ID,
4501
					'scope'         => $signed_role,
4502
					'user_email'    => $user->user_email,
4503
					'user_login'    => $user->user_login,
4504
					'is_active'     => Jetpack::is_active(),
4505
					'jp_version'    => JETPACK__VERSION,
4506
					'auth_type'     => $auth_type,
4507
					'secret'        => $secrets['secret_1'],
4508
					'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4509
					'blogname'      => get_option( 'blogname' ),
4510
					'site_url'      => site_url(),
4511
					'home_url'      => home_url(),
4512
					'site_icon'     => get_site_icon_url(),
4513
					'site_lang'     => get_locale(),
4514
					'_ui'           => $tracks_identity['_ui'],
4515
					'_ut'           => $tracks_identity['_ut'],
4516
					'site_created'  => Jetpack::get_assumed_site_creation_date(),
4517
				)
4518
			);
4519
4520
			self::apply_activation_source_to_args( $args );
4521
4522
			$connection = self::connection();
4523
			$url = add_query_arg( $args, $connection->api_url( 'authorize' ) );
4524
		}
4525
4526
		if ( $from ) {
4527
			$url = add_query_arg( 'from', $from, $url );
4528
		}
4529
4530
		// Ensure that class to get the affiliate code is loaded
4531
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4532
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4533
		}
4534
		// Get affiliate code and add it to the URL
4535
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4536
4537
		$calypso_env = $this->get_calypso_env();
4538
4539
		if ( ! empty( $calypso_env ) ) {
4540
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4541
		}
4542
4543
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4544
	}
4545
4546
	/**
4547
	 * Get our assumed site creation date.
4548
	 * Calculated based on the earlier date of either:
4549
	 * - Earliest admin user registration date.
4550
	 * - Earliest date of post of any post type.
4551
	 *
4552
	 * @since 7.2.0
4553
	 *
4554
	 * @return string Assumed site creation date and time.
4555
	 */
4556 View Code Duplication
	public static function get_assumed_site_creation_date() {
4557
		$earliest_registered_users = get_users( array(
4558
			'role'    => 'administrator',
4559
			'orderby' => 'user_registered',
4560
			'order'   => 'ASC',
4561
			'fields'  => array( 'user_registered' ),
4562
			'number'  => 1,
4563
		) );
4564
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4565
4566
		$earliest_posts = get_posts( array(
4567
			'posts_per_page' => 1,
4568
			'post_type'      => 'any',
4569
			'post_status'    => 'any',
4570
			'orderby'        => 'date',
4571
			'order'          => 'ASC',
4572
		) );
4573
4574
		// If there are no posts at all, we'll count only on user registration date.
4575
		if ( $earliest_posts ) {
4576
			$earliest_post_date = $earliest_posts[0]->post_date;
4577
		} else {
4578
			$earliest_post_date = PHP_INT_MAX;
4579
		}
4580
4581
		return min( $earliest_registration_date, $earliest_post_date );
4582
	}
4583
4584 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4585
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4586
4587
		if ( $activation_source_name ) {
4588
			$args['_as'] = urlencode( $activation_source_name );
4589
		}
4590
4591
		if ( $activation_source_keyword ) {
4592
			$args['_ak'] = urlencode( $activation_source_keyword );
4593
		}
4594
	}
4595
4596
	function build_reconnect_url( $raw = false ) {
4597
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4598
		return $raw ? $url : esc_url( $url );
4599
	}
4600
4601
	public static function admin_url( $args = null ) {
4602
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4603
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4604
		return $url;
4605
	}
4606
4607
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4608
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4609
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4610
	}
4611
4612
	function dismiss_jetpack_notice() {
4613
4614
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4615
			return;
4616
		}
4617
4618
		switch( $_GET['jetpack-notice'] ) {
4619
			case 'dismiss':
4620
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4621
4622
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4623
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4624
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4625
				}
4626
				break;
4627
			case 'jetpack-protect-multisite-opt-out':
4628
4629
				if ( check_admin_referer( 'jetpack_protect_multisite_banner_opt_out' ) ) {
4630
					// Don't show the banner again
4631
4632
					update_site_option( 'jetpack_dismissed_protect_multisite_banner', true );
4633
					// redirect back to the page that had the notice
4634
					if ( wp_get_referer() ) {
4635
						wp_safe_redirect( wp_get_referer() );
4636
					} else {
4637
						// Take me to Jetpack
4638
						wp_safe_redirect( admin_url( 'admin.php?page=jetpack' ) );
4639
					}
4640
				}
4641
				break;
4642
		}
4643
	}
4644
4645
	public static function sort_modules( $a, $b ) {
4646
		if ( $a['sort'] == $b['sort'] )
4647
			return 0;
4648
4649
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4650
	}
4651
4652
	function ajax_recheck_ssl() {
4653
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4654
		$result = Jetpack::permit_ssl( true );
4655
		wp_send_json( array(
4656
			'enabled' => $result,
4657
			'message' => get_transient( 'jetpack_https_test_message' )
4658
		) );
4659
	}
4660
4661
/* Client API */
4662
4663
	/**
4664
	 * Returns the requested Jetpack API URL
4665
	 *
4666
	 * @deprecated since 7.7
4667
	 * @return string
4668
	 */
4669
	public static function api_url( $relative_url ) {
4670
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4671
		$connection = self::connection();
4672
		return $connection->api_url( $relative_url );
4673
	}
4674
4675
	/**
4676
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4677
	 */
4678
	public static function fix_url_for_bad_hosts( $url ) {
4679
		if ( 0 !== strpos( $url, 'https://' ) ) {
4680
			return $url;
4681
		}
4682
4683
		switch ( JETPACK_CLIENT__HTTPS ) {
4684
			case 'ALWAYS' :
4685
				return $url;
4686
			case 'NEVER' :
4687
				return set_url_scheme( $url, 'http' );
4688
			// default : case 'AUTO' :
4689
		}
4690
4691
		// we now return the unmodified SSL URL by default, as a security precaution
4692
		return $url;
4693
	}
4694
4695
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4696
		// Default to a blog token.
4697
		$token_type = 'blog';
4698
4699
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4700
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4701
			if ( ! empty( $_GET['onboarding'] ) ) {
4702
				$jpo = $_GET;
4703
			} else {
4704
				$jpo = json_decode( $request_data, true );
4705
			}
4706
4707
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4708
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4709
4710
			if (
4711
				isset( $jpo_user )
4712
				&& isset( $jpo_token )
4713
				&& is_email( $jpo_user )
4714
				&& ctype_alnum( $jpo_token )
4715
				&& isset( $_GET['rest_route'] )
4716
				&& self::validate_onboarding_token_action(
4717
					$jpo_token,
4718
					$_GET['rest_route']
4719
				)
4720
			) {
4721
				$jp_user = get_user_by( 'email', $jpo_user );
4722
				if ( is_a( $jp_user, 'WP_User' ) ) {
4723
					wp_set_current_user( $jp_user->ID );
4724
					$user_can = is_multisite()
4725
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4726
						: current_user_can( 'manage_options' );
4727
					if ( $user_can ) {
4728
						$token_type = 'user';
4729
						$token->external_user_id = $jp_user->ID;
4730
					}
4731
				}
4732
			}
4733
4734
			$token_data['type']    = $token_type;
4735
			$token_data['user_id'] = $token->external_user_id;
4736
		}
4737
4738
		return $token_data;
4739
	}
4740
4741
	/**
4742
	 * Create a random secret for validating onboarding payload
4743
	 *
4744
	 * @return string Secret token
4745
	 */
4746
	public static function create_onboarding_token() {
4747
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4748
			$token = wp_generate_password( 32, false );
4749
			Jetpack_Options::update_option( 'onboarding', $token );
4750
		}
4751
4752
		return $token;
4753
	}
4754
4755
	/**
4756
	 * Remove the onboarding token
4757
	 *
4758
	 * @return bool True on success, false on failure
4759
	 */
4760
	public static function invalidate_onboarding_token() {
4761
		return Jetpack_Options::delete_option( 'onboarding' );
4762
	}
4763
4764
	/**
4765
	 * Validate an onboarding token for a specific action
4766
	 *
4767
	 * @return boolean True if token/action pair is accepted, false if not
4768
	 */
4769
	public static function validate_onboarding_token_action( $token, $action ) {
4770
		// Compare tokens, bail if tokens do not match
4771
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4772
			return false;
4773
		}
4774
4775
		// List of valid actions we can take
4776
		$valid_actions = array(
4777
			'/jetpack/v4/settings',
4778
		);
4779
4780
		// Whitelist the action
4781
		if ( ! in_array( $action, $valid_actions ) ) {
4782
			return false;
4783
		}
4784
4785
		return true;
4786
	}
4787
4788
	/**
4789
	 * Checks to see if the URL is using SSL to connect with Jetpack
4790
	 *
4791
	 * @since 2.3.3
4792
	 * @return boolean
4793
	 */
4794
	public static function permit_ssl( $force_recheck = false ) {
4795
		// Do some fancy tests to see if ssl is being supported
4796
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4797
			$message = '';
4798
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4799
				$ssl = 0;
4800
			} else {
4801
				switch ( JETPACK_CLIENT__HTTPS ) {
4802
					case 'NEVER':
4803
						$ssl = 0;
4804
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4805
						break;
4806
					case 'ALWAYS':
4807
					case 'AUTO':
4808
					default:
4809
						$ssl = 1;
4810
						break;
4811
				}
4812
4813
				// If it's not 'NEVER', test to see
4814
				if ( $ssl ) {
4815
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4816
						$ssl = 0;
4817
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4818
					} else {
4819
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4820
						if ( is_wp_error( $response ) ) {
4821
							$ssl = 0;
4822
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4823
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4824
							$ssl = 0;
4825
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4826
						}
4827
					}
4828
				}
4829
			}
4830
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4831
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4832
		}
4833
4834
		return (bool) $ssl;
4835
	}
4836
4837
	/*
4838
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4839
	 */
4840
	public function alert_auto_ssl_fail() {
4841
		if ( ! current_user_can( 'manage_options' ) )
4842
			return;
4843
4844
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4845
		?>
4846
4847
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4848
			<div class="jp-banner__content">
4849
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4850
				<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>
4851
				<p>
4852
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4853
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4854
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4855
				</p>
4856
				<p>
4857
					<?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' ),
4858
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4859
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4860
				</p>
4861
			</div>
4862
		</div>
4863
		<style>
4864
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4865
		</style>
4866
		<script type="text/javascript">
4867
			jQuery( document ).ready( function( $ ) {
4868
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4869
					var $this = $( this );
4870
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4871
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4872
					e.preventDefault();
4873
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4874
					$.post( ajaxurl, data )
4875
					  .done( function( response ) {
4876
					  	if ( response.enabled ) {
4877
					  		$( '#jetpack-ssl-warning' ).hide();
4878
					  	} else {
4879
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4880
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4881
					  	}
4882
					  }.bind( $this ) );
4883
				} );
4884
			} );
4885
		</script>
4886
4887
		<?php
4888
	}
4889
4890
	/**
4891
	 * Returns the Jetpack XML-RPC API
4892
	 *
4893
	 * @return string
4894
	 */
4895
	public static function xmlrpc_api_url() {
4896
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4897
		return untrailingslashit( $base ) . '/xmlrpc.php';
4898
	}
4899
4900
	public static function connection() {
4901
		return self::init()->connection_manager;
4902
	}
4903
4904
	/**
4905
	 * Creates two secret tokens and the end of life timestamp for them.
4906
	 *
4907
	 * Note these tokens are unique per call, NOT static per site for connecting.
4908
	 *
4909
	 * @since 2.6
4910
	 * @return array
4911
	 */
4912
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4913
		if ( false === $user_id ) {
4914
			$user_id = get_current_user_id();
4915
		}
4916
4917
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4918
	}
4919
4920
	public static function get_secrets( $action, $user_id ) {
4921
		$secrets = self::connection()->get_secrets( $action, $user_id );
4922
4923
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4924
			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...
4925
		}
4926
4927
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4928
			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...
4929
		}
4930
4931
		return $secrets;
4932
	}
4933
4934
	/**
4935
	 * @deprecated 7.5 Use Connection_Manager instead.
4936
	 *
4937
	 * @param $action
4938
	 * @param $user_id
4939
	 */
4940
	public static function delete_secrets( $action, $user_id ) {
4941
		return self::connection()->delete_secrets( $action, $user_id );
4942
	}
4943
4944
	/**
4945
	 * Builds the timeout limit for queries talking with the wpcom servers.
4946
	 *
4947
	 * Based on local php max_execution_time in php.ini
4948
	 *
4949
	 * @since 2.6
4950
	 * @return int
4951
	 * @deprecated
4952
	 **/
4953
	public function get_remote_query_timeout_limit() {
4954
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
4955
		return Jetpack::get_max_execution_time();
4956
	}
4957
4958
	/**
4959
	 * Builds the timeout limit for queries talking with the wpcom servers.
4960
	 *
4961
	 * Based on local php max_execution_time in php.ini
4962
	 *
4963
	 * @since 5.4
4964
	 * @return int
4965
	 **/
4966
	public static function get_max_execution_time() {
4967
		$timeout = (int) ini_get( 'max_execution_time' );
4968
4969
		// Ensure exec time set in php.ini
4970
		if ( ! $timeout ) {
4971
			$timeout = 30;
4972
		}
4973
		return $timeout;
4974
	}
4975
4976
	/**
4977
	 * Sets a minimum request timeout, and returns the current timeout
4978
	 *
4979
	 * @since 5.4
4980
	 **/
4981 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
4982
		$timeout = self::get_max_execution_time();
4983
		if ( $timeout < $min_timeout ) {
4984
			$timeout = $min_timeout;
4985
			set_time_limit( $timeout );
4986
		}
4987
		return $timeout;
4988
	}
4989
4990
	/**
4991
	 * Takes the response from the Jetpack register new site endpoint and
4992
	 * verifies it worked properly.
4993
	 *
4994
	 * @since 2.6
4995
	 * @deprecated since 7.7.0
4996
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
4997
	 **/
4998
	public function validate_remote_register_response() {
4999
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5000
	}
5001
5002
	/**
5003
	 * @return bool|WP_Error
5004
	 */
5005
	public static function register() {
5006
		$tracking = new Tracking();
5007
		$tracking->record_user_event( 'jpc_register_begin' );
5008
5009
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5010
5011
		$connection = self::connection();
5012
		$registration = $connection->register();
5013
5014
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5015
5016
		if ( ! $registration || is_wp_error( $registration ) ) {
5017
			return $registration;
5018
		}
5019
5020
		return true;
5021
	}
5022
5023
	/**
5024
	 * Filters the registration request body to include tracking properties.
5025
	 *
5026
	 * @param Array $properties
5027
	 * @return Array amended properties.
5028
	 */
5029
	public static function filter_register_request_body( $properties ) {
5030
		$tracking = new Tracking();
5031
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5032
5033
		return array_merge(
5034
			$properties,
5035
			array(
5036
				'_ui' => $tracks_identity['_ui'],
5037
				'_ut' => $tracks_identity['_ut'],
5038
			)
5039
		);
5040
	}
5041
5042
	/**
5043
	 * If the db version is showing something other that what we've got now, bump it to current.
5044
	 *
5045
	 * @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...
5046
	 */
5047
	public static function maybe_set_version_option() {
5048
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5049
		if ( JETPACK__VERSION != $version ) {
5050
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5051
5052
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5053
				/** This action is documented in class.jetpack.php */
5054
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5055
			}
5056
5057
			return true;
5058
		}
5059
		return false;
5060
	}
5061
5062
/* Client Server API */
5063
5064
	/**
5065
	 * Loads the Jetpack XML-RPC client
5066
	 */
5067
	public static function load_xml_rpc_client() {
5068
		require_once ABSPATH . WPINC . '/class-IXR.php';
5069
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
5070
	}
5071
5072
	/**
5073
	 * Resets the saved authentication state in between testing requests.
5074
	 */
5075
	public function reset_saved_auth_state() {
5076
		$this->rest_authentication_status = null;
5077
		$this->connection_manager->reset_saved_auth_state();
5078
	}
5079
5080
	/**
5081
	 * Verifies the signature of the current request.
5082
	 *
5083
	 * @deprecated since 7.7.0
5084
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5085
	 *
5086
	 * @return false|array
5087
	 */
5088
	public function verify_xml_rpc_signature() {
5089
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5090
		return self::connection()->verify_xml_rpc_signature();
5091
	}
5092
5093
	/**
5094
	 * Verifies the signature of the current request.
5095
	 *
5096
	 * This function has side effects and should not be used. Instead,
5097
	 * use the memoized version `->verify_xml_rpc_signature()`.
5098
	 *
5099
	 * @deprecated since 7.7.0
5100
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5101
	 * @internal
5102
	 */
5103
	private function internal_verify_xml_rpc_signature() {
5104
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5105
	}
5106
5107
	/**
5108
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5109
	 *
5110
	 * @deprecated since 7.7.0
5111
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5112
	 *
5113
	 * @param \WP_User|mixed $user     User object if authenticated.
5114
	 * @param string         $username Username.
5115
	 * @param string         $password Password string.
5116
	 * @return \WP_User|mixed Authenticated user or error.
5117
	 */
5118
	public function authenticate_jetpack( $user, $username, $password ) {
5119
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5120
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5121
	}
5122
5123
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5124
	// Uses the existing XMLRPC request signing implementation.
5125
	function wp_rest_authenticate( $user ) {
5126
		if ( ! empty( $user ) ) {
5127
			// Another authentication method is in effect.
5128
			return $user;
5129
		}
5130
5131
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5132
			// Nothing to do for this authentication method.
5133
			return null;
5134
		}
5135
5136
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5137
			// Nothing to do for this authentication method.
5138
			return null;
5139
		}
5140
5141
		// Ensure that we always have the request body available.  At this
5142
		// point, the WP REST API code to determine the request body has not
5143
		// run yet.  That code may try to read from 'php://input' later, but
5144
		// this can only be done once per request in PHP versions prior to 5.6.
5145
		// So we will go ahead and perform this read now if needed, and save
5146
		// the request body where both the Jetpack signature verification code
5147
		// and the WP REST API code can see it.
5148
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5149
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5150
		}
5151
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5152
5153
		// Only support specific request parameters that have been tested and
5154
		// are known to work with signature verification.  A different method
5155
		// can be passed to the WP REST API via the '?_method=' parameter if
5156
		// needed.
5157
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5158
			$this->rest_authentication_status = new WP_Error(
5159
				'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...
5160
				__( 'This request method is not supported.', 'jetpack' ),
5161
				array( 'status' => 400 )
5162
			);
5163
			return null;
5164
		}
5165
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5166
			$this->rest_authentication_status = new WP_Error(
5167
				'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...
5168
				__( 'This request method does not support body parameters.', 'jetpack' ),
5169
				array( 'status' => 400 )
5170
			);
5171
			return null;
5172
		}
5173
5174
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5175
5176
		if (
5177
			$verified &&
5178
			isset( $verified['type'] ) &&
5179
			'user' === $verified['type'] &&
5180
			! empty( $verified['user_id'] )
5181
		) {
5182
			// Authentication successful.
5183
			$this->rest_authentication_status = true;
5184
			return $verified['user_id'];
5185
		}
5186
5187
		// Something else went wrong.  Probably a signature error.
5188
		$this->rest_authentication_status = new WP_Error(
5189
			'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...
5190
			__( 'The request is not signed correctly.', 'jetpack' ),
5191
			array( 'status' => 400 )
5192
		);
5193
		return null;
5194
	}
5195
5196
	/**
5197
	 * Report authentication status to the WP REST API.
5198
	 *
5199
	 * @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...
5200
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5201
	 */
5202
	public function wp_rest_authentication_errors( $value ) {
5203
		if ( $value !== null ) {
5204
			return $value;
5205
		}
5206
		return $this->rest_authentication_status;
5207
	}
5208
5209
	/**
5210
	 * Add our nonce to this request.
5211
	 *
5212
	 * @deprecated since 7.7.0
5213
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5214
	 *
5215
	 * @param int    $timestamp Timestamp of the request.
5216
	 * @param string $nonce     Nonce string.
5217
	 */
5218
	public function add_nonce( $timestamp, $nonce ) {
5219
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5220
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5221
	}
5222
5223
	/**
5224
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5225
	 * Capture it here so we can verify the signature later.
5226
	 *
5227
	 * @deprecated since 7.7.0
5228
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5229
	 *
5230
	 * @param array $methods XMLRPC methods.
5231
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5232
	 */
5233
	public function xmlrpc_methods( $methods ) {
5234
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5235
		return $this->connection_manager->xmlrpc_methods( $methods );
5236
	}
5237
5238
	/**
5239
	 * Register additional public XMLRPC methods.
5240
	 *
5241
	 * @deprecated since 7.7.0
5242
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5243
	 *
5244
	 * @param array $methods Public XMLRPC methods.
5245
	 * @return array Public XMLRPC methods, with the getOptions one.
5246
	 */
5247
	public function public_xmlrpc_methods( $methods ) {
5248
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5249
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5250
	}
5251
5252
	/**
5253
	 * Handles a getOptions XMLRPC method call.
5254
	 *
5255
	 * @deprecated since 7.7.0
5256
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5257
	 *
5258
	 * @param array $args method call arguments.
5259
	 * @return array an amended XMLRPC server options array.
5260
	 */
5261
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5262
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5263
		return $this->connection_manager->jetpack_getOptions( $args );
5264
	}
5265
5266
	/**
5267
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5268
	 *
5269
	 * @deprecated since 7.7.0
5270
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5271
	 *
5272
	 * @param array $options Standard Core options.
5273
	 * @return array Amended options.
5274
	 */
5275
	public function xmlrpc_options( $options ) {
5276
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5277
		return $this->connection_manager->xmlrpc_options( $options );
5278
	}
5279
5280
	/**
5281
	 * Cleans nonces that were saved when calling ::add_nonce.
5282
	 *
5283
	 * @deprecated since 7.7.0
5284
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5285
	 *
5286
	 * @param bool $all whether to clean even non-expired nonces.
5287
	 */
5288
	public static function clean_nonces( $all = false ) {
5289
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5290
		return self::connection()->clean_nonces( $all );
5291
	}
5292
5293
	/**
5294
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5295
	 * SET: state( $key, $value );
5296
	 * GET: $value = state( $key );
5297
	 *
5298
	 * @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...
5299
	 * @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...
5300
	 * @param bool $restate private
5301
	 */
5302
	public static function state( $key = null, $value = null, $restate = false ) {
5303
		static $state = array();
5304
		static $path, $domain;
5305
		if ( ! isset( $path ) ) {
5306
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5307
			$admin_url = Jetpack::admin_url();
5308
			$bits      = wp_parse_url( $admin_url );
5309
5310
			if ( is_array( $bits ) ) {
5311
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5312
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5313
			} else {
5314
				$path = $domain = null;
5315
			}
5316
		}
5317
5318
		// Extract state from cookies and delete cookies
5319
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5320
			$yum = $_COOKIE[ 'jetpackState' ];
5321
			unset( $_COOKIE[ 'jetpackState' ] );
5322
			foreach ( $yum as $k => $v ) {
5323
				if ( strlen( $v ) )
5324
					$state[ $k ] = $v;
5325
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5326
			}
5327
		}
5328
5329
		if ( $restate ) {
5330
			foreach ( $state as $k => $v ) {
5331
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5332
			}
5333
			return;
5334
		}
5335
5336
		// Get a state variable
5337
		if ( isset( $key ) && ! isset( $value ) ) {
5338
			if ( array_key_exists( $key, $state ) )
5339
				return $state[ $key ];
5340
			return null;
5341
		}
5342
5343
		// Set a state variable
5344
		if ( isset ( $key ) && isset( $value ) ) {
5345
			if( is_array( $value ) && isset( $value[0] ) ) {
5346
				$value = $value[0];
5347
			}
5348
			$state[ $key ] = $value;
5349
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5350
		}
5351
	}
5352
5353
	public static function restate() {
5354
		Jetpack::state( null, null, true );
5355
	}
5356
5357
	public static function check_privacy( $file ) {
5358
		static $is_site_publicly_accessible = null;
5359
5360
		if ( is_null( $is_site_publicly_accessible ) ) {
5361
			$is_site_publicly_accessible = false;
5362
5363
			Jetpack::load_xml_rpc_client();
5364
			$rpc = new Jetpack_IXR_Client();
5365
5366
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5367
			if ( $success ) {
5368
				$response = $rpc->getResponse();
5369
				if ( $response ) {
5370
					$is_site_publicly_accessible = true;
5371
				}
5372
			}
5373
5374
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5375
		}
5376
5377
		if ( $is_site_publicly_accessible ) {
5378
			return;
5379
		}
5380
5381
		$module_slug = self::get_module_slug( $file );
5382
5383
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5384
		if ( ! $privacy_checks ) {
5385
			$privacy_checks = $module_slug;
5386
		} else {
5387
			$privacy_checks .= ",$module_slug";
5388
		}
5389
5390
		Jetpack::state( 'privacy_checks', $privacy_checks );
5391
	}
5392
5393
	/**
5394
	 * Helper method for multicall XMLRPC.
5395
	 */
5396
	public static function xmlrpc_async_call() {
5397
		global $blog_id;
5398
		static $clients = array();
5399
5400
		$client_blog_id = is_multisite() ? $blog_id : 0;
5401
5402
		if ( ! isset( $clients[$client_blog_id] ) ) {
5403
			Jetpack::load_xml_rpc_client();
5404
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5405
			if ( function_exists( 'ignore_user_abort' ) ) {
5406
				ignore_user_abort( true );
5407
			}
5408
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5409
		}
5410
5411
		$args = func_get_args();
5412
5413
		if ( ! empty( $args[0] ) ) {
5414
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5415
		} elseif ( is_multisite() ) {
5416
			foreach ( $clients as $client_blog_id => $client ) {
5417
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5418
					continue;
5419
				}
5420
5421
				$switch_success = switch_to_blog( $client_blog_id, true );
5422
				if ( ! $switch_success ) {
5423
					continue;
5424
				}
5425
5426
				flush();
5427
				$client->query();
5428
5429
				restore_current_blog();
5430
			}
5431
		} else {
5432
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5433
				flush();
5434
				$clients[0]->query();
5435
			}
5436
		}
5437
	}
5438
5439
	public static function staticize_subdomain( $url ) {
5440
5441
		// Extract hostname from URL
5442
		$host = parse_url( $url, PHP_URL_HOST );
5443
5444
		// Explode hostname on '.'
5445
		$exploded_host = explode( '.', $host );
5446
5447
		// Retrieve the name and TLD
5448
		if ( count( $exploded_host ) > 1 ) {
5449
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5450
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5451
			// Rebuild domain excluding subdomains
5452
			$domain = $name . '.' . $tld;
5453
		} else {
5454
			$domain = $host;
5455
		}
5456
		// Array of Automattic domains
5457
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5458
5459
		// Return $url if not an Automattic domain
5460
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5461
			return $url;
5462
		}
5463
5464
		if ( is_ssl() ) {
5465
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5466
		}
5467
5468
		srand( crc32( basename( $url ) ) );
5469
		$static_counter = rand( 0, 2 );
5470
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5471
5472
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5473
	}
5474
5475
/* JSON API Authorization */
5476
5477
	/**
5478
	 * Handles the login action for Authorizing the JSON API
5479
	 */
5480
	function login_form_json_api_authorization() {
5481
		$this->verify_json_api_authorization_request();
5482
5483
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5484
5485
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5486
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5487
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5488
	}
5489
5490
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5491
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5492
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5493
			return $url;
5494
		}
5495
5496
		$parsed_url = parse_url( $url );
5497
		$url = strtok( $url, '?' );
5498
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5499
		if ( ! empty( $parsed_url['query'] ) )
5500
			$url .= "&{$parsed_url['query']}";
5501
5502
		return $url;
5503
	}
5504
5505
	// Make sure the POSTed request is handled by the same action
5506
	function preserve_action_in_login_form_for_json_api_authorization() {
5507
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5508
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5509
	}
5510
5511
	// If someone logs in to approve API access, store the Access Code in usermeta
5512
	function store_json_api_authorization_token( $user_login, $user ) {
5513
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5514
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5515
		$token = wp_generate_password( 32, false );
5516
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5517
	}
5518
5519
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5520
	function allow_wpcom_public_api_domain( $domains ) {
5521
		$domains[] = 'public-api.wordpress.com';
5522
		return $domains;
5523
	}
5524
5525
	static function is_redirect_encoded( $redirect_url ) {
5526
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5527
	}
5528
5529
	// Add all wordpress.com environments to the safe redirect whitelist
5530
	function allow_wpcom_environments( $domains ) {
5531
		$domains[] = 'wordpress.com';
5532
		$domains[] = 'wpcalypso.wordpress.com';
5533
		$domains[] = 'horizon.wordpress.com';
5534
		$domains[] = 'calypso.localhost';
5535
		return $domains;
5536
	}
5537
5538
	// Add the Access Code details to the public-api.wordpress.com redirect
5539
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5540
		return add_query_arg(
5541
			urlencode_deep(
5542
				array(
5543
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5544
					'jetpack-user-id' => (int) $user->ID,
5545
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5546
				)
5547
			),
5548
			$redirect_to
5549
		);
5550
	}
5551
5552
5553
	/**
5554
	 * Verifies the request by checking the signature
5555
	 *
5556
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5557
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5558
	 *
5559
	 * @param null|array $environment
5560
	 */
5561
	function verify_json_api_authorization_request( $environment = null ) {
5562
		$environment = is_null( $environment )
5563
			? $_REQUEST
5564
			: $environment;
5565
5566
		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...
5567
		$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...
5568
		if ( ! $token || empty( $token->secret ) ) {
5569
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5570
		}
5571
5572
		$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' );
5573
5574
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5575
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5576
			/**
5577
			 * Jetpack authorisation request Error.
5578
			 *
5579
			 * @since 7.5.0
5580
			 *
5581
			 */
5582
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5583
			$die_error = sprintf(
5584
				/* translators: %s is a URL */
5585
				__( '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' ),
5586
				'https://jetpack.com/support/double-encoding/'
5587
			);
5588
		}
5589
5590
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5591
5592
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5593
			$signature = $jetpack_signature->sign_request(
5594
				$environment['token'],
5595
				$environment['timestamp'],
5596
				$environment['nonce'],
5597
				'',
5598
				'GET',
5599
				$environment['jetpack_json_api_original_query'],
5600
				null,
5601
				true
5602
			);
5603
		} else {
5604
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5605
		}
5606
5607
		if ( ! $signature ) {
5608
			wp_die( $die_error );
5609
		} else if ( is_wp_error( $signature ) ) {
5610
			wp_die( $die_error );
5611
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5612
			if ( is_ssl() ) {
5613
				// 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
5614
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5615
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5616
					wp_die( $die_error );
5617
				}
5618
			} else {
5619
				wp_die( $die_error );
5620
			}
5621
		}
5622
5623
		$timestamp = (int) $environment['timestamp'];
5624
		$nonce     = stripslashes( (string) $environment['nonce'] );
5625
5626
		if ( ! $this->connection->add_nonce( $timestamp, $nonce ) ) {
0 ignored issues
show
The property connection does not seem to exist. Did you mean connection_manager?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

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