Completed
Push — add/new-disconnect-dialog ( f9b90a )
by
unknown
18:50 queued 12:20
created

class.jetpack.php (61 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
	 * The handles of scripts that can be loaded asynchronously.
86
	 *
87
	 * @var array
88
	 */
89
	public $async_script_handles = array(
90
		'woocommerce-analytics',
91
	);
92
93
	/**
94
	 * Contains all assets that have had their URL rewritten to minified versions.
95
	 *
96
	 * @var array
97
	 */
98
	static $min_assets = array();
99
100
	public $plugins_to_deactivate = array(
101
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
102
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
103
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
104
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
105
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
106
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
107
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
108
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
109
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
110
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
111
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
112
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
113
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
114
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
115
	);
116
117
	/**
118
	 * Map of roles we care about, and their corresponding minimum capabilities.
119
	 *
120
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
121
	 *
122
	 * @access public
123
	 * @static
124
	 *
125
	 * @var array
126
	 */
127
	public static $capability_translations = array(
128
		'administrator' => 'manage_options',
129
		'editor'        => 'edit_others_posts',
130
		'author'        => 'publish_posts',
131
		'contributor'   => 'edit_posts',
132
		'subscriber'    => 'read',
133
	);
134
135
	/**
136
	 * Map of modules that have conflicts with plugins and should not be auto-activated
137
	 * if the plugins are active.  Used by filter_default_modules
138
	 *
139
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
140
	 * change `module-slug` and add this to your plugin:
141
	 *
142
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
143
	 * function my_jetpack_get_default_modules( $modules ) {
144
	 *     return array_diff( $modules, array( 'module-slug' ) );
145
	 * }
146
	 *
147
	 * @var array
148
	 */
149
	private $conflicting_plugins = array(
150
		'comments'          => array(
151
			'Intense Debate'                       => 'intensedebate/intensedebate.php',
152
			'Disqus'                               => 'disqus-comment-system/disqus.php',
153
			'Livefyre'                             => 'livefyre-comments/livefyre.php',
154
			'Comments Evolved for WordPress'       => 'gplus-comments/comments-evolved.php',
155
			'Google+ Comments'                     => 'google-plus-comments/google-plus-comments.php',
156
			'WP-SpamShield Anti-Spam'              => 'wp-spamshield/wp-spamshield.php',
157
		),
158
		'comment-likes' => array(
159
			'Epoch'                                => 'epoch/plugincore.php',
160
		),
161
		'contact-form'      => array(
162
			'Contact Form 7'                       => 'contact-form-7/wp-contact-form-7.php',
163
			'Gravity Forms'                        => 'gravityforms/gravityforms.php',
164
			'Contact Form Plugin'                  => 'contact-form-plugin/contact_form.php',
165
			'Easy Contact Forms'                   => 'easy-contact-forms/easy-contact-forms.php',
166
			'Fast Secure Contact Form'             => 'si-contact-form/si-contact-form.php',
167
			'Ninja Forms'                          => 'ninja-forms/ninja-forms.php',
168
		),
169
		'minileven'         => array(
170
			'WPtouch'                              => 'wptouch/wptouch.php',
171
		),
172
		'latex'             => array(
173
			'LaTeX for WordPress'                  => 'latex/latex.php',
174
			'Youngwhans Simple Latex'              => 'youngwhans-simple-latex/yw-latex.php',
175
			'Easy WP LaTeX'                        => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
176
			'MathJax-LaTeX'                        => 'mathjax-latex/mathjax-latex.php',
177
			'Enable Latex'                         => 'enable-latex/enable-latex.php',
178
			'WP QuickLaTeX'                        => 'wp-quicklatex/wp-quicklatex.php',
179
		),
180
		'protect'           => array(
181
			'Limit Login Attempts'                 => 'limit-login-attempts/limit-login-attempts.php',
182
			'Captcha'                              => 'captcha/captcha.php',
183
			'Brute Force Login Protection'         => 'brute-force-login-protection/brute-force-login-protection.php',
184
			'Login Security Solution'              => 'login-security-solution/login-security-solution.php',
185
			'WPSecureOps Brute Force Protect'      => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
186
			'BulletProof Security'                 => 'bulletproof-security/bulletproof-security.php',
187
			'SiteGuard WP Plugin'                  => 'siteguard/siteguard.php',
188
			'Security-protection'                  => 'security-protection/security-protection.php',
189
			'Login Security'                       => 'login-security/login-security.php',
190
			'Botnet Attack Blocker'                => 'botnet-attack-blocker/botnet-attack-blocker.php',
191
			'Wordfence Security'                   => 'wordfence/wordfence.php',
192
			'All In One WP Security & Firewall'    => 'all-in-one-wp-security-and-firewall/wp-security.php',
193
			'iThemes Security'                     => 'better-wp-security/better-wp-security.php',
194
		),
195
		'random-redirect'   => array(
196
			'Random Redirect 2'                    => 'random-redirect-2/random-redirect.php',
197
		),
198
		'related-posts'     => array(
199
			'YARPP'                                => 'yet-another-related-posts-plugin/yarpp.php',
200
			'WordPress Related Posts'              => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
201
			'nrelate Related Content'              => 'nrelate-related-content/nrelate-related.php',
202
			'Contextual Related Posts'             => 'contextual-related-posts/contextual-related-posts.php',
203
			'Related Posts for WordPress'          => 'microkids-related-posts/microkids-related-posts.php',
204
			'outbrain'                             => 'outbrain/outbrain.php',
205
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
206
			'Sexybookmarks'                        => 'sexybookmarks/shareaholic.php',
207
		),
208
		'sharedaddy'        => array(
209
			'AddThis'                              => 'addthis/addthis_social_widget.php',
210
			'Add To Any'                           => 'add-to-any/add-to-any.php',
211
			'ShareThis'                            => 'share-this/sharethis.php',
212
			'Shareaholic'                          => 'shareaholic/shareaholic.php',
213
		),
214
		'seo-tools' => array(
215
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
216
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
217
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
218
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
219
			'The SEO Framework'                    => 'autodescription/autodescription.php',
220
		),
221
		'verification-tools' => array(
222
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
223
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
224
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
225
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
226
			'The SEO Framework'                    => 'autodescription/autodescription.php',
227
		),
228
		'widget-visibility' => array(
229
			'Widget Logic'                         => 'widget-logic/widget_logic.php',
230
			'Dynamic Widgets'                      => 'dynamic-widgets/dynamic-widgets.php',
231
		),
232
		'sitemaps' => array(
233
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
234
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
235
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
236
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
237
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
238
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
239
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
240
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242
			'The SEO Framework'                    => 'autodescription/autodescription.php',
243
			'Sitemap'                              => 'sitemap/sitemap.php',
244
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
245
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
246
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
247
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
248
		),
249
		'lazy-images' => array(
250
			'Lazy Load'              => 'lazy-load/lazy-load.php',
251
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
252
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
253
		),
254
	);
255
256
	/**
257
	 * Plugins for which we turn off our Facebook OG Tags implementation.
258
	 *
259
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
260
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
261
	 *
262
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
263
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
264
	 */
265
	private $open_graph_conflicting_plugins = array(
266
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
267
		                                                         // 2 Click Social Media Buttons
268
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
269
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
270
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
271
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
272
		                                                         // Open Graph Meta Tags by Heateor
273
		'facebook/facebook.php',                                 // Facebook (official plugin)
274
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
275
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
276
		                                                         // Facebook Featured Image & OG Meta Tags
277
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
278
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
279
		                                                         // Facebook Open Graph Meta Tags for WordPress
280
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
281
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
282
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
283
		                                                         // Fedmich's Facebook Open Graph Meta
284
		'network-publisher/networkpub.php',                      // Network Publisher
285
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
286
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
287
		                                                         // NextScripts SNAP
288
		'og-tags/og-tags.php',                                   // OG Tags
289
		'opengraph/opengraph.php',                               // Open Graph
290
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
291
		                                                         // Open Graph Protocol Framework
292
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
293
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
294
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
295
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
296
		'sharepress/sharepress.php',                             // SharePress
297
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
298
		'social-discussions/social-discussions.php',             // Social Discussions
299
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
300
		'socialize/socialize.php',                               // Socialize
301
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
302
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
303
		                                                         // Tweet, Like, Google +1 and Share
304
		'wordbooker/wordbooker.php',                             // Wordbooker
305
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
306
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
307
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
308
		                                                         // WP Facebook Like Send & Open Graph Meta
309
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
310
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
311
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
312
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
313
		'open-graph-metabox/open-graph-metabox.php'              // Open Graph Metabox
314
	);
315
316
	/**
317
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
318
	 */
319
	private $twitter_cards_conflicting_plugins = array(
320
	//	'twitter/twitter.php',                       // The official one handles this on its own.
321
	//	                                             // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
322
		'eewee-twitter-card/index.php',              // Eewee Twitter Card
323
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
324
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
325
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
326
		                                             // Pure Web Brilliant's Social Graph Twitter Cards Extension
327
		'twitter-cards/twitter-cards.php',           // Twitter Cards
328
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
329
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
330
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
331
	);
332
333
	/**
334
	 * Message to display in admin_notice
335
	 * @var string
336
	 */
337
	public $message = '';
338
339
	/**
340
	 * Error to display in admin_notice
341
	 * @var string
342
	 */
343
	public $error = '';
344
345
	/**
346
	 * Modules that need more privacy description.
347
	 * @var string
348
	 */
349
	public $privacy_checks = '';
350
351
	/**
352
	 * Stats to record once the page loads
353
	 *
354
	 * @var array
355
	 */
356
	public $stats = array();
357
358
	/**
359
	 * Jetpack_Sync object
360
	 */
361
	public $sync;
362
363
	/**
364
	 * Verified data for JSON authorization request
365
	 */
366
	public $json_api_authorization_request = array();
367
368
	/**
369
	 * @var \Automattic\Jetpack\Connection\Manager
370
	 */
371
	protected $connection_manager;
372
373
	/**
374
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
375
	 */
376
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
377
378
	/**
379
	 * Holds the singleton instance of this class
380
	 * @since 2.3.3
381
	 * @var Jetpack
382
	 */
383
	static $instance = false;
384
385
	/**
386
	 * Singleton
387
	 * @static
388
	 */
389
	public static function init() {
390
		if ( ! self::$instance ) {
391
			self::$instance = new Jetpack;
392
393
			self::$instance->plugin_upgrade();
394
		}
395
396
		return self::$instance;
397
	}
398
399
	/**
400
	 * Must never be called statically
401
	 */
402
	function plugin_upgrade() {
403
		if ( Jetpack::is_active() ) {
404
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
405
			if ( JETPACK__VERSION != $version ) {
406
				// Prevent multiple upgrades at once - only a single process should trigger
407
				// an upgrade to avoid stampedes
408
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
409
					return;
410
				}
411
412
				// Set a short lock to prevent multiple instances of the upgrade
413
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
414
415
				// check which active modules actually exist and remove others from active_modules list
416
				$unfiltered_modules = Jetpack::get_active_modules();
417
				$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
418
				if ( array_diff( $unfiltered_modules, $modules ) ) {
419
					Jetpack::update_active_modules( $modules );
420
				}
421
422
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
423
424
				// Upgrade to 4.3.0
425
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
426
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
427
				}
428
429
				// Make sure Markdown for posts gets turned back on
430
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
431
					update_option( 'wpcom_publish_posts_with_markdown', true );
432
				}
433
434
				if ( did_action( 'wp_loaded' ) ) {
435
					self::upgrade_on_load();
436
				} else {
437
					add_action(
438
						'wp_loaded',
439
						array( __CLASS__, 'upgrade_on_load' )
440
					);
441
				}
442
			}
443
		}
444
	}
445
446
	/**
447
	 * Runs upgrade routines that need to have modules loaded.
448
	 */
449
	static function upgrade_on_load() {
450
451
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
452
		// This can happen in case Jetpack has been just upgraded and is
453
		// being initialized late during the page load. In this case we wait
454
		// until the next proper admin page load with Jetpack active.
455
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
456
			delete_transient( self::$plugin_upgrade_lock_key );
457
458
			return;
459
		}
460
461
		Jetpack::maybe_set_version_option();
462
463
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
464
			Jetpack_Widget_Conditions::migrate_post_type_rules();
465
		}
466
467
		if (
468
			class_exists( 'Jetpack_Sitemap_Manager' )
469
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
470
		) {
471
			do_action( 'jetpack_sitemaps_purge_data' );
472
		}
473
474
		// Delete old stats cache
475
		delete_option( 'jetpack_restapi_stats_cache' );
476
477
		delete_transient( self::$plugin_upgrade_lock_key );
478
	}
479
480
	/**
481
	 * Saves all the currently active modules to options.
482
	 * Also fires Action hooks for each newly activated and deactivated module.
483
	 *
484
	 * @param $modules Array Array of active modules to be saved in options.
485
	 *
486
	 * @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...
487
	 */
488
	static function update_active_modules( $modules ) {
489
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
490
		$active_modules       = Jetpack::get_active_modules();
491
		$new_active_modules   = array_diff( $modules, $current_modules );
492
		$new_inactive_modules = array_diff( $active_modules, $modules );
493
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
494
		$reindexed_modules    = array_values( $new_current_modules );
495
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
496
497
		foreach ( $new_active_modules as $module ) {
498
			/**
499
			 * Fires when a specific module is activated.
500
			 *
501
			 * @since 1.9.0
502
			 *
503
			 * @param string $module Module slug.
504
			 * @param boolean $success whether the module was activated. @since 4.2
505
			 */
506
			do_action( 'jetpack_activate_module', $module, $success );
507
			/**
508
			 * Fires when a module is activated.
509
			 * The dynamic part of the filter, $module, is the module slug.
510
			 *
511
			 * @since 1.9.0
512
			 *
513
			 * @param string $module Module slug.
514
			 */
515
			do_action( "jetpack_activate_module_$module", $module );
516
		}
517
518
		foreach ( $new_inactive_modules as $module ) {
519
			/**
520
			 * Fired after a module has been deactivated.
521
			 *
522
			 * @since 4.2.0
523
			 *
524
			 * @param string $module Module slug.
525
			 * @param boolean $success whether the module was deactivated.
526
			 */
527
			do_action( 'jetpack_deactivate_module', $module, $success );
528
			/**
529
			 * Fires when a module is deactivated.
530
			 * The dynamic part of the filter, $module, is the module slug.
531
			 *
532
			 * @since 1.9.0
533
			 *
534
			 * @param string $module Module slug.
535
			 */
536
			do_action( "jetpack_deactivate_module_$module", $module );
537
		}
538
539
		return $success;
540
	}
541
542
	static function delete_active_modules() {
543
		self::update_active_modules( array() );
544
	}
545
546
	/**
547
	 * Constructor.  Initializes WordPress hooks
548
	 */
549
	private function __construct() {
550
		/*
551
		 * Check for and alert any deprecated hooks
552
		 */
553
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
554
555
		/*
556
		 * Enable enhanced handling of previewing sites in Calypso
557
		 */
558
		if ( Jetpack::is_active() ) {
559
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
560
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
561
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
562
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
563
		}
564
565
		if ( self::jetpack_tos_agreed() ) {
566
			$tracking = new Automattic\Jetpack\Plugin\Tracking();
567
			add_action( 'init', array( $tracking, 'init' ) );
568
		}
569
570
571
		add_filter( 'jetpack_connection_secret_generator', function( $callable ) {
572
			return function() {
573
				return wp_generate_password( 32, false );
574
			};
575
		} );
576
577
		$this->connection_manager = new Connection_Manager();
578
		$this->connection_manager->init();
579
580
		/*
581
		 * Load things that should only be in Network Admin.
582
		 *
583
		 * For now blow away everything else until a more full
584
		 * understanding of what is needed at the network level is
585
		 * available
586
		 */
587
		if ( is_multisite() ) {
588
			$network = Jetpack_Network::init();
589
			$network->set_connection( $this->connection_manager );
590
		}
591
592
		add_filter(
593
			'jetpack_signature_check_token',
594
			array( __CLASS__, 'verify_onboarding_token' ),
595
			10,
596
			3
597
		);
598
599
		/**
600
		 * Prepare Gutenberg Editor functionality
601
		 */
602
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
603
		Jetpack_Gutenberg::init();
604
		Jetpack_Gutenberg::load_independent_blocks();
605
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
606
607
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
608
609
		// Unlink user before deleting the user from WP.com.
610
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
611
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
612
613
		// Initialize remote file upload request handlers.
614
		$this->add_remote_request_handlers();
615
616
		if ( Jetpack::is_active() ) {
617
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
618
619
			Jetpack_Heartbeat::init();
620
			if ( Jetpack::is_module_active( 'stats' ) && Jetpack::is_module_active( 'search' ) ) {
621
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
622
				Jetpack_Search_Performance_Logger::init();
623
			}
624
		}
625
626
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
627
628
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
629
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
630
631
		add_action( 'admin_init', array( $this, 'admin_init' ) );
632
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
633
634
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
635
636
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
637
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
638
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
639
640
		// returns HTTPS support status
641
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
642
643
		// JITM AJAX callback function
644
		add_action( 'wp_ajax_jitm_ajax',  array( $this, 'jetpack_jitm_ajax_callback' ) );
645
646
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
647
648
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
649
		add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
650
		add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
651
		add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
652
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
653
654
		add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
655
656
		/**
657
		 * These actions run checks to load additional files.
658
		 * They check for external files or plugins, so they need to run as late as possible.
659
		 */
660
		add_action( 'wp_head', array( $this, 'check_open_graph' ),       1 );
661
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ),     999 );
662
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
663
664
		add_filter( 'plugins_url',      array( 'Jetpack', 'maybe_min_asset' ),     1, 3 );
665
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2  );
666
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
667
668
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
669
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
670
671
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
672
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
673
674
		// A filter to control all just in time messages
675
		add_filter( 'jetpack_just_in_time_msgs', array( $this, 'is_active_and_not_development_mode' ), 9 );
676
677
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9);
678
679
		// If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
680
		// We should make sure to only do this for front end links.
681
		if ( Jetpack::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
682
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
683
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
684
685
			//we'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
686
			//so they point moderation links on emails to Calypso
687
			jetpack_require_lib( 'functions.wp-notify' );
688
		}
689
690
		// Hide edit post link if mobile app.
691
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
692
			add_filter( 'edit_post_link', '__return_empty_string' );
693
		}
694
695
		// Update the Jetpack plan from API on heartbeats
696
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
697
698
		/**
699
		 * This is the hack to concatenate all css files into one.
700
		 * For description and reasoning see the implode_frontend_css method
701
		 *
702
		 * Super late priority so we catch all the registered styles
703
		 */
704
		if( !is_admin() ) {
705
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
706
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
707
		}
708
709
710
		/**
711
		 * These are sync actions that we need to keep track of for jitms
712
		 */
713
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
714
715
		// Actually push the stats on shutdown.
716
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
717
			add_action( 'shutdown', array( $this, 'push_stats' ) );
718
		}
719
720
		/*
721
		 * Load some scripts asynchronously.
722
		 */
723
		add_action( 'script_loader_tag', array( $this, 'script_add_async' ), 10, 3 );
724
	}
725
726
	/**
727
	 * Sets up the XMLRPC request handlers.
728
	 *
729
	 * @deprecated since 7.7.0
730
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
731
	 *
732
	 * @param Array                 $request_params Incoming request parameters.
733
	 * @param Boolean               $is_active      Whether the connection is currently active.
734
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
735
	 * @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...
736
	 */
737
	public function setup_xmlrpc_handlers(
738
		$request_params,
739
		$is_active,
740
		$is_signed,
741
		Jetpack_XMLRPC_Server $xmlrpc_server = null
742
	) {
743
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
744
		return $this->connection_manager->setup_xmlrpc_handlers(
745
			$request_params,
746
			$is_active,
747
			$is_signed,
748
			$xmlrpc_server
749
		);
750
	}
751
752
	/**
753
	 * Initialize REST API registration connector.
754
	 *
755
	 * @deprecated since 7.7.0
756
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
757
	 */
758
	public function initialize_rest_api_registration_connector() {
759
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
760
		$this->connection_manager->initialize_rest_api_registration_connector();
761
	}
762
763
	/**
764
	 * This is ported over from the manage module, which has been deprecated and baked in here.
765
	 *
766
	 * @param $domains
767
	 */
768
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
769
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
770
	}
771
772
	/**
773
	 * Return $domains, with 'wordpress.com' appended.
774
	 * This is ported over from the manage module, which has been deprecated and baked in here.
775
	 *
776
	 * @param $domains
777
	 * @return array
778
	 */
779
	function allow_wpcom_domain( $domains ) {
780
		if ( empty( $domains ) ) {
781
			$domains = array();
782
		}
783
		$domains[] = 'wordpress.com';
784
		return array_unique( $domains );
785
	}
786
787
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
788
		$post = get_post( $post_id );
789
790
		if ( empty( $post ) ) {
791
			return $default_url;
792
		}
793
794
		$post_type = $post->post_type;
795
796
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
797
		// https://en.support.wordpress.com/custom-post-types/
798
		$allowed_post_types = array(
799
			'post' => 'post',
800
			'page' => 'page',
801
			'jetpack-portfolio' => 'edit/jetpack-portfolio',
802
			'jetpack-testimonial' => 'edit/jetpack-testimonial',
803
		);
804
805
		if ( ! in_array( $post_type, array_keys( $allowed_post_types ) ) ) {
806
			return $default_url;
807
		}
808
809
		$path_prefix = $allowed_post_types[ $post_type ];
810
811
		$site_slug  = Jetpack::build_raw_urls( get_home_url() );
812
813
		return esc_url( sprintf( 'https://wordpress.com/%s/%s/%d', $path_prefix, $site_slug, $post_id ) );
814
	}
815
816
	function point_edit_comment_links_to_calypso( $url ) {
817
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
818
		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...
819
		return esc_url( sprintf( 'https://wordpress.com/comment/%s/%d',
820
			Jetpack::build_raw_urls( get_home_url() ),
821
			$query_args['amp;c']
822
		) );
823
	}
824
825
	function jetpack_track_last_sync_callback( $params ) {
826
		/**
827
		 * Filter to turn off jitm caching
828
		 *
829
		 * @since 5.4.0
830
		 *
831
		 * @param bool false Whether to cache just in time messages
832
		 */
833
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
834
			return $params;
835
		}
836
837
		if ( is_array( $params ) && isset( $params[0] ) ) {
838
			$option = $params[0];
839
			if ( 'active_plugins' === $option ) {
840
				// use the cache if we can, but not terribly important if it gets evicted
841
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
842
			}
843
		}
844
845
		return $params;
846
	}
847
848
	function jetpack_connection_banner_callback() {
849
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
850
851
		if ( isset( $_REQUEST['dismissBanner'] ) ) {
852
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
853
			wp_send_json_success();
854
		}
855
856
		wp_die();
857
	}
858
859
	/**
860
	 * Removes all XML-RPC methods that are not `jetpack.*`.
861
	 * Only used in our alternate XML-RPC endpoint, where we want to
862
	 * ensure that Core and other plugins' methods are not exposed.
863
	 *
864
	 * @deprecated since 7.7.0
865
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
866
	 *
867
	 * @param array $methods A list of registered WordPress XMLRPC methods.
868
	 * @return array Filtered $methods
869
	 */
870
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
871
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
872
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
873
	}
874
875
	/**
876
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
877
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
878
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
879
	 * which is accessible via a different URI. Most of the below is copied directly
880
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
881
	 *
882
	 * @deprecated since 7.7.0
883
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
884
	 */
885
	public function alternate_xmlrpc() {
886
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
887
		$this->connection_manager->alternate_xmlrpc();
888
	}
889
890
	/**
891
	 * The callback for the JITM ajax requests.
892
	 */
893
	function jetpack_jitm_ajax_callback() {
894
		// Check for nonce
895
		if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
896
			wp_die( 'Module activation failed due to lack of appropriate permissions' );
897
		}
898
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
899
			$module_slug = $_REQUEST['jitmModule'];
900
			Jetpack::log( 'activate', $module_slug );
901
			Jetpack::activate_module( $module_slug, false, false );
902
			Jetpack::state( 'message', 'no_message' );
903
904
			//A Jetpack module is being activated through a JITM, track it
905
			$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
906
			$this->do_stats( 'server_side' );
907
908
			wp_send_json_success();
909
		}
910
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
911
			// get the hide_jitm options array
912
			$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
913
			$module_slug = $_REQUEST['jitmModule'];
914
915
			if( ! $jetpack_hide_jitm ) {
916
				$jetpack_hide_jitm = array(
917
					$module_slug => 'hide'
918
				);
919
			} else {
920
				$jetpack_hide_jitm[$module_slug] = 'hide';
921
			}
922
923
			Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
924
925
			//jitm is being dismissed forever, track it
926
			$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
927
			$this->do_stats( 'server_side' );
928
929
			wp_send_json_success();
930
		}
931 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
932
			$module_slug = $_REQUEST['jitmModule'];
933
934
			// User went to WordPress.com, track this
935
			$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
936
			$this->do_stats( 'server_side' );
937
938
			wp_send_json_success();
939
		}
940 View Code Duplication
		if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
941
			$track = $_REQUEST['jitmModule'];
942
943
			// User is viewing JITM, track it.
944
			$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
945
			$this->do_stats( 'server_side' );
946
947
			wp_send_json_success();
948
		}
949
	}
950
951
	/**
952
	 * If there are any stats that need to be pushed, but haven't been, push them now.
953
	 */
954
	function push_stats() {
955
		if ( ! empty( $this->stats ) ) {
956
			$this->do_stats( 'server_side' );
957
		}
958
	}
959
960
	function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
961
		switch( $cap ) {
962
			case 'jetpack_connect' :
963
			case 'jetpack_reconnect' :
964
				if ( Jetpack::is_development_mode() ) {
965
					$caps = array( 'do_not_allow' );
966
					break;
967
				}
968
				/**
969
				 * Pass through. If it's not development mode, these should match disconnect.
970
				 * Let users disconnect if it's development mode, just in case things glitch.
971
				 */
972
			case 'jetpack_disconnect' :
973
				/**
974
				 * In multisite, can individual site admins manage their own connection?
975
				 *
976
				 * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
977
				 */
978
				if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
979
					if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
980
						/**
981
						 * We need to update the option name -- it's terribly unclear which
982
						 * direction the override goes.
983
						 *
984
						 * @todo: Update the option name to `sub-sites-can-manage-own-connections`
985
						 */
986
						$caps = array( 'do_not_allow' );
987
						break;
988
					}
989
				}
990
991
				$caps = array( 'manage_options' );
992
				break;
993
			case 'jetpack_manage_modules' :
994
			case 'jetpack_activate_modules' :
995
			case 'jetpack_deactivate_modules' :
996
				$caps = array( 'manage_options' );
997
				break;
998
			case 'jetpack_configure_modules' :
999
				$caps = array( 'manage_options' );
1000
				break;
1001
			case 'jetpack_manage_autoupdates' :
1002
				$caps = array(
1003
					'manage_options',
1004
					'update_plugins',
1005
				);
1006
				break;
1007
			case 'jetpack_network_admin_page':
1008
			case 'jetpack_network_settings_page':
1009
				$caps = array( 'manage_network_plugins' );
1010
				break;
1011
			case 'jetpack_network_sites_page':
1012
				$caps = array( 'manage_sites' );
1013
				break;
1014
			case 'jetpack_admin_page' :
1015
				if ( Jetpack::is_development_mode() ) {
1016
					$caps = array( 'manage_options' );
1017
					break;
1018
				} else {
1019
					$caps = array( 'read' );
1020
				}
1021
				break;
1022
			case 'jetpack_connect_user' :
1023
				if ( Jetpack::is_development_mode() ) {
1024
					$caps = array( 'do_not_allow' );
1025
					break;
1026
				}
1027
				$caps = array( 'read' );
1028
				break;
1029
		}
1030
		return $caps;
1031
	}
1032
1033
	/**
1034
	 * Require a Jetpack authentication.
1035
	 *
1036
	 * @deprecated since 7.7.0
1037
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1038
	 */
1039
	public function require_jetpack_authentication() {
1040
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1041
		$this->connection_manager->require_jetpack_authentication();
1042
	}
1043
1044
	/**
1045
	 * Load language files
1046
	 * @action plugins_loaded
1047
	 */
1048
	public static function plugin_textdomain() {
1049
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1050
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1051
	}
1052
1053
	/**
1054
	 * Register assets for use in various modules and the Jetpack admin page.
1055
	 *
1056
	 * @uses wp_script_is, wp_register_script, plugins_url
1057
	 * @action wp_loaded
1058
	 * @return null
1059
	 */
1060
	public function register_assets() {
1061
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1062
			wp_register_script(
1063
				'spin',
1064
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1065
				false,
1066
				'1.3'
1067
			);
1068
		}
1069
1070 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1071
			wp_register_script(
1072
				'jquery.spin',
1073
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1074
				array( 'jquery', 'spin' ),
1075
				'1.3'
1076
			);
1077
		}
1078
1079 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1080
			wp_register_script(
1081
				'jetpack-gallery-settings',
1082
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1083
				array( 'media-views' ),
1084
				'20121225'
1085
			);
1086
		}
1087
1088 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1089
			wp_register_script(
1090
				'jetpack-twitter-timeline',
1091
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1092
				array( 'jquery' ),
1093
				'4.0.0',
1094
				true
1095
			);
1096
		}
1097
1098
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1099
			wp_register_script(
1100
				'jetpack-facebook-embed',
1101
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1102
				array( 'jquery' ),
1103
				null,
1104
				true
1105
			);
1106
1107
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1108
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1109
			if ( ! is_numeric( $fb_app_id ) ) {
1110
				$fb_app_id = '';
1111
			}
1112
			wp_localize_script(
1113
				'jetpack-facebook-embed',
1114
				'jpfbembed',
1115
				array(
1116
					'appid' => $fb_app_id,
1117
					'locale' => $this->get_locale(),
1118
				)
1119
			);
1120
		}
1121
1122
		/**
1123
		 * As jetpack_register_genericons is by default fired off a hook,
1124
		 * the hook may have already fired by this point.
1125
		 * So, let's just trigger it manually.
1126
		 */
1127
		require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
1128
		jetpack_register_genericons();
1129
1130
		/**
1131
		 * Register the social logos
1132
		 */
1133
		require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
1134
		jetpack_register_social_logos();
1135
1136 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
1137
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1138
	}
1139
1140
	/**
1141
	 * Guess locale from language code.
1142
	 *
1143
	 * @param string $lang Language code.
1144
	 * @return string|bool
1145
	 */
1146 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1147
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1148
			return 'en_US';
1149
		}
1150
1151
		if ( ! class_exists( 'GP_Locales' ) ) {
1152
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1153
				return false;
1154
			}
1155
1156
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1157
		}
1158
1159
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1160
			// WP.com: get_locale() returns 'it'
1161
			$locale = GP_Locales::by_slug( $lang );
1162
		} else {
1163
			// Jetpack: get_locale() returns 'it_IT';
1164
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1165
		}
1166
1167
		if ( ! $locale ) {
1168
			return false;
1169
		}
1170
1171
		if ( empty( $locale->facebook_locale ) ) {
1172
			if ( empty( $locale->wp_locale ) ) {
1173
				return false;
1174
			} else {
1175
				// Facebook SDK is smart enough to fall back to en_US if a
1176
				// locale isn't supported. Since supported Facebook locales
1177
				// can fall out of sync, we'll attempt to use the known
1178
				// wp_locale value and rely on said fallback.
1179
				return $locale->wp_locale;
1180
			}
1181
		}
1182
1183
		return $locale->facebook_locale;
1184
	}
1185
1186
	/**
1187
	 * Get the locale.
1188
	 *
1189
	 * @return string|bool
1190
	 */
1191
	function get_locale() {
1192
		$locale = $this->guess_locale_from_lang( get_locale() );
1193
1194
		if ( ! $locale ) {
1195
			$locale = 'en_US';
1196
		}
1197
1198
		return $locale;
1199
	}
1200
1201
	/**
1202
	 * Device Pixels support
1203
	 * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
1204
	 */
1205
	function devicepx() {
1206
		if ( Jetpack::is_active() && ! Jetpack_AMP_Support::is_amp_request() ) {
1207
			wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
1208
		}
1209
	}
1210
1211
	function deactivate_dialog() {
1212
		if ( Jetpack::is_active() ) {
1213
			add_thickbox();
1214
			wp_enqueue_script(
1215
				'jetpack-deactivate-dialog-js',
1216
				Assets::get_file_url_for_environment(
1217
					'_inc/build/jetpack-deactivate-dialog.min.js',
1218
					'_inc/jetpack-deactivate-dialog.js'
1219
				),
1220
				array( 'jquery' ),
1221
				JETPACK__VERSION,
1222
				true
1223
			);
1224
			wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
1225
1226
		}
1227
	}
1228
1229
	/**
1230
	 * Return the network_site_url so that .com knows what network this site is a part of.
1231
	 * @param  bool $option
1232
	 * @return string
1233
	 */
1234
	public function jetpack_main_network_site_option( $option ) {
1235
		return network_site_url();
1236
	}
1237
	/**
1238
	 * Network Name.
1239
	 */
1240
	static function network_name( $option = null ) {
1241
		global $current_site;
1242
		return $current_site->site_name;
1243
	}
1244
	/**
1245
	 * Does the network allow new user and site registrations.
1246
	 * @return string
1247
	 */
1248
	static function network_allow_new_registrations( $option = null ) {
1249
		return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
1250
	}
1251
	/**
1252
	 * Does the network allow admins to add new users.
1253
	 * @return boolian
1254
	 */
1255
	static function network_add_new_users( $option = null ) {
1256
		return (bool) get_site_option( 'add_new_users' );
1257
	}
1258
	/**
1259
	 * File upload psace left per site in MB.
1260
	 *  -1 means NO LIMIT.
1261
	 * @return number
1262
	 */
1263
	static function network_site_upload_space( $option = null ) {
1264
		// value in MB
1265
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1266
	}
1267
1268
	/**
1269
	 * Network allowed file types.
1270
	 * @return string
1271
	 */
1272
	static function network_upload_file_types( $option = null ) {
1273
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1274
	}
1275
1276
	/**
1277
	 * Maximum file upload size set by the network.
1278
	 * @return number
1279
	 */
1280
	static function network_max_upload_file_size( $option = null ) {
1281
		// value in KB
1282
		return get_site_option( 'fileupload_maxk', 300 );
1283
	}
1284
1285
	/**
1286
	 * Lets us know if a site allows admins to manage the network.
1287
	 * @return array
1288
	 */
1289
	static function network_enable_administration_menus( $option = null ) {
1290
		return get_site_option( 'menu_items' );
1291
	}
1292
1293
	/**
1294
	 * If a user has been promoted to or demoted from admin, we need to clear the
1295
	 * jetpack_other_linked_admins transient.
1296
	 *
1297
	 * @since 4.3.2
1298
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1299
	 *
1300
	 * @param int    $user_id   The user ID whose role changed.
1301
	 * @param string $role      The new role.
1302
	 * @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...
1303
	 */
1304
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1305
		if ( 'administrator' == $role
1306
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1307
			|| is_null( $old_roles )
1308
		) {
1309
			delete_transient( 'jetpack_other_linked_admins' );
1310
		}
1311
	}
1312
1313
	/**
1314
	 * Checks to see if there are any other users available to become primary
1315
	 * Users must both:
1316
	 * - Be linked to wpcom
1317
	 * - Be an admin
1318
	 *
1319
	 * @return mixed False if no other users are linked, Int if there are.
1320
	 */
1321
	static function get_other_linked_admins() {
1322
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1323
1324
		if ( false === $other_linked_users ) {
1325
			$admins = get_users( array( 'role' => 'administrator' ) );
1326
			if ( count( $admins ) > 1 ) {
1327
				$available = array();
1328
				foreach ( $admins as $admin ) {
1329
					if ( Jetpack::is_user_connected( $admin->ID ) ) {
1330
						$available[] = $admin->ID;
1331
					}
1332
				}
1333
1334
				$count_connected_admins = count( $available );
1335
				if ( count( $available ) > 1 ) {
1336
					$other_linked_users = $count_connected_admins;
1337
				} else {
1338
					$other_linked_users = 0;
1339
				}
1340
			} else {
1341
				$other_linked_users = 0;
1342
			}
1343
1344
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1345
		}
1346
1347
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1348
	}
1349
1350
	/**
1351
	 * Return whether we are dealing with a multi network setup or not.
1352
	 * The reason we are type casting this is because we want to avoid the situation where
1353
	 * the result is false since when is_main_network_option return false it cases
1354
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1355
	 * database which could be set to anything as opposed to what this function returns.
1356
	 * @param  bool  $option
1357
	 *
1358
	 * @return boolean
1359
	 */
1360
	public function is_main_network_option( $option ) {
1361
		// return '1' or ''
1362
		return (string) (bool) Jetpack::is_multi_network();
1363
	}
1364
1365
	/**
1366
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1367
	 *
1368
	 * @param  string  $option
1369
	 * @return boolean
1370
	 */
1371
	public function is_multisite( $option ) {
1372
		return (string) (bool) is_multisite();
1373
	}
1374
1375
	/**
1376
	 * Implemented since there is no core is multi network function
1377
	 * Right now there is no way to tell if we which network is the dominant network on the system
1378
	 *
1379
	 * @since  3.3
1380
	 * @return boolean
1381
	 */
1382 View Code Duplication
	public static function is_multi_network() {
1383
		global  $wpdb;
1384
1385
		// if we don't have a multi site setup no need to do any more
1386
		if ( ! is_multisite() ) {
1387
			return false;
1388
		}
1389
1390
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1391
		if ( $num_sites > 1 ) {
1392
			return true;
1393
		} else {
1394
			return false;
1395
		}
1396
	}
1397
1398
	/**
1399
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1400
	 * @return null
1401
	 */
1402
	function update_jetpack_main_network_site_option() {
1403
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1404
	}
1405
	/**
1406
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1407
	 *
1408
	 */
1409
	function update_jetpack_network_settings() {
1410
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1411
		// Only sync this info for the main network site.
1412
	}
1413
1414
	/**
1415
	 * Get back if the current site is single user site.
1416
	 *
1417
	 * @return bool
1418
	 */
1419 View Code Duplication
	public static function is_single_user_site() {
1420
		global $wpdb;
1421
1422
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1423
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1424
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1425
		}
1426
		return 1 === (int) $some_users;
1427
	}
1428
1429
	/**
1430
	 * Returns true if the site has file write access false otherwise.
1431
	 * @return string ( '1' | '0' )
1432
	 **/
1433
	public static function file_system_write_access() {
1434
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1435
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
1436
		}
1437
1438
		require_once( ABSPATH . 'wp-admin/includes/template.php' );
1439
1440
		$filesystem_method = get_filesystem_method();
1441
		if ( $filesystem_method === 'direct' ) {
1442
			return 1;
1443
		}
1444
1445
		ob_start();
1446
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1447
		ob_end_clean();
1448
		if ( $filesystem_credentials_are_stored ) {
1449
			return 1;
1450
		}
1451
		return 0;
1452
	}
1453
1454
	/**
1455
	 * Finds out if a site is using a version control system.
1456
	 * @return string ( '1' | '0' )
1457
	 **/
1458
	public static function is_version_controlled() {
1459
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1460
		return (string) (int) Functions::is_version_controlled();
1461
	}
1462
1463
	/**
1464
	 * Determines whether the current theme supports featured images or not.
1465
	 * @return string ( '1' | '0' )
1466
	 */
1467
	public static function featured_images_enabled() {
1468
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1469
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1470
	}
1471
1472
	/**
1473
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1474
	 *
1475
	 * @deprecated 4.7 use get_avatar_url instead.
1476
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1477
	 * @param int $size Size of the avatar image
1478
	 * @param string $default URL to a default image to use if no avatar is available
1479
	 * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
1480
	 *
1481
	 * @return array
1482
	 */
1483
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1484
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1485
		return get_avatar_url( $id_or_email, array(
1486
			'size' => $size,
1487
			'default' => $default,
1488
			'force_default' => $force_display,
1489
		) );
1490
	}
1491
1492
	/**
1493
	 * jetpack_updates is saved in the following schema:
1494
	 *
1495
	 * array (
1496
	 *      'plugins'                       => (int) Number of plugin updates available.
1497
	 *      'themes'                        => (int) Number of theme updates available.
1498
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1499
	 *      'translations'                  => (int) Number of translation updates available.
1500
	 *      'total'                         => (int) Total of all available updates.
1501
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1502
	 * )
1503
	 * @return array
1504
	 */
1505
	public static function get_updates() {
1506
		$update_data = wp_get_update_data();
1507
1508
		// Stores the individual update counts as well as the total count.
1509
		if ( isset( $update_data['counts'] ) ) {
1510
			$updates = $update_data['counts'];
1511
		}
1512
1513
		// If we need to update WordPress core, let's find the latest version number.
1514 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1515
			$cur = get_preferred_from_update_core();
1516
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1517
				$updates['wp_update_version'] = $cur->current;
1518
			}
1519
		}
1520
		return isset( $updates ) ? $updates : array();
1521
	}
1522
1523
	public static function get_update_details() {
1524
		$update_details = array(
1525
			'update_core' => get_site_transient( 'update_core' ),
1526
			'update_plugins' => get_site_transient( 'update_plugins' ),
1527
			'update_themes' => get_site_transient( 'update_themes' ),
1528
		);
1529
		return $update_details;
1530
	}
1531
1532
	public static function refresh_update_data() {
1533
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1534
1535
	}
1536
1537
	public static function refresh_theme_data() {
1538
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1539
	}
1540
1541
	/**
1542
	 * Is Jetpack active?
1543
	 */
1544
	public static function is_active() {
1545
		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...
1546
	}
1547
1548
	/**
1549
	 * Make an API call to WordPress.com for plan status
1550
	 *
1551
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1552
	 *
1553
	 * @return bool True if plan is updated, false if no update
1554
	 */
1555
	public static function refresh_active_plan_from_wpcom() {
1556
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1557
		return Jetpack_Plan::refresh_from_wpcom();
1558
	}
1559
1560
	/**
1561
	 * Get the plan that this Jetpack site is currently using
1562
	 *
1563
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1564
	 * @return array Active Jetpack plan details.
1565
	 */
1566
	public static function get_active_plan() {
1567
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1568
		return Jetpack_Plan::get();
1569
	}
1570
1571
	/**
1572
	 * Determine whether the active plan supports a particular feature
1573
	 *
1574
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1575
	 * @return bool True if plan supports feature, false if not.
1576
	 */
1577
	public static function active_plan_supports( $feature ) {
1578
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1579
		return Jetpack_Plan::supports( $feature );
1580
	}
1581
1582
	/**
1583
	 * Is Jetpack in development (offline) mode?
1584
	 */
1585 View Code Duplication
	public static function is_development_mode() {
1586
		$development_mode = false;
1587
1588
		if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
1589
			$development_mode = JETPACK_DEV_DEBUG;
1590
		} elseif ( $site_url = site_url() ) {
1591
			$development_mode = false === strpos( $site_url, '.' );
1592
		}
1593
1594
		/**
1595
		 * Filters Jetpack's development mode.
1596
		 *
1597
		 * @see https://jetpack.com/support/development-mode/
1598
		 *
1599
		 * @since 2.2.1
1600
		 *
1601
		 * @param bool $development_mode Is Jetpack's development mode active.
1602
		 */
1603
		$development_mode = ( bool ) apply_filters( 'jetpack_development_mode', $development_mode );
1604
		return $development_mode;
1605
	}
1606
1607
	/**
1608
	 * Whether the site is currently onboarding or not.
1609
	 * A site is considered as being onboarded if it currently has an onboarding token.
1610
	 *
1611
	 * @since 5.8
1612
	 *
1613
	 * @access public
1614
	 * @static
1615
	 *
1616
	 * @return bool True if the site is currently onboarding, false otherwise
1617
	 */
1618
	public static function is_onboarding() {
1619
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1620
	}
1621
1622
	/**
1623
	 * Determines reason for Jetpack development mode.
1624
	 */
1625
	public static function development_mode_trigger_text() {
1626
		if ( ! Jetpack::is_development_mode() ) {
1627
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1628
		}
1629
1630
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1631
			$notice =  __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1632
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1633
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1634
		} else {
1635
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1636
		}
1637
1638
		return $notice;
1639
1640
	}
1641
	/**
1642
	* Get Jetpack development mode notice text and notice class.
1643
	*
1644
	* Mirrors the checks made in Jetpack::is_development_mode
1645
	*
1646
	*/
1647
	public static function show_development_mode_notice() {
1648 View Code Duplication
		if ( Jetpack::is_development_mode() ) {
1649
			$notice = sprintf(
1650
			/* translators: %s is a URL */
1651
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1652
				'https://jetpack.com/support/development-mode/'
1653
			);
1654
1655
			$notice .= ' ' . Jetpack::development_mode_trigger_text();
1656
1657
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1658
		}
1659
1660
		// Throw up a notice if using a development version and as for feedback.
1661
		if ( Jetpack::is_development_version() ) {
1662
			/* translators: %s is a URL */
1663
			$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/' );
1664
1665
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1666
		}
1667
		// Throw up a notice if using staging mode
1668
		if ( Jetpack::is_staging_site() ) {
1669
			/* translators: %s is a URL */
1670
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
1671
1672
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1673
		}
1674
	}
1675
1676
	/**
1677
	 * Whether Jetpack's version maps to a public release, or a development version.
1678
	 */
1679
	public static function is_development_version() {
1680
		/**
1681
		 * Allows filtering whether this is a development version of Jetpack.
1682
		 *
1683
		 * This filter is especially useful for tests.
1684
		 *
1685
		 * @since 4.3.0
1686
		 *
1687
		 * @param bool $development_version Is this a develoment version of Jetpack?
1688
		 */
1689
		return (bool) apply_filters(
1690
			'jetpack_development_version',
1691
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1692
		);
1693
	}
1694
1695
	/**
1696
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1697
	 */
1698
	public static function is_user_connected( $user_id = false ) {
1699
		return self::connection()->is_user_connected( $user_id );
1700
	}
1701
1702
	/**
1703
	 * Get the wpcom user data of the current|specified connected user.
1704
	 */
1705 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1706
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1707
		if ( ! $user_id ) {
1708
			$user_id = get_current_user_id();
1709
		}
1710
1711
		$transient_key = "jetpack_connected_user_data_$user_id";
1712
1713
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1714
			return $cached_user_data;
1715
		}
1716
1717
		$xml = new Jetpack_IXR_Client( array(
1718
			'user_id' => $user_id,
1719
		) );
1720
		$xml->query( 'wpcom.getUser' );
1721
		if ( ! $xml->isError() ) {
1722
			$user_data = $xml->getResponse();
1723
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1724
			return $user_data;
1725
		}
1726
1727
		return false;
1728
	}
1729
1730
	/**
1731
	 * Get the wpcom email of the current|specified connected user.
1732
	 */
1733 View Code Duplication
	public static function get_connected_user_email( $user_id = null ) {
1734
		if ( ! $user_id ) {
1735
			$user_id = get_current_user_id();
1736
		}
1737
1738
		$xml = new Jetpack_IXR_Client( array(
1739
			'user_id' => $user_id,
1740
		) );
1741
		$xml->query( 'wpcom.getUserEmail' );
1742
		if ( ! $xml->isError() ) {
1743
			return $xml->getResponse();
1744
		}
1745
		return false;
1746
	}
1747
1748
	/**
1749
	 * Get the wpcom email of the master user.
1750
	 */
1751
	public static function get_master_user_email() {
1752
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1753
		if ( $master_user_id ) {
1754
			return self::get_connected_user_email( $master_user_id );
1755
		}
1756
		return '';
1757
	}
1758
1759
	/**
1760
	 * Whether the current user is the connection owner.
1761
	 *
1762
	 * @deprecated since 7.7
1763
	 *
1764
	 * @return bool Whether the current user is the connection owner.
1765
	 */
1766
	public function current_user_is_connection_owner() {
1767
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1768
		return self::connection()->is_connection_owner();
1769
	}
1770
1771
	/**
1772
	 * Gets current user IP address.
1773
	 *
1774
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1775
	 *
1776
	 * @return string                  Current user IP address.
1777
	 */
1778
	public static function current_user_ip( $check_all_headers = false ) {
1779
		if ( $check_all_headers ) {
1780
			foreach ( array(
1781
				'HTTP_CF_CONNECTING_IP',
1782
				'HTTP_CLIENT_IP',
1783
				'HTTP_X_FORWARDED_FOR',
1784
				'HTTP_X_FORWARDED',
1785
				'HTTP_X_CLUSTER_CLIENT_IP',
1786
				'HTTP_FORWARDED_FOR',
1787
				'HTTP_FORWARDED',
1788
				'HTTP_VIA',
1789
			) as $key ) {
1790
				if ( ! empty( $_SERVER[ $key ] ) ) {
1791
					return $_SERVER[ $key ];
1792
				}
1793
			}
1794
		}
1795
1796
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1797
	}
1798
1799
	/**
1800
	 * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
1801
	 */
1802
	function extra_oembed_providers() {
1803
		// Cloudup: https://dev.cloudup.com/#oembed
1804
		wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
1805
		wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
1806
		wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
1807
		wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
1808
		wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
1809
		wp_oembed_add_provider( '#https?://(www\.)?icloud\.com/keynote/.*#i', 'https://iwmb.icloud.com/iwmb/oembed', true );
1810
		wp_oembed_add_provider( 'https://song.link/*', 'https://song.link/oembed', false );
1811
	}
1812
1813
	/**
1814
	 * Synchronize connected user role changes
1815
	 */
1816
	function user_role_change( $user_id ) {
1817
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1818
		Users::user_role_change( $user_id );
1819
	}
1820
1821
	/**
1822
	 * Loads the currently active modules.
1823
	 */
1824
	public static function load_modules() {
1825
		if (
1826
			! self::is_active()
1827
			&& ! self::is_development_mode()
1828
			&& ! self::is_onboarding()
1829
			&& (
1830
				! is_multisite()
1831
				|| ! get_site_option( 'jetpack_protect_active' )
1832
			)
1833
		) {
1834
			return;
1835
		}
1836
1837
		$version = Jetpack_Options::get_option( 'version' );
1838 View Code Duplication
		if ( ! $version ) {
1839
			$version = $old_version = JETPACK__VERSION . ':' . time();
1840
			/** This action is documented in class.jetpack.php */
1841
			do_action( 'updating_jetpack_version', $version, false );
1842
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1843
		}
1844
		list( $version ) = explode( ':', $version );
1845
1846
		$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1847
1848
		$modules_data = array();
1849
1850
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1851
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1852
			$updated_modules = array();
1853
			foreach ( $modules as $module ) {
1854
				$modules_data[ $module ] = Jetpack::get_module( $module );
1855
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1856
					continue;
1857
				}
1858
1859
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1860
					continue;
1861
				}
1862
1863
				$updated_modules[] = $module;
1864
			}
1865
1866
			$modules = array_diff( $modules, $updated_modules );
1867
		}
1868
1869
		$is_development_mode = Jetpack::is_development_mode();
1870
1871
		foreach ( $modules as $index => $module ) {
1872
			// If we're in dev mode, disable modules requiring a connection
1873
			if ( $is_development_mode ) {
1874
				// Prime the pump if we need to
1875
				if ( empty( $modules_data[ $module ] ) ) {
1876
					$modules_data[ $module ] = Jetpack::get_module( $module );
1877
				}
1878
				// If the module requires a connection, but we're in local mode, don't include it.
1879
				if ( $modules_data[ $module ]['requires_connection'] ) {
1880
					continue;
1881
				}
1882
			}
1883
1884
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1885
				continue;
1886
			}
1887
1888
			if ( ! include_once( Jetpack::get_module_path( $module ) ) ) {
1889
				unset( $modules[ $index ] );
1890
				self::update_active_modules( array_values( $modules ) );
1891
				continue;
1892
			}
1893
1894
			/**
1895
			 * Fires when a specific module is loaded.
1896
			 * The dynamic part of the hook, $module, is the module slug.
1897
			 *
1898
			 * @since 1.1.0
1899
			 */
1900
			do_action( 'jetpack_module_loaded_' . $module );
1901
		}
1902
1903
		/**
1904
		 * Fires when all the modules are loaded.
1905
		 *
1906
		 * @since 1.1.0
1907
		 */
1908
		do_action( 'jetpack_modules_loaded' );
1909
1910
		// 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.
1911
		require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
1912
	}
1913
1914
	/**
1915
	 * Check if Jetpack's REST API compat file should be included
1916
	 * @action plugins_loaded
1917
	 * @return null
1918
	 */
1919
	public function check_rest_api_compat() {
1920
		/**
1921
		 * Filters the list of REST API compat files to be included.
1922
		 *
1923
		 * @since 2.2.5
1924
		 *
1925
		 * @param array $args Array of REST API compat files to include.
1926
		 */
1927
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1928
1929
		if ( function_exists( 'bbpress' ) )
1930
			$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
1931
1932
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
1933
			require_once $_jetpack_rest_api_compat_include;
1934
	}
1935
1936
	/**
1937
	 * Gets all plugins currently active in values, regardless of whether they're
1938
	 * traditionally activated or network activated.
1939
	 *
1940
	 * @todo Store the result in core's object cache maybe?
1941
	 */
1942
	public static function get_active_plugins() {
1943
		$active_plugins = (array) get_option( 'active_plugins', array() );
1944
1945
		if ( is_multisite() ) {
1946
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
1947
			// whereas active_plugins stores them in the values.
1948
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
1949
			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...
1950
				$active_plugins = array_merge( $active_plugins, $network_plugins );
1951
			}
1952
		}
1953
1954
		sort( $active_plugins );
1955
1956
		return array_unique( $active_plugins );
1957
	}
1958
1959
	/**
1960
	 * Gets and parses additional plugin data to send with the heartbeat data
1961
	 *
1962
	 * @since 3.8.1
1963
	 *
1964
	 * @return array Array of plugin data
1965
	 */
1966
	public static function get_parsed_plugin_data() {
1967
		if ( ! function_exists( 'get_plugins' ) ) {
1968
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
1969
		}
1970
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
1971
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
1972
		$active_plugins = Jetpack::get_active_plugins();
1973
1974
		$plugins = array();
1975
		foreach ( $all_plugins as $path => $plugin_data ) {
1976
			$plugins[ $path ] = array(
1977
					'is_active' => in_array( $path, $active_plugins ),
1978
					'file'      => $path,
1979
					'name'      => $plugin_data['Name'],
1980
					'version'   => $plugin_data['Version'],
1981
					'author'    => $plugin_data['Author'],
1982
			);
1983
		}
1984
1985
		return $plugins;
1986
	}
1987
1988
	/**
1989
	 * Gets and parses theme data to send with the heartbeat data
1990
	 *
1991
	 * @since 3.8.1
1992
	 *
1993
	 * @return array Array of theme data
1994
	 */
1995
	public static function get_parsed_theme_data() {
1996
		$all_themes = wp_get_themes( array( 'allowed' => true ) );
1997
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
1998
1999
		$themes = array();
2000
		foreach ( $all_themes as $slug => $theme_data ) {
2001
			$theme_headers = array();
2002
			foreach ( $header_keys as $header_key ) {
2003
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2004
			}
2005
2006
			$themes[ $slug ] = array(
2007
					'is_active_theme' => $slug == wp_get_theme()->get_template(),
2008
					'slug' => $slug,
2009
					'theme_root' => $theme_data->get_theme_root_uri(),
2010
					'parent' => $theme_data->parent(),
2011
					'headers' => $theme_headers
2012
			);
2013
		}
2014
2015
		return $themes;
2016
	}
2017
2018
	/**
2019
	 * Checks whether a specific plugin is active.
2020
	 *
2021
	 * We don't want to store these in a static variable, in case
2022
	 * there are switch_to_blog() calls involved.
2023
	 */
2024
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2025
		return in_array( $plugin, self::get_active_plugins() );
2026
	}
2027
2028
	/**
2029
	 * Check if Jetpack's Open Graph tags should be used.
2030
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2031
	 *
2032
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2033
	 * @action plugins_loaded
2034
	 * @return null
2035
	 */
2036
	public function check_open_graph() {
2037
		if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
2038
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2039
		}
2040
2041
		$active_plugins = self::get_active_plugins();
2042
2043
		if ( ! empty( $active_plugins ) ) {
2044
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2045
				if ( in_array( $plugin, $active_plugins ) ) {
2046
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2047
					break;
2048
				}
2049
			}
2050
		}
2051
2052
		/**
2053
		 * Allow the addition of Open Graph Meta Tags to all pages.
2054
		 *
2055
		 * @since 2.0.3
2056
		 *
2057
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2058
		 */
2059
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2060
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2061
		}
2062
	}
2063
2064
	/**
2065
	 * Check if Jetpack's Twitter tags should be used.
2066
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2067
	 *
2068
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2069
	 * @action plugins_loaded
2070
	 * @return null
2071
	 */
2072
	public function check_twitter_tags() {
2073
2074
		$active_plugins = self::get_active_plugins();
2075
2076
		if ( ! empty( $active_plugins ) ) {
2077
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2078
				if ( in_array( $plugin, $active_plugins ) ) {
2079
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2080
					break;
2081
				}
2082
			}
2083
		}
2084
2085
		/**
2086
		 * Allow Twitter Card Meta tags to be disabled.
2087
		 *
2088
		 * @since 2.6.0
2089
		 *
2090
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2091
		 */
2092
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2093
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2094
		}
2095
	}
2096
2097
	/**
2098
	 * Allows plugins to submit security reports.
2099
 	 *
2100
	 * @param string  $type         Report type (login_form, backup, file_scanning, spam)
2101
	 * @param string  $plugin_file  Plugin __FILE__, so that we can pull plugin data
2102
	 * @param array   $args         See definitions above
2103
	 */
2104
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2105
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2106
	}
2107
2108
/* Jetpack Options API */
2109
2110
	public static function get_option_names( $type = 'compact' ) {
2111
		return Jetpack_Options::get_option_names( $type );
2112
	}
2113
2114
	/**
2115
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2116
 	 *
2117
	 * @param string $name    Option name
2118
	 * @param mixed  $default (optional)
2119
	 */
2120
	public static function get_option( $name, $default = false ) {
2121
		return Jetpack_Options::get_option( $name, $default );
2122
	}
2123
2124
	/**
2125
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2126
 	 *
2127
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2128
	 * @param string $name  Option name
2129
	 * @param mixed  $value Option value
2130
	 */
2131
	public static function update_option( $name, $value ) {
2132
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2133
		return Jetpack_Options::update_option( $name, $value );
2134
	}
2135
2136
	/**
2137
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2138
 	 *
2139
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2140
	 * @param array $array array( option name => option value, ... )
2141
	 */
2142
	public static function update_options( $array ) {
2143
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2144
		return Jetpack_Options::update_options( $array );
2145
	}
2146
2147
	/**
2148
	 * Deletes the given option.  May be passed multiple option names as an array.
2149
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2150
	 *
2151
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2152
	 * @param string|array $names
2153
	 */
2154
	public static function delete_option( $names ) {
2155
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2156
		return Jetpack_Options::delete_option( $names );
2157
	}
2158
2159
	/**
2160
	 * Enters a user token into the user_tokens option
2161
	 *
2162
	 * @param int $user_id
2163
	 * @param string $token
2164
	 * return bool
2165
	 */
2166
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2167
		// not designed for concurrent updates
2168
		$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
2169
		if ( ! is_array( $user_tokens ) )
2170
			$user_tokens = array();
2171
		$user_tokens[$user_id] = $token;
2172
		if ( $is_master_user ) {
2173
			$master_user = $user_id;
2174
			$options     = compact( 'user_tokens', 'master_user' );
2175
		} else {
2176
			$options = compact( 'user_tokens' );
2177
		}
2178
		return Jetpack_Options::update_options( $options );
2179
	}
2180
2181
	/**
2182
	 * Returns an array of all PHP files in the specified absolute path.
2183
	 * Equivalent to glob( "$absolute_path/*.php" ).
2184
	 *
2185
	 * @param string $absolute_path The absolute path of the directory to search.
2186
	 * @return array Array of absolute paths to the PHP files.
2187
	 */
2188
	public static function glob_php( $absolute_path ) {
2189
		if ( function_exists( 'glob' ) ) {
2190
			return glob( "$absolute_path/*.php" );
2191
		}
2192
2193
		$absolute_path = untrailingslashit( $absolute_path );
2194
		$files = array();
2195
		if ( ! $dir = @opendir( $absolute_path ) ) {
2196
			return $files;
2197
		}
2198
2199
		while ( false !== $file = readdir( $dir ) ) {
2200
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2201
				continue;
2202
			}
2203
2204
			$file = "$absolute_path/$file";
2205
2206
			if ( ! is_file( $file ) ) {
2207
				continue;
2208
			}
2209
2210
			$files[] = $file;
2211
		}
2212
2213
		closedir( $dir );
2214
2215
		return $files;
2216
	}
2217
2218
	public static function activate_new_modules( $redirect = false ) {
2219
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
2220
			return;
2221
		}
2222
2223
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2224 View Code Duplication
		if ( ! $jetpack_old_version ) {
2225
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2226
			/** This action is documented in class.jetpack.php */
2227
			do_action( 'updating_jetpack_version', $version, false );
2228
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2229
		}
2230
2231
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2232
2233
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2234
			return;
2235
		}
2236
2237
		$active_modules     = Jetpack::get_active_modules();
2238
		$reactivate_modules = array();
2239
		foreach ( $active_modules as $active_module ) {
2240
			$module = Jetpack::get_module( $active_module );
2241
			if ( ! isset( $module['changed'] ) ) {
2242
				continue;
2243
			}
2244
2245
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2246
				continue;
2247
			}
2248
2249
			$reactivate_modules[] = $active_module;
2250
			Jetpack::deactivate_module( $active_module );
2251
		}
2252
2253
		$new_version = JETPACK__VERSION . ':' . time();
2254
		/** This action is documented in class.jetpack.php */
2255
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2256
		Jetpack_Options::update_options(
2257
			array(
2258
				'version'     => $new_version,
2259
				'old_version' => $jetpack_old_version,
2260
			)
2261
		);
2262
2263
		Jetpack::state( 'message', 'modules_activated' );
2264
		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...
2265
2266
		if ( $redirect ) {
2267
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2268
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2269
				$page = $_GET['page'];
2270
			}
2271
2272
			wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
2273
			exit;
2274
		}
2275
	}
2276
2277
	/**
2278
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2279
	 * Make sure to tuck away module "library" files in a sub-directory.
2280
	 */
2281
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2282
		static $modules = null;
2283
2284
		if ( ! isset( $modules ) ) {
2285
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2286
			// Use the cache if we're on the front-end and it's available...
2287
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2288
				$modules = $available_modules_option[ JETPACK__VERSION ];
2289
			} else {
2290
				$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2291
2292
				$modules = array();
2293
2294
				foreach ( $files as $file ) {
2295
					if ( ! $headers = Jetpack::get_module( $file ) ) {
2296
						continue;
2297
					}
2298
2299
					$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
2300
				}
2301
2302
				Jetpack_Options::update_option( 'available_modules', array(
2303
					JETPACK__VERSION => $modules,
2304
				) );
2305
			}
2306
		}
2307
2308
		/**
2309
		 * Filters the array of modules available to be activated.
2310
		 *
2311
		 * @since 2.4.0
2312
		 *
2313
		 * @param array $modules Array of available modules.
2314
		 * @param string $min_version Minimum version number required to use modules.
2315
		 * @param string $max_version Maximum version number required to use modules.
2316
		 */
2317
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
2318
2319
		if ( ! $min_version && ! $max_version ) {
2320
			return array_keys( $mods );
2321
		}
2322
2323
		$r = array();
2324
		foreach ( $mods as $slug => $introduced ) {
2325
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2326
				continue;
2327
			}
2328
2329
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2330
				continue;
2331
			}
2332
2333
			$r[] = $slug;
2334
		}
2335
2336
		return $r;
2337
	}
2338
2339
	/**
2340
	 * Default modules loaded on activation.
2341
	 */
2342
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2343
		$return = array();
2344
2345
		foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
2346
			$module_data = Jetpack::get_module( $module );
2347
2348
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2349
				case 'yes' :
2350
					$return[] = $module;
2351
					break;
2352
				case 'public' :
2353
					if ( Jetpack_Options::get_option( 'public' ) ) {
2354
						$return[] = $module;
2355
					}
2356
					break;
2357
				case 'no' :
2358
				default :
2359
					break;
2360
			}
2361
		}
2362
		/**
2363
		 * Filters the array of default modules.
2364
		 *
2365
		 * @since 2.5.0
2366
		 *
2367
		 * @param array $return Array of default modules.
2368
		 * @param string $min_version Minimum version number required to use modules.
2369
		 * @param string $max_version Maximum version number required to use modules.
2370
		 */
2371
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
2372
	}
2373
2374
	/**
2375
	 * Checks activated modules during auto-activation to determine
2376
	 * if any of those modules are being deprecated.  If so, close
2377
	 * them out, and add any replacement modules.
2378
	 *
2379
	 * Runs at priority 99 by default.
2380
	 *
2381
	 * This is run late, so that it can still activate a module if
2382
	 * the new module is a replacement for another that the user
2383
	 * currently has active, even if something at the normal priority
2384
	 * would kibosh everything.
2385
	 *
2386
	 * @since 2.6
2387
	 * @uses jetpack_get_default_modules filter
2388
	 * @param array $modules
2389
	 * @return array
2390
	 */
2391
	function handle_deprecated_modules( $modules ) {
2392
		$deprecated_modules = array(
2393
			'debug'            => null,  // Closed out and moved to the debugger library.
2394
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2395
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2396
		);
2397
2398
		// Don't activate SSO if they never completed activating WPCC.
2399
		if ( Jetpack::is_module_active( 'wpcc' ) ) {
2400
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2401
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2402
				$deprecated_modules['wpcc'] = null;
2403
			}
2404
		}
2405
2406
		foreach ( $deprecated_modules as $module => $replacement ) {
2407
			if ( Jetpack::is_module_active( $module ) ) {
2408
				self::deactivate_module( $module );
2409
				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...
2410
					$modules[] = $replacement;
2411
				}
2412
			}
2413
		}
2414
2415
		return array_unique( $modules );
2416
	}
2417
2418
	/**
2419
	 * Checks activated plugins during auto-activation to determine
2420
	 * if any of those plugins are in the list with a corresponding module
2421
	 * that is not compatible with the plugin. The module will not be allowed
2422
	 * to auto-activate.
2423
	 *
2424
	 * @since 2.6
2425
	 * @uses jetpack_get_default_modules filter
2426
	 * @param array $modules
2427
	 * @return array
2428
	 */
2429
	function filter_default_modules( $modules ) {
2430
2431
		$active_plugins = self::get_active_plugins();
2432
2433
		if ( ! empty( $active_plugins ) ) {
2434
2435
			// For each module we'd like to auto-activate...
2436
			foreach ( $modules as $key => $module ) {
2437
				// If there are potential conflicts for it...
2438
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2439
					// For each potential conflict...
2440
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2441
						// If that conflicting plugin is active...
2442
						if ( in_array( $plugin, $active_plugins ) ) {
2443
							// Remove that item from being auto-activated.
2444
							unset( $modules[ $key ] );
2445
						}
2446
					}
2447
				}
2448
			}
2449
		}
2450
2451
		return $modules;
2452
	}
2453
2454
	/**
2455
	 * Extract a module's slug from its full path.
2456
	 */
2457
	public static function get_module_slug( $file ) {
2458
		return str_replace( '.php', '', basename( $file ) );
2459
	}
2460
2461
	/**
2462
	 * Generate a module's path from its slug.
2463
	 */
2464
	public static function get_module_path( $slug ) {
2465
		/**
2466
		 * Filters the path of a modules.
2467
		 *
2468
		 * @since 7.4.0
2469
		 *
2470
		 * @param array $return The absolute path to a module's root php file
2471
		 * @param string $slug The module slug
2472
		 */
2473
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
2474
	}
2475
2476
	/**
2477
	 * Load module data from module file. Headers differ from WordPress
2478
	 * plugin headers to avoid them being identified as standalone
2479
	 * plugins on the WordPress plugins page.
2480
	 */
2481
	public static function get_module( $module ) {
2482
		$headers = array(
2483
			'name'                      => 'Module Name',
2484
			'description'               => 'Module Description',
2485
			'sort'                      => 'Sort Order',
2486
			'recommendation_order'      => 'Recommendation Order',
2487
			'introduced'                => 'First Introduced',
2488
			'changed'                   => 'Major Changes In',
2489
			'deactivate'                => 'Deactivate',
2490
			'free'                      => 'Free',
2491
			'requires_connection'       => 'Requires Connection',
2492
			'auto_activate'             => 'Auto Activate',
2493
			'module_tags'               => 'Module Tags',
2494
			'feature'                   => 'Feature',
2495
			'additional_search_queries' => 'Additional Search Queries',
2496
			'plan_classes'              => 'Plans',
2497
		);
2498
2499
		$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
2500
2501
		$mod = Jetpack::get_file_data( $file, $headers );
2502
		if ( empty( $mod['name'] ) ) {
2503
			return false;
2504
		}
2505
2506
		$mod['sort']                    = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2507
		$mod['recommendation_order']    = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2508
		$mod['deactivate']              = empty( $mod['deactivate'] );
2509
		$mod['free']                    = empty( $mod['free'] );
2510
		$mod['requires_connection']     = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2511
2512
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2513
			$mod['auto_activate'] = 'No';
2514
		} else {
2515
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2516
		}
2517
2518
		if ( $mod['module_tags'] ) {
2519
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2520
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2521
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2522
		} else {
2523
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2524
		}
2525
2526 View Code Duplication
		if ( $mod['plan_classes'] ) {
2527
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2528
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2529
		} else {
2530
			$mod['plan_classes'] = array( 'free' );
2531
		}
2532
2533 View Code Duplication
		if ( $mod['feature'] ) {
2534
			$mod['feature'] = explode( ',', $mod['feature'] );
2535
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2536
		} else {
2537
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2538
		}
2539
2540
		/**
2541
		 * Filters the feature array on a module.
2542
		 *
2543
		 * This filter allows you to control where each module is filtered: Recommended,
2544
		 * and the default "Other" listing.
2545
		 *
2546
		 * @since 3.5.0
2547
		 *
2548
		 * @param array   $mod['feature'] The areas to feature this module:
2549
		 *     'Recommended' shows on the main Jetpack admin screen.
2550
		 *     'Other' should be the default if no other value is in the array.
2551
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2552
		 * @param array   $mod All the currently assembled module data.
2553
		 */
2554
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
2555
2556
		/**
2557
		 * Filter the returned data about a module.
2558
		 *
2559
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2560
		 * so please be careful.
2561
		 *
2562
		 * @since 3.6.0
2563
		 *
2564
		 * @param array   $mod    The details of the requested module.
2565
		 * @param string  $module The slug of the module, e.g. sharedaddy
2566
		 * @param string  $file   The path to the module source file.
2567
		 */
2568
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
2569
	}
2570
2571
	/**
2572
	 * Like core's get_file_data implementation, but caches the result.
2573
	 */
2574
	public static function get_file_data( $file, $headers ) {
2575
		//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2576
		$file_name = basename( $file );
2577
2578
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2579
2580
		$file_data_option = get_transient( $cache_key );
2581
2582
		if ( false === $file_data_option ) {
2583
			$file_data_option = array();
2584
		}
2585
2586
		$key           = md5( $file_name . serialize( $headers ) );
2587
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2588
2589
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2590
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2591
			return $file_data_option[ $key ];
2592
		}
2593
2594
		$data = get_file_data( $file, $headers );
2595
2596
		$file_data_option[ $key ] = $data;
2597
2598
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2599
2600
		return $data;
2601
	}
2602
2603
2604
	/**
2605
	 * Return translated module tag.
2606
	 *
2607
	 * @param string $tag Tag as it appears in each module heading.
2608
	 *
2609
	 * @return mixed
2610
	 */
2611
	public static function translate_module_tag( $tag ) {
2612
		return jetpack_get_module_i18n_tag( $tag );
2613
	}
2614
2615
	/**
2616
	 * Get i18n strings as a JSON-encoded string
2617
	 *
2618
	 * @return string The locale as JSON
2619
	 */
2620
	public static function get_i18n_data_json() {
2621
2622
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2623
		// JSON files with the file they should be included for. This is an md5
2624
		// of '_inc/build/admin.js'.
2625
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2626
2627
		$i18n_json =
2628
				   JETPACK__PLUGIN_DIR
2629
				   . 'languages/json/jetpack-'
2630
				   . get_user_locale()
2631
				   . '-'
2632
				   . $path_md5
2633
				   . '.json';
2634
2635
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2636
			$locale_data = @file_get_contents( $i18n_json );
2637
			if ( $locale_data ) {
2638
				return $locale_data;
2639
			}
2640
		}
2641
2642
		// Return valid empty Jed locale
2643
		return '{ "locale_data": { "messages": { "": {} } } }';
2644
	}
2645
2646
	/**
2647
	 * Add locale data setup to wp-i18n
2648
	 *
2649
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2650
	 *
2651
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2652
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2653
	 *
2654
	 * This method provides a safe way to request the setup multiple times but add the script at
2655
	 * most once.
2656
	 *
2657
	 * @since 6.7.0
2658
	 *
2659
	 * @return void
2660
	 */
2661
	public static function setup_wp_i18n_locale_data() {
2662
		static $script_added = false;
2663
		if ( ! $script_added ) {
2664
			$script_added = true;
2665
			wp_add_inline_script(
2666
				'wp-i18n',
2667
				'wp.i18n.setLocaleData( ' . Jetpack::get_i18n_data_json() . ', \'jetpack\' );'
2668
			);
2669
		}
2670
	}
2671
2672
	/**
2673
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2674
	 *
2675
	 * @since 3.9.2
2676
	 *
2677
	 * @param array $modules
2678
	 *
2679
	 * @return string|void
2680
	 */
2681
	public static function get_translated_modules( $modules ) {
2682
		foreach ( $modules as $index => $module ) {
2683
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2684
			if ( isset( $module['name'] ) ) {
2685
				$modules[ $index ]['name'] = $i18n_module['name'];
2686
			}
2687
			if ( isset( $module['description'] ) ) {
2688
				$modules[ $index ]['description'] = $i18n_module['description'];
2689
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2690
			}
2691
		}
2692
		return $modules;
2693
	}
2694
2695
	/**
2696
	 * Get a list of activated modules as an array of module slugs.
2697
	 */
2698
	public static function get_active_modules() {
2699
		$active = Jetpack_Options::get_option( 'active_modules' );
2700
2701
		if ( ! is_array( $active ) ) {
2702
			$active = array();
2703
		}
2704
2705
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2706
			$active[] = 'vaultpress';
2707
		} else {
2708
			$active = array_diff( $active, array( 'vaultpress' ) );
2709
		}
2710
2711
		//If protect is active on the main site of a multisite, it should be active on all sites.
2712
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2713
			$active[] = 'protect';
2714
		}
2715
2716
		/**
2717
		 * Allow filtering of the active modules.
2718
		 *
2719
		 * Gives theme and plugin developers the power to alter the modules that
2720
		 * are activated on the fly.
2721
		 *
2722
		 * @since 5.8.0
2723
		 *
2724
		 * @param array $active Array of active module slugs.
2725
		 */
2726
		$active = apply_filters( 'jetpack_active_modules', $active );
2727
2728
		return array_unique( $active );
2729
	}
2730
2731
	/**
2732
	 * Check whether or not a Jetpack module is active.
2733
	 *
2734
	 * @param string $module The slug of a Jetpack module.
2735
	 * @return bool
2736
	 *
2737
	 * @static
2738
	 */
2739
	public static function is_module_active( $module ) {
2740
		return in_array( $module, self::get_active_modules() );
2741
	}
2742
2743
	public static function is_module( $module ) {
2744
		return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
2745
	}
2746
2747
	/**
2748
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2749
	 *
2750
	 * @param bool $catch True to start catching, False to stop.
2751
	 *
2752
	 * @static
2753
	 */
2754
	public static function catch_errors( $catch ) {
2755
		static $display_errors, $error_reporting;
2756
2757
		if ( $catch ) {
2758
			$display_errors  = @ini_set( 'display_errors', 1 );
2759
			$error_reporting = @error_reporting( E_ALL );
2760
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2761
		} else {
2762
			@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...
2763
			@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...
2764
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2765
		}
2766
	}
2767
2768
	/**
2769
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2770
	 */
2771
	public static function catch_errors_on_shutdown() {
2772
		Jetpack::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2773
	}
2774
2775
	/**
2776
	 * Rewrite any string to make paths easier to read.
2777
	 *
2778
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2779
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2780
	 *
2781
	 * @param $string
2782
	 * @return mixed
2783
	 */
2784
	public static function alias_directories( $string ) {
2785
		// ABSPATH has a trailing slash.
2786
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2787
		// WP_CONTENT_DIR does not have a trailing slash.
2788
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2789
2790
		return $string;
2791
	}
2792
2793
	public static function activate_default_modules(
2794
		$min_version = false,
2795
		$max_version = false,
2796
		$other_modules = array(),
2797
		$redirect = true,
2798
		$send_state_messages = true
2799
	) {
2800
		$jetpack = Jetpack::init();
2801
2802
		$modules = Jetpack::get_default_modules( $min_version, $max_version );
2803
		$modules = array_merge( $other_modules, $modules );
2804
2805
		// Look for standalone plugins and disable if active.
2806
2807
		$to_deactivate = array();
2808
		foreach ( $modules as $module ) {
2809
			if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
2810
				$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
2811
			}
2812
		}
2813
2814
		$deactivated = array();
2815
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2816
			list( $probable_file, $probable_title ) = $deactivate_me;
2817
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2818
				$deactivated[] = $module;
2819
			}
2820
		}
2821
2822
		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...
2823
			Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
2824
2825
			$url = add_query_arg(
2826
				array(
2827
					'action'   => 'activate_default_modules',
2828
					'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2829
				),
2830
				add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
2831
			);
2832
			wp_safe_redirect( $url );
2833
			exit;
2834
		}
2835
2836
		/**
2837
		 * Fires before default modules are activated.
2838
		 *
2839
		 * @since 1.9.0
2840
		 *
2841
		 * @param string $min_version Minimum version number required to use modules.
2842
		 * @param string $max_version Maximum version number required to use modules.
2843
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2844
		 */
2845
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2846
2847
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2848
		if ( $send_state_messages ) {
2849
			Jetpack::restate();
2850
			Jetpack::catch_errors( true );
2851
		}
2852
2853
		$active = Jetpack::get_active_modules();
2854
2855
		foreach ( $modules as $module ) {
2856
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2857
				$active[] = $module;
2858
				self::update_active_modules( $active );
2859
				continue;
2860
			}
2861
2862
			if ( $send_state_messages && in_array( $module, $active ) ) {
2863
				$module_info = Jetpack::get_module( $module );
2864 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2865
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2866
					if ( $active_state = Jetpack::state( $state ) ) {
2867
						$active_state = explode( ',', $active_state );
2868
					} else {
2869
						$active_state = array();
2870
					}
2871
					$active_state[] = $module;
2872
					Jetpack::state( $state, implode( ',', $active_state ) );
2873
				}
2874
				continue;
2875
			}
2876
2877
			$file = Jetpack::get_module_path( $module );
2878
			if ( ! file_exists( $file ) ) {
2879
				continue;
2880
			}
2881
2882
			// we'll override this later if the plugin can be included without fatal error
2883
			if ( $redirect ) {
2884
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
2885
			}
2886
2887
			if ( $send_state_messages ) {
2888
				Jetpack::state( 'error', 'module_activation_failed' );
2889
				Jetpack::state( 'module', $module );
2890
			}
2891
2892
			ob_start();
2893
			require_once $file;
2894
2895
			$active[] = $module;
2896
2897 View Code Duplication
			if ( $send_state_messages ) {
2898
2899
				$state    = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2900
				if ( $active_state = Jetpack::state( $state ) ) {
2901
					$active_state = explode( ',', $active_state );
2902
				} else {
2903
					$active_state = array();
2904
				}
2905
				$active_state[] = $module;
2906
				Jetpack::state( $state, implode( ',', $active_state ) );
2907
			}
2908
2909
			Jetpack::update_active_modules( $active );
2910
2911
			ob_end_clean();
2912
		}
2913
2914
		if ( $send_state_messages ) {
2915
			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...
2916
			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...
2917
		}
2918
2919
		Jetpack::catch_errors( false );
2920
		/**
2921
		 * Fires when default modules are activated.
2922
		 *
2923
		 * @since 1.9.0
2924
		 *
2925
		 * @param string $min_version Minimum version number required to use modules.
2926
		 * @param string $max_version Maximum version number required to use modules.
2927
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2928
		 */
2929
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
2930
	}
2931
2932
	public static function activate_module( $module, $exit = true, $redirect = true ) {
2933
		/**
2934
		 * Fires before a module is activated.
2935
		 *
2936
		 * @since 2.6.0
2937
		 *
2938
		 * @param string $module Module slug.
2939
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
2940
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
2941
		 */
2942
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
2943
2944
		$jetpack = Jetpack::init();
2945
2946
		if ( ! strlen( $module ) )
2947
			return false;
2948
2949
		if ( ! Jetpack::is_module( $module ) )
2950
			return false;
2951
2952
		// If it's already active, then don't do it again
2953
		$active = Jetpack::get_active_modules();
2954
		foreach ( $active as $act ) {
2955
			if ( $act == $module )
2956
				return true;
2957
		}
2958
2959
		$module_data = Jetpack::get_module( $module );
2960
2961
		if ( ! Jetpack::is_active() ) {
2962
			if ( ! Jetpack::is_development_mode() && ! Jetpack::is_onboarding() )
2963
				return false;
2964
2965
			// If we're not connected but in development mode, make sure the module doesn't require a connection
2966
			if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
2967
				return false;
2968
		}
2969
2970
		// Check and see if the old plugin is active
2971
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2972
			// Deactivate the old plugin
2973
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
2974
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
2975
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
2976
				Jetpack::state( 'deactivated_plugins', $module );
2977
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
2978
				exit;
2979
			}
2980
		}
2981
2982
		// Protect won't work with mis-configured IPs
2983
		if ( 'protect' === $module ) {
2984
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
2985
			if ( ! jetpack_protect_get_ip() ) {
2986
				Jetpack::state( 'message', 'protect_misconfigured_ip' );
2987
				return false;
2988
			}
2989
		}
2990
2991
		if ( ! Jetpack_Plan::supports( $module ) ) {
2992
			return false;
2993
		}
2994
2995
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
2996
		Jetpack::state( 'module', $module );
2997
		Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
2998
2999
		Jetpack::catch_errors( true );
3000
		ob_start();
3001
		require Jetpack::get_module_path( $module );
3002
		/** This action is documented in class.jetpack.php */
3003
		do_action( 'jetpack_activate_module', $module );
3004
		$active[] = $module;
3005
		Jetpack::update_active_modules( $active );
3006
3007
		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...
3008
		ob_end_clean();
3009
		Jetpack::catch_errors( false );
3010
3011
		if ( $redirect ) {
3012
			wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
3013
		}
3014
		if ( $exit ) {
3015
			exit;
3016
		}
3017
		return true;
3018
	}
3019
3020
	function activate_module_actions( $module ) {
3021
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3022
	}
3023
3024
	public static function deactivate_module( $module ) {
3025
		/**
3026
		 * Fires when a module is deactivated.
3027
		 *
3028
		 * @since 1.9.0
3029
		 *
3030
		 * @param string $module Module slug.
3031
		 */
3032
		do_action( 'jetpack_pre_deactivate_module', $module );
3033
3034
		$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...
3035
3036
		$active = Jetpack::get_active_modules();
3037
		$new    = array_filter( array_diff( $active, (array) $module ) );
3038
3039
		return self::update_active_modules( $new );
3040
	}
3041
3042
	public static function enable_module_configurable( $module ) {
3043
		$module = Jetpack::get_module_slug( $module );
3044
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3045
	}
3046
3047
	/**
3048
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3049
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3050
	 *
3051
	 * @param string $module Module slug
3052
	 * @return string $url module configuration URL
3053
	 */
3054
	public static function module_configuration_url( $module ) {
3055
		$module = Jetpack::get_module_slug( $module );
3056
		$default_url =  Jetpack::admin_url() . "#/settings?term=$module";
3057
		/**
3058
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3059
		 *
3060
		 * @since 6.9.0
3061
		 *
3062
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3063
		 */
3064
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3065
3066
		return $url;
3067
	}
3068
3069
/* Installation */
3070
	public static function bail_on_activation( $message, $deactivate = true ) {
3071
?>
3072
<!doctype html>
3073
<html>
3074
<head>
3075
<meta charset="<?php bloginfo( 'charset' ); ?>">
3076
<style>
3077
* {
3078
	text-align: center;
3079
	margin: 0;
3080
	padding: 0;
3081
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3082
}
3083
p {
3084
	margin-top: 1em;
3085
	font-size: 18px;
3086
}
3087
</style>
3088
<body>
3089
<p><?php echo esc_html( $message ); ?></p>
3090
</body>
3091
</html>
3092
<?php
3093
		if ( $deactivate ) {
3094
			$plugins = get_option( 'active_plugins' );
3095
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3096
			$update  = false;
3097
			foreach ( $plugins as $i => $plugin ) {
3098
				if ( $plugin === $jetpack ) {
3099
					$plugins[$i] = false;
3100
					$update = true;
3101
				}
3102
			}
3103
3104
			if ( $update ) {
3105
				update_option( 'active_plugins', array_filter( $plugins ) );
3106
			}
3107
		}
3108
		exit;
3109
	}
3110
3111
	/**
3112
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3113
	 * @static
3114
	 */
3115
	public static function plugin_activation( $network_wide ) {
3116
		Jetpack_Options::update_option( 'activated', 1 );
3117
3118
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3119
			Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3120
		}
3121
3122
		if ( $network_wide )
3123
			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...
3124
3125
		// For firing one-off events (notices) immediately after activation
3126
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3127
3128
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3129
3130
		Jetpack::plugin_initialize();
3131
	}
3132
3133
	public static function get_activation_source( $referer_url ) {
3134
3135
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3136
			return array( 'wp-cli', null );
3137
		}
3138
3139
		$referer = parse_url( $referer_url );
3140
3141
		$source_type = 'unknown';
3142
		$source_query = null;
3143
3144
		if ( ! is_array( $referer ) ) {
3145
			return array( $source_type, $source_query );
3146
		}
3147
3148
		$plugins_path = parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
3149
		$plugins_install_path = parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
3150
3151
		if ( isset( $referer['query'] ) ) {
3152
			parse_str( $referer['query'], $query_parts );
3153
		} else {
3154
			$query_parts = array();
3155
		}
3156
3157
		if ( $plugins_path === $referer['path'] ) {
3158
			$source_type = 'list';
3159
		} elseif ( $plugins_install_path === $referer['path'] ) {
3160
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3161
			switch( $tab ) {
3162
				case 'popular':
3163
					$source_type = 'popular';
3164
					break;
3165
				case 'recommended':
3166
					$source_type = 'recommended';
3167
					break;
3168
				case 'favorites':
3169
					$source_type = 'favorites';
3170
					break;
3171
				case 'search':
3172
					$source_type = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3173
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3174
					break;
3175
				default:
3176
					$source_type = 'featured';
3177
			}
3178
		}
3179
3180
		return array( $source_type, $source_query );
3181
	}
3182
3183
	/**
3184
	 * Runs before bumping version numbers up to a new version
3185
	 * @param  string $version    Version:timestamp
3186
	 * @param  string $old_version Old Version:timestamp or false if not set yet.
3187
	 * @return null              [description]
3188
	 */
3189
	public static function do_version_bump( $version, $old_version ) {
3190
		if ( ! $old_version ) { // For new sites
3191
			// There used to be stuff here, but this seems like it might  be useful to someone in the future...
3192
		}
3193
	}
3194
3195
	/**
3196
	 * Sets the internal version number and activation state.
3197
	 * @static
3198
	 */
3199
	public static function plugin_initialize() {
3200
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3201
			Jetpack_Options::update_option( 'activated', 2 );
3202
		}
3203
3204 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3205
			$version = $old_version = JETPACK__VERSION . ':' . time();
3206
			/** This action is documented in class.jetpack.php */
3207
			do_action( 'updating_jetpack_version', $version, false );
3208
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3209
		}
3210
3211
		Jetpack::load_modules();
3212
3213
		Jetpack_Options::delete_option( 'do_activate' );
3214
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3215
	}
3216
3217
	/**
3218
	 * Removes all connection options
3219
	 * @static
3220
	 */
3221
	public static function plugin_deactivation( ) {
3222
		require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
3223
		if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3224
			Jetpack_Network::init()->deactivate();
3225
		} else {
3226
			Jetpack::disconnect( false );
3227
			//Jetpack_Heartbeat::init()->deactivate();
3228
		}
3229
	}
3230
3231
	/**
3232
	 * Disconnects from the Jetpack servers.
3233
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3234
	 * @static
3235
	 */
3236
	public static function disconnect( $update_activated_state = true ) {
3237
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3238
		$connection = self::connection();
3239
		$connection->clean_nonces( true );
3240
3241
		// If the site is in an IDC because sync is not allowed,
3242
		// let's make sure to not disconnect the production site.
3243
		if ( ! self::validate_sync_error_idc_option() ) {
3244
			$tracking = new Tracking();
3245
			$tracking->record_user_event( 'disconnect_site', array() );
3246
3247
			$xml = new Jetpack_IXR_Client();
3248
			$xml->query( 'jetpack.deregister', get_current_user_id() );
3249
		}
3250
3251
		Jetpack_Options::delete_option(
3252
			array(
3253
				'blog_token',
3254
				'user_token',
3255
				'user_tokens',
3256
				'master_user',
3257
				'time_diff',
3258
				'fallback_no_verify_ssl_certs',
3259
			)
3260
		);
3261
3262
		Jetpack_IDC::clear_all_idc_options();
3263
		Jetpack_Options::delete_raw_option( 'jetpack_secrets' );
3264
3265
		if ( $update_activated_state ) {
3266
			Jetpack_Options::update_option( 'activated', 4 );
3267
		}
3268
3269
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3270
			// Check then record unique disconnection if site has never been disconnected previously
3271
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3272
				$jetpack_unique_connection['disconnected'] = 1;
3273
			} else {
3274
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3275
					//track unique disconnect
3276
					$jetpack = Jetpack::init();
3277
3278
					$jetpack->stat( 'connections', 'unique-disconnect' );
3279
					$jetpack->do_stats( 'server_side' );
3280
				}
3281
				// increment number of times disconnected
3282
				$jetpack_unique_connection['disconnected'] += 1;
3283
			}
3284
3285
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3286
		}
3287
3288
		// Delete cached connected user data
3289
		$transient_key = "jetpack_connected_user_data_" . get_current_user_id();
3290
		delete_transient( $transient_key );
3291
3292
		// Delete all the sync related data. Since it could be taking up space.
3293
		Sender::get_instance()->uninstall();
3294
3295
		// Disable the Heartbeat cron
3296
		Jetpack_Heartbeat::init()->deactivate();
3297
	}
3298
3299
	/**
3300
	 * Unlinks the current user from the linked WordPress.com user.
3301
	 *
3302
	 * @deprecated since 7.7
3303
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3304
	 *
3305
	 * @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...
3306
	 * @return Boolean Whether the disconnection of the user was successful.
3307
	 */
3308
	public static function unlink_user( $user_id = null ) {
3309
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3310
		return Connection_Manager::disconnect_user( $user_id );
3311
	}
3312
3313
	/**
3314
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3315
	 */
3316
	public static function try_registration() {
3317
		// The user has agreed to the TOS at some point by now.
3318
		Jetpack_Options::update_option( 'tos_agreed', true );
3319
3320
		// Let's get some testing in beta versions and such.
3321
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3322
			// Before attempting to connect, let's make sure that the domains are viable.
3323
			$domains_to_check = array_unique( array(
3324
				'siteurl' => parse_url( get_site_url(), PHP_URL_HOST ),
3325
				'homeurl' => parse_url( get_home_url(), PHP_URL_HOST ),
3326
			) );
3327
			foreach ( $domains_to_check as $domain ) {
3328
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
It seems like $domain defined by $domain on line 3327 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...
3329
				if ( is_wp_error( $result ) ) {
3330
					return $result;
3331
				}
3332
			}
3333
		}
3334
3335
		$result = Jetpack::register();
3336
3337
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3338
		if ( ! $result || is_wp_error( $result ) ) {
3339
			return $result;
3340
		} else {
3341
			return true;
3342
		}
3343
	}
3344
3345
	/**
3346
	 * Tracking an internal event log. Try not to put too much chaff in here.
3347
	 *
3348
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3349
	 */
3350
	public static function log( $code, $data = null ) {
3351
		// only grab the latest 200 entries
3352
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3353
3354
		// Append our event to the log
3355
		$log_entry = array(
3356
			'time'    => time(),
3357
			'user_id' => get_current_user_id(),
3358
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3359
			'code'    => $code,
3360
		);
3361
		// Don't bother storing it unless we've got some.
3362
		if ( ! is_null( $data ) ) {
3363
			$log_entry['data'] = $data;
3364
		}
3365
		$log[] = $log_entry;
3366
3367
		// Try add_option first, to make sure it's not autoloaded.
3368
		// @todo: Add an add_option method to Jetpack_Options
3369
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3370
			Jetpack_Options::update_option( 'log', $log );
3371
		}
3372
3373
		/**
3374
		 * Fires when Jetpack logs an internal event.
3375
		 *
3376
		 * @since 3.0.0
3377
		 *
3378
		 * @param array $log_entry {
3379
		 *	Array of details about the log entry.
3380
		 *
3381
		 *	@param string time Time of the event.
3382
		 *	@param int user_id ID of the user who trigerred the event.
3383
		 *	@param int blog_id Jetpack Blog ID.
3384
		 *	@param string code Unique name for the event.
3385
		 *	@param string data Data about the event.
3386
		 * }
3387
		 */
3388
		do_action( 'jetpack_log_entry', $log_entry );
3389
	}
3390
3391
	/**
3392
	 * Get the internal event log.
3393
	 *
3394
	 * @param $event (string) - only return the specific log events
3395
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3396
	 *
3397
	 * @return array of log events || WP_Error for invalid params
3398
	 */
3399
	public static function get_log( $event = false, $num = false ) {
3400
		if ( $event && ! is_string( $event ) ) {
3401
			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...
3402
		}
3403
3404
		if ( $num && ! is_numeric( $num ) ) {
3405
			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...
3406
		}
3407
3408
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3409
3410
		// If nothing set - act as it did before, otherwise let's start customizing the output
3411
		if ( ! $num && ! $event ) {
3412
			return $entire_log;
3413
		} else {
3414
			$entire_log = array_reverse( $entire_log );
3415
		}
3416
3417
		$custom_log_output = array();
3418
3419
		if ( $event ) {
3420
			foreach ( $entire_log as $log_event ) {
3421
				if ( $event == $log_event[ 'code' ] ) {
3422
					$custom_log_output[] = $log_event;
3423
				}
3424
			}
3425
		} else {
3426
			$custom_log_output = $entire_log;
3427
		}
3428
3429
		if ( $num ) {
3430
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3431
		}
3432
3433
		return $custom_log_output;
3434
	}
3435
3436
	/**
3437
	 * Log modification of important settings.
3438
	 */
3439
	public static function log_settings_change( $option, $old_value, $value ) {
3440
		switch( $option ) {
3441
			case 'jetpack_sync_non_public_post_stati':
3442
				self::log( $option, $value );
3443
				break;
3444
		}
3445
	}
3446
3447
	/**
3448
	 * Return stat data for WPCOM sync
3449
	 */
3450
	public static function get_stat_data( $encode = true, $extended = true ) {
3451
		$data = Jetpack_Heartbeat::generate_stats_array();
3452
3453
		if ( $extended ) {
3454
			$additional_data = self::get_additional_stat_data();
3455
			$data = array_merge( $data, $additional_data );
3456
		}
3457
3458
		if ( $encode ) {
3459
			return json_encode( $data );
3460
		}
3461
3462
		return $data;
3463
	}
3464
3465
	/**
3466
	 * Get additional stat data to sync to WPCOM
3467
	 */
3468
	public static function get_additional_stat_data( $prefix = '' ) {
3469
		$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...
3470
		$return["{$prefix}plugins-extra"]  = Jetpack::get_parsed_plugin_data();
3471
		$return["{$prefix}users"]          = (int) Jetpack::get_site_user_count();
3472
		$return["{$prefix}site-count"]     = 0;
3473
3474
		if ( function_exists( 'get_blog_count' ) ) {
3475
			$return["{$prefix}site-count"] = get_blog_count();
3476
		}
3477
		return $return;
3478
	}
3479
3480
	private static function get_site_user_count() {
3481
		global $wpdb;
3482
3483
		if ( function_exists( 'wp_is_large_network' ) ) {
3484
			if ( wp_is_large_network( 'users' ) ) {
3485
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3486
			}
3487
		}
3488
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3489
			// It wasn't there, so regenerate the data and save the transient
3490
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3491
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3492
		}
3493
		return $user_count;
3494
	}
3495
3496
	/* Admin Pages */
3497
3498
	function admin_init() {
3499
		// If the plugin is not connected, display a connect message.
3500
		if (
3501
			// the plugin was auto-activated and needs its candy
3502
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3503
		||
3504
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3505
			! Jetpack_Options::get_option( 'activated' )
3506
		) {
3507
			Jetpack::plugin_initialize();
3508
		}
3509
3510
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
3511
			Jetpack_Connection_Banner::init();
3512
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3513
			// Upgrade: 1.1 -> 1.1.1
3514
			// Check and see if host can verify the Jetpack servers' SSL certificate
3515
			$args = array();
3516
			$connection = self::connection();
3517
			Client::_wp_remote_request(
3518
				Jetpack::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3519
				$args,
3520
				true
3521
			);
3522
		}
3523
3524
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3525
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3526
		}
3527
3528
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3529
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3530
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3531
3532
		if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
3533
			// Artificially throw errors in certain whitelisted cases during plugin activation
3534
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3535
		}
3536
3537
		// Add custom column in wp-admin/users.php to show whether user is linked.
3538
		add_filter( 'manage_users_columns',       array( $this, 'jetpack_icon_user_connected' ) );
3539
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3540
		add_action( 'admin_print_styles',         array( $this, 'jetpack_user_col_style' ) );
3541
	}
3542
3543
	function admin_body_class( $admin_body_class = '' ) {
3544
		$classes = explode( ' ', trim( $admin_body_class ) );
3545
3546
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3547
3548
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3549
		return " $admin_body_class ";
3550
	}
3551
3552
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3553
		return $admin_body_class . ' jetpack-pagestyles ';
3554
	}
3555
3556
	/**
3557
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3558
	 * This function artificially throws errors for such cases (whitelisted).
3559
	 *
3560
	 * @param string $plugin The activated plugin.
3561
	 */
3562
	function throw_error_on_activate_plugin( $plugin ) {
3563
		$active_modules = Jetpack::get_active_modules();
3564
3565
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3566
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3567
			$throw = false;
3568
3569
			// Try and make sure it really was the stats plugin
3570
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3571
				if ( 'stats.php' == basename( $plugin ) ) {
3572
					$throw = true;
3573
				}
3574
			} else {
3575
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3576
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3577
					$throw = true;
3578
				}
3579
			}
3580
3581
			if ( $throw ) {
3582
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3583
			}
3584
		}
3585
	}
3586
3587
	function intercept_plugin_error_scrape_init() {
3588
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3589
	}
3590
3591
	function intercept_plugin_error_scrape( $action, $result ) {
3592
		if ( ! $result ) {
3593
			return;
3594
		}
3595
3596
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3597
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3598
				Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3599
			}
3600
		}
3601
	}
3602
3603
	/**
3604
	 * Register the remote file upload request handlers, if needed.
3605
	 *
3606
	 * @access public
3607
	 */
3608
	public function add_remote_request_handlers() {
3609
		// Remote file uploads are allowed only via AJAX requests.
3610
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3611
			return;
3612
		}
3613
3614
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3615
		$remote_request_actions = array(
3616
			'jetpack_upload_file',
3617
			'jetpack_update_file',
3618
		);
3619
3620
		// phpcs:ignore WordPress.Security.NonceVerification
3621
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3622
			return;
3623
		}
3624
3625
		// Require Jetpack authentication for the remote file upload AJAX requests.
3626
		$this->connection_manager->require_jetpack_authentication();
3627
3628
		// Register the remote file upload AJAX handlers.
3629
		foreach ( $remote_request_actions as $action ) {
3630
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3631
		}
3632
	}
3633
3634
	/**
3635
	 * Handler for Jetpack remote file uploads.
3636
	 *
3637
	 * @access public
3638
	 */
3639
	public function remote_request_handlers() {
3640
		$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...
3641
3642
		switch ( current_filter() ) {
3643
		case 'wp_ajax_nopriv_jetpack_upload_file' :
3644
			$response = $this->upload_handler();
3645
			break;
3646
3647
		case 'wp_ajax_nopriv_jetpack_update_file' :
3648
			$response = $this->upload_handler( true );
3649
			break;
3650
		default :
3651
			$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...
3652
			break;
3653
		}
3654
3655
		if ( ! $response ) {
3656
			$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...
3657
		}
3658
3659
		if ( is_wp_error( $response ) ) {
3660
			$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...
3661
			$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...
3662
			$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...
3663
3664
			if ( ! is_int( $status_code ) ) {
3665
				$status_code = 400;
3666
			}
3667
3668
			status_header( $status_code );
3669
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3670
		}
3671
3672
		status_header( 200 );
3673
		if ( true === $response ) {
3674
			exit;
3675
		}
3676
3677
		die( json_encode( (object) $response ) );
3678
	}
3679
3680
	/**
3681
	 * Uploads a file gotten from the global $_FILES.
3682
	 * If `$update_media_item` is true and `post_id` is defined
3683
	 * the attachment file of the media item (gotten through of the post_id)
3684
	 * will be updated instead of add a new one.
3685
	 *
3686
	 * @param  boolean $update_media_item - update media attachment
3687
	 * @return array - An array describing the uploadind files process
3688
	 */
3689
	function upload_handler( $update_media_item = false ) {
3690
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3691
			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...
3692
		}
3693
3694
		$user = wp_authenticate( '', '' );
3695
		if ( ! $user || is_wp_error( $user ) ) {
3696
			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...
3697
		}
3698
3699
		wp_set_current_user( $user->ID );
3700
3701
		if ( ! current_user_can( 'upload_files' ) ) {
3702
			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...
3703
		}
3704
3705
		if ( empty( $_FILES ) ) {
3706
			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...
3707
		}
3708
3709
		foreach ( array_keys( $_FILES ) as $files_key ) {
3710
			if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
3711
				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...
3712
			}
3713
		}
3714
3715
		$media_keys = array_keys( $_FILES['media'] );
3716
3717
		$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...
3718
		if ( ! $token || is_wp_error( $token ) ) {
3719
			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...
3720
		}
3721
3722
		$uploaded_files = array();
3723
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3724
		unset( $GLOBALS['post'] );
3725
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3726
			$file = array();
3727
			foreach ( $media_keys as $media_key ) {
3728
				$file[$media_key] = $_FILES['media'][$media_key][$index];
3729
			}
3730
3731
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
3732
3733
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3734
			if ( $hmac_provided !== $hmac_file ) {
3735
				$uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
3736
				continue;
3737
			}
3738
3739
			$_FILES['.jetpack.upload.'] = $file;
3740
			$post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
3741
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3742
				$post_id = 0;
3743
			}
3744
3745
			if ( $update_media_item ) {
3746
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3747
					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...
3748
				}
3749
3750
				$media_array = $_FILES['media'];
3751
3752
				$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...
3753
				$file_array['type'] = $media_array['type'][0];
3754
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3755
				$file_array['error'] = $media_array['error'][0];
3756
				$file_array['size'] = $media_array['size'][0];
3757
3758
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3759
3760
				if ( is_wp_error( $edited_media_item ) ) {
3761
					return $edited_media_item;
3762
				}
3763
3764
				$response = (object) array(
3765
					'id'   => (string) $post_id,
3766
					'file' => (string) $edited_media_item->post_title,
3767
					'url'  => (string) wp_get_attachment_url( $post_id ),
3768
					'type' => (string) $edited_media_item->post_mime_type,
3769
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3770
				);
3771
3772
				return (array) array( $response );
3773
			}
3774
3775
			$attachment_id = media_handle_upload(
3776
				'.jetpack.upload.',
3777
				$post_id,
3778
				array(),
3779
				array(
3780
					'action' => 'jetpack_upload_file',
3781
				)
3782
			);
3783
3784
			if ( ! $attachment_id ) {
3785
				$uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
3786
			} elseif ( is_wp_error( $attachment_id ) ) {
3787
				$uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
3788
			} else {
3789
				$attachment = get_post( $attachment_id );
3790
				$uploaded_files[$index] = (object) array(
3791
					'id'   => (string) $attachment_id,
3792
					'file' => $attachment->post_title,
3793
					'url'  => wp_get_attachment_url( $attachment_id ),
3794
					'type' => $attachment->post_mime_type,
3795
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3796
				);
3797
				// Zip files uploads are not supported unless they are done for installation purposed
3798
				// lets delete them in case something goes wrong in this whole process
3799
				if ( 'application/zip' === $attachment->post_mime_type ) {
3800
					// Schedule a cleanup for 2 hours from now in case of failed install.
3801
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3802
				}
3803
			}
3804
		}
3805
		if ( ! is_null( $global_post ) ) {
3806
			$GLOBALS['post'] = $global_post;
3807
		}
3808
3809
		return $uploaded_files;
3810
	}
3811
3812
	/**
3813
	 * Add help to the Jetpack page
3814
	 *
3815
	 * @since Jetpack (1.2.3)
3816
	 * @return false if not the Jetpack page
3817
	 */
3818
	function admin_help() {
3819
		$current_screen = get_current_screen();
3820
3821
		// Overview
3822
		$current_screen->add_help_tab(
3823
			array(
3824
				'id'		=> 'home',
3825
				'title'		=> __( 'Home', 'jetpack' ),
3826
				'content'	=>
3827
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3828
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3829
					'<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>',
3830
			)
3831
		);
3832
3833
		// Screen Content
3834
		if ( current_user_can( 'manage_options' ) ) {
3835
			$current_screen->add_help_tab(
3836
				array(
3837
					'id'		=> 'settings',
3838
					'title'		=> __( 'Settings', 'jetpack' ),
3839
					'content'	=>
3840
						'<p><strong>' . __( 'Jetpack by WordPress.com',                                              'jetpack' ) . '</strong></p>' .
3841
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3842
						'<ol>' .
3843
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.',														'jetpack' ) . '</li>' .
3844
							'<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>' .
3845
						'</ol>' .
3846
						'<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>'
3847
				)
3848
			);
3849
		}
3850
3851
		// Help Sidebar
3852
		$current_screen->set_help_sidebar(
3853
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3854
			'<p><a href="https://jetpack.com/faq/" target="_blank">'     . __( 'Jetpack FAQ',     'jetpack' ) . '</a></p>' .
3855
			'<p><a href="https://jetpack.com/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3856
			'<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3857
		);
3858
	}
3859
3860
	function admin_menu_css() {
3861
		wp_enqueue_style( 'jetpack-icons' );
3862
	}
3863
3864
	function admin_menu_order() {
3865
		return true;
3866
	}
3867
3868 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3869
		$jp_menu_order = array();
3870
3871
		foreach ( $menu_order as $index => $item ) {
3872
			if ( $item != 'jetpack' ) {
3873
				$jp_menu_order[] = $item;
3874
			}
3875
3876
			if ( $index == 0 ) {
3877
				$jp_menu_order[] = 'jetpack';
3878
			}
3879
		}
3880
3881
		return $jp_menu_order;
3882
	}
3883
3884
	function admin_banner_styles() {
3885
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3886
3887
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3888
			wp_register_style(
3889
				'jetpack-dops-style',
3890
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3891
				array(),
3892
				JETPACK__VERSION
3893
			);
3894
		}
3895
3896
		wp_enqueue_style(
3897
			'jetpack',
3898
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3899
			array( 'jetpack-dops-style' ),
3900
			 JETPACK__VERSION . '-20121016'
3901
		);
3902
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3903
		wp_style_add_data( 'jetpack', 'suffix', $min );
3904
	}
3905
3906
	function plugin_action_links( $actions ) {
3907
3908
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3909
3910
		if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
3911
			return array_merge(
3912
				$jetpack_home,
3913
				array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3914
				array( 'support' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack-debugger '), __( 'Support', 'jetpack' ) ) ),
3915
				$actions
3916
				);
3917
			}
3918
3919
		return array_merge( $jetpack_home, $actions );
3920
	}
3921
3922
	/*
3923
	 * Registration flow:
3924
	 * 1 - ::admin_page_load() action=register
3925
	 * 2 - ::try_registration()
3926
	 * 3 - ::register()
3927
	 *     - Creates jetpack_register option containing two secrets and a timestamp
3928
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
3929
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
3930
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
3931
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
3932
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
3933
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
3934
	 *       jetpack_id, jetpack_secret, jetpack_public
3935
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
3936
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
3937
	 * 5 - user logs in with WP.com account
3938
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
3939
	 *		- Jetpack_Client_Server::authorize()
3940
	 *		- Jetpack_Client_Server::get_token()
3941
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
3942
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
3943
	 *			- which responds with access_token, token_type, scope
3944
	 *		- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
3945
	 *		- Jetpack::activate_default_modules()
3946
	 *     		- Deactivates deprecated plugins
3947
	 *     		- Activates all default modules
3948
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
3949
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
3950
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
3951
	 *     Done!
3952
	 */
3953
3954
	/**
3955
	 * Handles the page load events for the Jetpack admin page
3956
	 */
3957
	function admin_page_load() {
3958
		$error = false;
3959
3960
		// Make sure we have the right body class to hook stylings for subpages off of.
3961
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
3962
3963
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
3964
			// Should only be used in intermediate redirects to preserve state across redirects
3965
			Jetpack::restate();
3966
		}
3967
3968
		if ( isset( $_GET['connect_url_redirect'] ) ) {
3969
			// @todo: Add validation against a known whitelist
3970
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
3971
			// User clicked in the iframe to link their accounts
3972
			if ( ! Jetpack::is_user_connected() ) {
3973
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
3974
3975
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3976
				$connect_url = $this->build_connect_url( true, $redirect, $from );
3977
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
3978
3979
				if ( isset( $_GET['notes_iframe'] ) )
3980
					$connect_url .= '&notes_iframe';
3981
				wp_redirect( $connect_url );
3982
				exit;
3983
			} else {
3984
				if ( ! isset( $_GET['calypso_env'] ) ) {
3985
					Jetpack::state( 'message', 'already_authorized' );
3986
					wp_safe_redirect( Jetpack::admin_url() );
3987
					exit;
3988
				} else {
3989
					$connect_url = $this->build_connect_url( true, false, $from );
3990
					$connect_url .= '&already_authorized=true';
3991
					wp_redirect( $connect_url );
3992
					exit;
3993
				}
3994
			}
3995
		}
3996
3997
3998
		if ( isset( $_GET['action'] ) ) {
3999
			switch ( $_GET['action'] ) {
4000
			case 'authorize':
4001
				if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
4002
					Jetpack::state( 'message', 'already_authorized' );
4003
					wp_safe_redirect( Jetpack::admin_url() );
4004
					exit;
4005
				}
4006
				Jetpack::log( 'authorize' );
4007
				$client_server = new Jetpack_Client_Server;
4008
				$client_server->client_authorize();
4009
				exit;
4010
			case 'register' :
4011
				if ( ! current_user_can( 'jetpack_connect' ) ) {
4012
					$error = 'cheatin';
4013
					break;
4014
				}
4015
				check_admin_referer( 'jetpack-register' );
4016
				Jetpack::log( 'register' );
4017
				Jetpack::maybe_set_version_option();
4018
				$registered = Jetpack::try_registration();
4019
				if ( is_wp_error( $registered ) ) {
4020
					$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...
4021
					Jetpack::state( 'error', $error );
4022
					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...
4023
4024
					/**
4025
					 * Jetpack registration Error.
4026
					 *
4027
					 * @since 7.5.0
4028
					 *
4029
					 * @param string|int $error The error code.
4030
					 * @param \WP_Error $registered The error object.
4031
					 */
4032
					do_action( 'jetpack_connection_register_fail', $error, $registered );
4033
					break;
4034
				}
4035
4036
				$from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4037
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4038
4039
				/**
4040
				 * Jetpack registration Success.
4041
				 *
4042
				 * @since 7.5.0
4043
				 *
4044
				 * @param string $from 'from' GET parameter;
4045
				 */
4046
				do_action( 'jetpack_connection_register_success', $from );
4047
4048
				$url = $this->build_connect_url( true, $redirect, $from );
4049
4050
				if ( ! empty( $_GET['onboarding'] ) ) {
4051
					$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4052
				}
4053
4054
				if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4055
					$url = add_query_arg( 'auth_approved', 'true', $url );
4056
				}
4057
4058
				wp_redirect( $url );
4059
				exit;
4060
			case 'activate' :
4061
				if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4062
					$error = 'cheatin';
4063
					break;
4064
				}
4065
4066
				$module = stripslashes( $_GET['module'] );
4067
				check_admin_referer( "jetpack_activate-$module" );
4068
				Jetpack::log( 'activate', $module );
4069
				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...
4070
					Jetpack::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4071
				}
4072
				// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4073
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4074
				exit;
4075
			case 'activate_default_modules' :
4076
				check_admin_referer( 'activate_default_modules' );
4077
				Jetpack::log( 'activate_default_modules' );
4078
				Jetpack::restate();
4079
				$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4080
				$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4081
				$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4082
				Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
4083
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4084
				exit;
4085
			case 'disconnect' :
4086
				if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4087
					$error = 'cheatin';
4088
					break;
4089
				}
4090
4091
				check_admin_referer( 'jetpack-disconnect' );
4092
				Jetpack::log( 'disconnect' );
4093
				Jetpack::disconnect();
4094
				wp_safe_redirect( Jetpack::admin_url( 'disconnected=true' ) );
4095
				exit;
4096
			case 'reconnect' :
4097
				if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4098
					$error = 'cheatin';
4099
					break;
4100
				}
4101
4102
				check_admin_referer( 'jetpack-reconnect' );
4103
				Jetpack::log( 'reconnect' );
4104
				$this->disconnect();
4105
				wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4106
				exit;
4107 View Code Duplication
			case 'deactivate' :
4108
				if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4109
					$error = 'cheatin';
4110
					break;
4111
				}
4112
4113
				$modules = stripslashes( $_GET['module'] );
4114
				check_admin_referer( "jetpack_deactivate-$modules" );
4115
				foreach ( explode( ',', $modules ) as $module ) {
4116
					Jetpack::log( 'deactivate', $module );
4117
					Jetpack::deactivate_module( $module );
4118
					Jetpack::state( 'message', 'module_deactivated' );
4119
				}
4120
				Jetpack::state( 'module', $modules );
4121
				wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4122
				exit;
4123
			case 'unlink' :
4124
				$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4125
				check_admin_referer( 'jetpack-unlink' );
4126
				Jetpack::log( 'unlink' );
4127
				Connection_Manager::disconnect_user();
4128
				Jetpack::state( 'message', 'unlinked' );
4129
				if ( 'sub-unlink' == $redirect ) {
4130
					wp_safe_redirect( admin_url() );
4131
				} else {
4132
					wp_safe_redirect( Jetpack::admin_url( array( 'page' => $redirect ) ) );
4133
				}
4134
				exit;
4135
			case 'onboard' :
4136
				if ( ! current_user_can( 'manage_options' ) ) {
4137
					wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
4138
				} else {
4139
					Jetpack::create_onboarding_token();
4140
					$url = $this->build_connect_url( true );
4141
4142
					if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4143
						$url = add_query_arg( 'onboarding', $token, $url );
4144
					}
4145
4146
					$calypso_env = $this->get_calypso_env();
4147
					if ( ! empty( $calypso_env ) ) {
4148
						$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4149
					}
4150
4151
					wp_redirect( $url );
4152
					exit;
4153
				}
4154
				exit;
4155
			default:
4156
				/**
4157
				 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4158
				 *
4159
				 * @since 2.6.0
4160
				 *
4161
				 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4162
				 */
4163
				do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4164
			}
4165
		}
4166
4167
		if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
4168
			self::activate_new_modules( true );
4169
		}
4170
4171
		$message_code = Jetpack::state( 'message' );
4172
		if ( Jetpack::state( 'optin-manage' ) ) {
4173
			$activated_manage = $message_code;
4174
			$message_code = 'jetpack-manage';
4175
		}
4176
4177
		switch ( $message_code ) {
4178
		case 'jetpack-manage':
4179
			$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>';
4180
			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...
4181
				$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack'  ) . '</strong>';
4182
			}
4183
			break;
4184
4185
		}
4186
4187
		$deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
4188
4189
		if ( ! empty( $deactivated_plugins ) ) {
4190
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4191
			$deactivated_titles  = array();
4192
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4193
				if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
4194
					continue;
4195
				}
4196
4197
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
4198
			}
4199
4200
			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...
4201
				if ( $this->message ) {
4202
					$this->message .= "<br /><br />\n";
4203
				}
4204
4205
				$this->message .= wp_sprintf(
4206
					_n(
4207
						'Jetpack contains the most recent version of the old %l plugin.',
4208
						'Jetpack contains the most recent versions of the old %l plugins.',
4209
						count( $deactivated_titles ),
4210
						'jetpack'
4211
					),
4212
					$deactivated_titles
4213
				);
4214
4215
				$this->message .= "<br />\n";
4216
4217
				$this->message .= _n(
4218
					'The old version has been deactivated and can be removed from your site.',
4219
					'The old versions have been deactivated and can be removed from your site.',
4220
					count( $deactivated_titles ),
4221
					'jetpack'
4222
				);
4223
			}
4224
		}
4225
4226
		$this->privacy_checks = Jetpack::state( 'privacy_checks' );
4227
4228
		if ( $this->message || $this->error || $this->privacy_checks ) {
4229
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4230
		}
4231
4232
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4233
	}
4234
4235
	function admin_notices() {
4236
4237
		if ( $this->error ) {
4238
?>
4239
<div id="message" class="jetpack-message jetpack-err">
4240
	<div class="squeezer">
4241
		<h2><?php echo wp_kses( $this->error, array( 'a' => array( 'href' => array() ), 'small' => true, 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h2>
4242
<?php	if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
4243
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4244
<?php	endif; ?>
4245
	</div>
4246
</div>
4247
<?php
4248
		}
4249
4250
		if ( $this->message ) {
4251
?>
4252
<div id="message" class="jetpack-message">
4253
	<div class="squeezer">
4254
		<h2><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h2>
4255
	</div>
4256
</div>
4257
<?php
4258
		}
4259
4260
		if ( $this->privacy_checks ) :
4261
			$module_names = $module_slugs = array();
4262
4263
			$privacy_checks = explode( ',', $this->privacy_checks );
4264
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4265
			foreach ( $privacy_checks as $module_slug ) {
4266
				$module = Jetpack::get_module( $module_slug );
4267
				if ( ! $module ) {
4268
					continue;
4269
				}
4270
4271
				$module_slugs[] = $module_slug;
4272
				$module_names[] = "<strong>{$module['name']}</strong>";
4273
			}
4274
4275
			$module_slugs = join( ',', $module_slugs );
4276
?>
4277
<div id="message" class="jetpack-message jetpack-err">
4278
	<div class="squeezer">
4279
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4280
		<p><?php
4281
			echo wp_kses(
4282
				wptexturize(
4283
					wp_sprintf(
4284
						_nx(
4285
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4286
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4287
							count( $privacy_checks ),
4288
							'%l = list of Jetpack module/feature names',
4289
							'jetpack'
4290
						),
4291
						$module_names
4292
					)
4293
				),
4294
				array( 'strong' => true )
4295
			);
4296
4297
			echo "\n<br />\n";
4298
4299
			echo wp_kses(
4300
				sprintf(
4301
					_nx(
4302
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4303
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4304
						count( $privacy_checks ),
4305
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4306
						'jetpack'
4307
					),
4308
					wp_nonce_url(
4309
						Jetpack::admin_url(
4310
							array(
4311
								'page'   => 'jetpack',
4312
								'action' => 'deactivate',
4313
								'module' => urlencode( $module_slugs ),
4314
							)
4315
						),
4316
						"jetpack_deactivate-$module_slugs"
4317
					),
4318
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4319
				),
4320
				array( 'a' => array( 'href' => true, 'title' => true ) )
4321
			);
4322
		?></p>
4323
	</div>
4324
</div>
4325
<?php endif;
4326
	}
4327
4328
	/**
4329
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4330
	 */
4331
	function stat( $group, $detail ) {
4332
		if ( ! isset( $this->stats[ $group ] ) )
4333
			$this->stats[ $group ] = array();
4334
		$this->stats[ $group ][] = $detail;
4335
	}
4336
4337
	/**
4338
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4339
	 */
4340
	function do_stats( $method = '' ) {
4341
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4342
			foreach ( $this->stats as $group => $stats ) {
4343
				if ( is_array( $stats ) && count( $stats ) ) {
4344
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4345
					if ( 'server_side' === $method ) {
4346
						self::do_server_side_stat( $args );
4347
					} else {
4348
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4349
					}
4350
				}
4351
				unset( $this->stats[ $group ] );
4352
			}
4353
		}
4354
	}
4355
4356
	/**
4357
	 * Runs stats code for a one-off, server-side.
4358
	 *
4359
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4360
	 *
4361
	 * @return bool If it worked.
4362
	 */
4363
	static function do_server_side_stat( $args ) {
4364
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4365
		if ( is_wp_error( $response ) )
4366
			return false;
4367
4368
		if ( 200 !== wp_remote_retrieve_response_code( $response ) )
4369
			return false;
4370
4371
		return true;
4372
	}
4373
4374
	/**
4375
	 * Builds the stats url.
4376
	 *
4377
	 * @param $args array|string The arguments to append to the URL.
4378
	 *
4379
	 * @return string The URL to be pinged.
4380
	 */
4381
	static function build_stats_url( $args ) {
4382
		$defaults = array(
4383
			'v'    => 'wpcom2',
4384
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4385
		);
4386
		$args     = wp_parse_args( $args, $defaults );
4387
		/**
4388
		 * Filter the URL used as the Stats tracking pixel.
4389
		 *
4390
		 * @since 2.3.2
4391
		 *
4392
		 * @param string $url Base URL used as the Stats tracking pixel.
4393
		 */
4394
		$base_url = apply_filters(
4395
			'jetpack_stats_base_url',
4396
			'https://pixel.wp.com/g.gif'
4397
		);
4398
		$url      = add_query_arg( $args, $base_url );
4399
		return $url;
4400
	}
4401
4402
	/**
4403
	 * Get the role of the current user.
4404
	 *
4405
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4406
	 *
4407
	 * @access public
4408
	 * @static
4409
	 *
4410
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4411
	 */
4412
	public static function translate_current_user_to_role() {
4413
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4414
4415
		$roles = new Roles();
4416
		return $roles->translate_current_user_to_role();
4417
	}
4418
4419
	/**
4420
	 * Get the role of a particular user.
4421
	 *
4422
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4423
	 *
4424
	 * @access public
4425
	 * @static
4426
	 *
4427
	 * @param \WP_User $user User object.
4428
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4429
	 */
4430
	public static function translate_user_to_role( $user ) {
4431
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4432
4433
		$roles = new Roles();
4434
		return $roles->translate_user_to_role( $user );
4435
	}
4436
4437
	/**
4438
	 * Get the minimum capability for a role.
4439
	 *
4440
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4441
	 *
4442
	 * @access public
4443
	 * @static
4444
	 *
4445
	 * @param string $role Role name.
4446
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4447
	 */
4448
	public static function translate_role_to_cap( $role ) {
4449
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4450
4451
		$roles = new Roles();
4452
		return $roles->translate_role_to_cap( $role );
4453
	}
4454
4455
	/**
4456
	 * Sign a user role with the master access token.
4457
	 * If not specified, will default to the current user.
4458
	 *
4459
	 * @deprecated since 7.7
4460
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4461
	 *
4462
	 * @access public
4463
	 * @static
4464
	 *
4465
	 * @param string $role    User role.
4466
	 * @param int    $user_id ID of the user.
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...
4467
	 * @return string Signed user role.
4468
	 */
4469
	public static function sign_role( $role, $user_id = null ) {
4470
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4471
		return self::connection()->sign_role( $role, $user_id );
4472
	}
4473
4474
	/**
4475
	 * Builds a URL to the Jetpack connection auth page
4476
	 *
4477
	 * @since 3.9.5
4478
	 *
4479
	 * @param bool $raw If true, URL will not be escaped.
4480
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4481
	 *                              If string, will be a custom redirect.
4482
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4483
	 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4484
	 *
4485
	 * @return string Connect URL
4486
	 */
4487
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4488
		$site_id = Jetpack_Options::get_option( 'id' );
4489
		$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...
4490
4491
		if ( $register || ! $blog_token || ! $site_id ) {
4492
			$url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
4493
4494
			if ( ! empty( $redirect ) ) {
4495
				$url = add_query_arg(
4496
					'redirect',
4497
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4498
					$url
4499
				);
4500
			}
4501
4502
			if( is_network_admin() ) {
4503
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4504
			}
4505
		} else {
4506
4507
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4508
			// because otherwise this logic can get us in to a loop.
4509
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4510
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4511
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4512
4513
				$response = Client::wpcom_json_api_request_as_blog(
4514
					sprintf( '/sites/%d', $site_id ) .'?force=wpcom',
4515
					'1.1'
4516
				);
4517
4518
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4519
4520
					// Generating a register URL instead to refresh the existing token
4521
					return $this->build_connect_url( $raw, $redirect, $from, true );
4522
				}
4523
			}
4524
4525
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
It seems like $redirect defined by parameter $redirect on line 4487 can also be of type string; however, Jetpack::build_authorize_url() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
4526
		}
4527
4528
		if ( $from ) {
4529
			$url = add_query_arg( 'from', $from, $url );
4530
		}
4531
4532
		// Ensure that class to get the affiliate code is loaded
4533
		if ( ! class_exists( 'Jetpack_Affiliate' ) ) {
4534
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-affiliate.php';
4535
		}
4536
		// Get affiliate code and add it to the URL
4537
		$url = Jetpack_Affiliate::init()->add_code_as_query_arg( $url );
4538
4539
		$calypso_env = $this->get_calypso_env();
4540
4541
		if ( ! empty( $calypso_env ) ) {
4542
			$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4543
		}
4544
4545
		return $raw ? esc_url_raw( $url ) : esc_url( $url );
4546
	}
4547
4548
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4549
		if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && include_once JETPACK__GLOTPRESS_LOCALES_PATH ) {
4550
			$gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4551
		}
4552
4553
		$roles       = new Roles();
4554
		$role        = $roles->translate_current_user_to_role();
4555
		$signed_role = self::connection()->sign_role( $role );
4556
4557
		$user = wp_get_current_user();
4558
4559
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4560
		$redirect = $redirect
4561
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4562
			: $jetpack_admin_page;
4563
4564
		if( isset( $_REQUEST['is_multisite'] ) ) {
4565
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4566
		}
4567
4568
		$secrets = Jetpack::generate_secrets( 'authorize', false, 2 * HOUR_IN_SECONDS );
4569
4570
		/**
4571
		 * Filter the type of authorization.
4572
		 * 'calypso' completes authorization on wordpress.com/jetpack/connect
4573
		 * while 'jetpack' ( or any other value ) completes the authorization at jetpack.wordpress.com.
4574
		 *
4575
		 * @since 4.3.3
4576
		 *
4577
		 * @param string $auth_type Defaults to 'calypso', can also be 'jetpack'.
4578
		 */
4579
		$auth_type = apply_filters( 'jetpack_auth_type', 'calypso' );
4580
4581
4582
		$tracks = new Tracking();
4583
		$tracks_identity = $tracks->tracks_get_identity( get_current_user_id() );
4584
4585
		$args = urlencode_deep(
4586
			array(
4587
				'response_type' => 'code',
4588
				'client_id'     => Jetpack_Options::get_option( 'id' ),
4589
				'redirect_uri'  => add_query_arg(
4590
					array(
4591
						'action'   => 'authorize',
4592
						'_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
4593
						'redirect' => urlencode( $redirect ),
4594
					),
4595
					esc_url( admin_url( 'admin.php?page=jetpack' ) )
4596
				),
4597
				'state'         => $user->ID,
4598
				'scope'         => $signed_role,
4599
				'user_email'    => $user->user_email,
4600
				'user_login'    => $user->user_login,
4601
				'is_active'     => Jetpack::is_active(),
4602
				'jp_version'    => JETPACK__VERSION,
4603
				'auth_type'     => $auth_type,
4604
				'secret'        => $secrets['secret_1'],
4605
				'locale'        => ( isset( $gp_locale ) && isset( $gp_locale->slug ) ) ? $gp_locale->slug : '',
4606
				'blogname'      => get_option( 'blogname' ),
4607
				'site_url'      => site_url(),
4608
				'home_url'      => home_url(),
4609
				'site_icon'     => get_site_icon_url(),
4610
				'site_lang'     => get_locale(),
4611
				'_ui'           => $tracks_identity['_ui'],
4612
				'_ut'           => $tracks_identity['_ut'],
4613
				'site_created'  => Jetpack::get_assumed_site_creation_date(),
4614
			)
4615
		);
4616
4617
		self::apply_activation_source_to_args( $args );
4618
4619
		$connection = self::connection();
4620
4621
		$api_url = $iframe ? $connection->api_url( 'authorize_iframe' ) : $connection->api_url( 'authorize' );
4622
4623
		return add_query_arg( $args, $api_url );
4624
	}
4625
4626
	/**
4627
	 * Get our assumed site creation date.
4628
	 * Calculated based on the earlier date of either:
4629
	 * - Earliest admin user registration date.
4630
	 * - Earliest date of post of any post type.
4631
	 *
4632
	 * @since 7.2.0
4633
	 *
4634
	 * @return string Assumed site creation date and time.
4635
	 */
4636 View Code Duplication
	public static function get_assumed_site_creation_date() {
4637
		$earliest_registered_users = get_users( array(
4638
			'role'    => 'administrator',
4639
			'orderby' => 'user_registered',
4640
			'order'   => 'ASC',
4641
			'fields'  => array( 'user_registered' ),
4642
			'number'  => 1,
4643
		) );
4644
		$earliest_registration_date = $earliest_registered_users[0]->user_registered;
4645
4646
		$earliest_posts = get_posts( array(
4647
			'posts_per_page' => 1,
4648
			'post_type'      => 'any',
4649
			'post_status'    => 'any',
4650
			'orderby'        => 'date',
4651
			'order'          => 'ASC',
4652
		) );
4653
4654
		// If there are no posts at all, we'll count only on user registration date.
4655
		if ( $earliest_posts ) {
4656
			$earliest_post_date = $earliest_posts[0]->post_date;
4657
		} else {
4658
			$earliest_post_date = PHP_INT_MAX;
4659
		}
4660
4661
		return min( $earliest_registration_date, $earliest_post_date );
4662
	}
4663
4664 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4665
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4666
4667
		if ( $activation_source_name ) {
4668
			$args['_as'] = urlencode( $activation_source_name );
4669
		}
4670
4671
		if ( $activation_source_keyword ) {
4672
			$args['_ak'] = urlencode( $activation_source_keyword );
4673
		}
4674
	}
4675
4676
	function build_reconnect_url( $raw = false ) {
4677
		$url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4678
		return $raw ? $url : esc_url( $url );
4679
	}
4680
4681
	public static function admin_url( $args = null ) {
4682
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
4683
		$url = add_query_arg( $args, admin_url( 'admin.php' ) );
4684
		return $url;
4685
	}
4686
4687
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4688
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4689
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4690
	}
4691
4692
	function dismiss_jetpack_notice() {
4693
4694
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
4695
			return;
4696
		}
4697
4698
		switch( $_GET['jetpack-notice'] ) {
4699
			case 'dismiss':
4700
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4701
4702
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
4703
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4704
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4705
				}
4706
				break;
4707
		}
4708
	}
4709
4710
	public static function sort_modules( $a, $b ) {
4711
		if ( $a['sort'] == $b['sort'] )
4712
			return 0;
4713
4714
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
4715
	}
4716
4717
	function ajax_recheck_ssl() {
4718
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4719
		$result = Jetpack::permit_ssl( true );
4720
		wp_send_json( array(
4721
			'enabled' => $result,
4722
			'message' => get_transient( 'jetpack_https_test_message' )
4723
		) );
4724
	}
4725
4726
/* Client API */
4727
4728
	/**
4729
	 * Returns the requested Jetpack API URL
4730
	 *
4731
	 * @deprecated since 7.7
4732
	 * @return string
4733
	 */
4734
	public static function api_url( $relative_url ) {
4735
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
4736
		$connection = self::connection();
4737
		return $connection->api_url( $relative_url );
4738
	}
4739
4740
	/**
4741
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
4742
	 */
4743
	public static function fix_url_for_bad_hosts( $url ) {
4744
		if ( 0 !== strpos( $url, 'https://' ) ) {
4745
			return $url;
4746
		}
4747
4748
		switch ( JETPACK_CLIENT__HTTPS ) {
4749
			case 'ALWAYS' :
4750
				return $url;
4751
			case 'NEVER' :
4752
				return set_url_scheme( $url, 'http' );
4753
			// default : case 'AUTO' :
4754
		}
4755
4756
		// we now return the unmodified SSL URL by default, as a security precaution
4757
		return $url;
4758
	}
4759
4760
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4761
		// Default to a blog token.
4762
		$token_type = 'blog';
4763
4764
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
4765
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
4766
			if ( ! empty( $_GET['onboarding'] ) ) {
4767
				$jpo = $_GET;
4768
			} else {
4769
				$jpo = json_decode( $request_data, true );
4770
			}
4771
4772
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4773
			$jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4774
4775
			if (
4776
				isset( $jpo_user )
4777
				&& isset( $jpo_token )
4778
				&& is_email( $jpo_user )
4779
				&& ctype_alnum( $jpo_token )
4780
				&& isset( $_GET['rest_route'] )
4781
				&& self::validate_onboarding_token_action(
4782
					$jpo_token,
4783
					$_GET['rest_route']
4784
				)
4785
			) {
4786
				$jp_user = get_user_by( 'email', $jpo_user );
4787
				if ( is_a( $jp_user, 'WP_User' ) ) {
4788
					wp_set_current_user( $jp_user->ID );
4789
					$user_can = is_multisite()
4790
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
4791
						: current_user_can( 'manage_options' );
4792
					if ( $user_can ) {
4793
						$token_type = 'user';
4794
						$token->external_user_id = $jp_user->ID;
4795
					}
4796
				}
4797
			}
4798
4799
			$token_data['type']    = $token_type;
4800
			$token_data['user_id'] = $token->external_user_id;
4801
		}
4802
4803
		return $token_data;
4804
	}
4805
4806
	/**
4807
	 * Create a random secret for validating onboarding payload
4808
	 *
4809
	 * @return string Secret token
4810
	 */
4811
	public static function create_onboarding_token() {
4812
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4813
			$token = wp_generate_password( 32, false );
4814
			Jetpack_Options::update_option( 'onboarding', $token );
4815
		}
4816
4817
		return $token;
4818
	}
4819
4820
	/**
4821
	 * Remove the onboarding token
4822
	 *
4823
	 * @return bool True on success, false on failure
4824
	 */
4825
	public static function invalidate_onboarding_token() {
4826
		return Jetpack_Options::delete_option( 'onboarding' );
4827
	}
4828
4829
	/**
4830
	 * Validate an onboarding token for a specific action
4831
	 *
4832
	 * @return boolean True if token/action pair is accepted, false if not
4833
	 */
4834
	public static function validate_onboarding_token_action( $token, $action ) {
4835
		// Compare tokens, bail if tokens do not match
4836
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
4837
			return false;
4838
		}
4839
4840
		// List of valid actions we can take
4841
		$valid_actions = array(
4842
			'/jetpack/v4/settings',
4843
		);
4844
4845
		// Whitelist the action
4846
		if ( ! in_array( $action, $valid_actions ) ) {
4847
			return false;
4848
		}
4849
4850
		return true;
4851
	}
4852
4853
	/**
4854
	 * Checks to see if the URL is using SSL to connect with Jetpack
4855
	 *
4856
	 * @since 2.3.3
4857
	 * @return boolean
4858
	 */
4859
	public static function permit_ssl( $force_recheck = false ) {
4860
		// Do some fancy tests to see if ssl is being supported
4861
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
4862
			$message = '';
4863
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
4864
				$ssl = 0;
4865
			} else {
4866
				switch ( JETPACK_CLIENT__HTTPS ) {
4867
					case 'NEVER':
4868
						$ssl = 0;
4869
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
4870
						break;
4871
					case 'ALWAYS':
4872
					case 'AUTO':
4873
					default:
4874
						$ssl = 1;
4875
						break;
4876
				}
4877
4878
				// If it's not 'NEVER', test to see
4879
				if ( $ssl ) {
4880
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
4881
						$ssl = 0;
4882
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
4883
					} else {
4884
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
4885
						if ( is_wp_error( $response ) ) {
4886
							$ssl = 0;
4887
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
4888
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
4889
							$ssl = 0;
4890
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
4891
						}
4892
					}
4893
				}
4894
			}
4895
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
4896
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
4897
		}
4898
4899
		return (bool) $ssl;
4900
	}
4901
4902
	/*
4903
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
4904
	 */
4905
	public function alert_auto_ssl_fail() {
4906
		if ( ! current_user_can( 'manage_options' ) )
4907
			return;
4908
4909
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
4910
		?>
4911
4912
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
4913
			<div class="jp-banner__content">
4914
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
4915
				<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>
4916
				<p>
4917
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
4918
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
4919
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
4920
				</p>
4921
				<p>
4922
					<?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' ),
4923
							esc_url( Jetpack::admin_url( array( 'page' => 'jetpack-debugger' )  ) ),
4924
							esc_url( 'https://jetpack.com/support/getting-started-with-jetpack/troubleshooting-tips/' ) ); ?>
4925
				</p>
4926
			</div>
4927
		</div>
4928
		<style>
4929
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
4930
		</style>
4931
		<script type="text/javascript">
4932
			jQuery( document ).ready( function( $ ) {
4933
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
4934
					var $this = $( this );
4935
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
4936
					$( '#jetpack-recheck-ssl-output' ).html( '' );
4937
					e.preventDefault();
4938
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
4939
					$.post( ajaxurl, data )
4940
					  .done( function( response ) {
4941
					  	if ( response.enabled ) {
4942
					  		$( '#jetpack-ssl-warning' ).hide();
4943
					  	} else {
4944
					  		this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
4945
					  		$( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
4946
					  	}
4947
					  }.bind( $this ) );
4948
				} );
4949
			} );
4950
		</script>
4951
4952
		<?php
4953
	}
4954
4955
	/**
4956
	 * Returns the Jetpack XML-RPC API
4957
	 *
4958
	 * @return string
4959
	 */
4960
	public static function xmlrpc_api_url() {
4961
		$base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
4962
		return untrailingslashit( $base ) . '/xmlrpc.php';
4963
	}
4964
4965
	public static function connection() {
4966
		return self::init()->connection_manager;
4967
	}
4968
4969
	/**
4970
	 * Creates two secret tokens and the end of life timestamp for them.
4971
	 *
4972
	 * Note these tokens are unique per call, NOT static per site for connecting.
4973
	 *
4974
	 * @since 2.6
4975
	 * @return array
4976
	 */
4977
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
4978
		if ( false === $user_id ) {
4979
			$user_id = get_current_user_id();
4980
		}
4981
4982
		return self::connection()->generate_secrets( $action, $user_id, $exp );
4983
	}
4984
4985
	public static function get_secrets( $action, $user_id ) {
4986
		$secrets = self::connection()->get_secrets( $action, $user_id );
4987
4988
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
4989
			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...
4990
		}
4991
4992
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
4993
			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...
4994
		}
4995
4996
		return $secrets;
4997
	}
4998
4999
	/**
5000
	 * @deprecated 7.5 Use Connection_Manager instead.
5001
	 *
5002
	 * @param $action
5003
	 * @param $user_id
5004
	 */
5005
	public static function delete_secrets( $action, $user_id ) {
5006
		return self::connection()->delete_secrets( $action, $user_id );
5007
	}
5008
5009
	/**
5010
	 * Builds the timeout limit for queries talking with the wpcom servers.
5011
	 *
5012
	 * Based on local php max_execution_time in php.ini
5013
	 *
5014
	 * @since 2.6
5015
	 * @return int
5016
	 * @deprecated
5017
	 **/
5018
	public function get_remote_query_timeout_limit() {
5019
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5020
		return Jetpack::get_max_execution_time();
5021
	}
5022
5023
	/**
5024
	 * Builds the timeout limit for queries talking with the wpcom servers.
5025
	 *
5026
	 * Based on local php max_execution_time in php.ini
5027
	 *
5028
	 * @since 5.4
5029
	 * @return int
5030
	 **/
5031
	public static function get_max_execution_time() {
5032
		$timeout = (int) ini_get( 'max_execution_time' );
5033
5034
		// Ensure exec time set in php.ini
5035
		if ( ! $timeout ) {
5036
			$timeout = 30;
5037
		}
5038
		return $timeout;
5039
	}
5040
5041
	/**
5042
	 * Sets a minimum request timeout, and returns the current timeout
5043
	 *
5044
	 * @since 5.4
5045
	 **/
5046 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5047
		$timeout = self::get_max_execution_time();
5048
		if ( $timeout < $min_timeout ) {
5049
			$timeout = $min_timeout;
5050
			set_time_limit( $timeout );
5051
		}
5052
		return $timeout;
5053
	}
5054
5055
	/**
5056
	 * Takes the response from the Jetpack register new site endpoint and
5057
	 * verifies it worked properly.
5058
	 *
5059
	 * @since 2.6
5060
	 * @deprecated since 7.7.0
5061
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5062
	 **/
5063
	public function validate_remote_register_response() {
5064
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5065
	}
5066
5067
	/**
5068
	 * @return bool|WP_Error
5069
	 */
5070
	public static function register() {
5071
		$tracking = new Tracking();
5072
		$tracking->record_user_event( 'jpc_register_begin' );
5073
5074
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5075
5076
		$connection = self::connection();
5077
		$registration = $connection->register();
5078
5079
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5080
5081
		if ( ! $registration || is_wp_error( $registration ) ) {
5082
			return $registration;
5083
		}
5084
5085
		return true;
5086
	}
5087
5088
	/**
5089
	 * Filters the registration request body to include tracking properties.
5090
	 *
5091
	 * @param Array $properties
5092
	 * @return Array amended properties.
5093
	 */
5094
	public static function filter_register_request_body( $properties ) {
5095
		$tracking = new Tracking();
5096
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5097
5098
		return array_merge(
5099
			$properties,
5100
			array(
5101
				'_ui' => $tracks_identity['_ui'],
5102
				'_ut' => $tracks_identity['_ut'],
5103
			)
5104
		);
5105
	}
5106
5107
	/**
5108
	 * If the db version is showing something other that what we've got now, bump it to current.
5109
	 *
5110
	 * @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...
5111
	 */
5112
	public static function maybe_set_version_option() {
5113
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5114
		if ( JETPACK__VERSION != $version ) {
5115
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5116
5117
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5118
				/** This action is documented in class.jetpack.php */
5119
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5120
			}
5121
5122
			return true;
5123
		}
5124
		return false;
5125
	}
5126
5127
/* Client Server API */
5128
5129
	/**
5130
	 * Loads the Jetpack XML-RPC client.
5131
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5132
	 *
5133
	 * @deprecated since 7.7.0
5134
	 */
5135
	public static function load_xml_rpc_client() {
5136
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5137
	}
5138
5139
	/**
5140
	 * Resets the saved authentication state in between testing requests.
5141
	 */
5142
	public function reset_saved_auth_state() {
5143
		$this->rest_authentication_status = null;
5144
		$this->connection_manager->reset_saved_auth_state();
5145
	}
5146
5147
	/**
5148
	 * Verifies the signature of the current request.
5149
	 *
5150
	 * @deprecated since 7.7.0
5151
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5152
	 *
5153
	 * @return false|array
5154
	 */
5155
	public function verify_xml_rpc_signature() {
5156
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5157
		return self::connection()->verify_xml_rpc_signature();
5158
	}
5159
5160
	/**
5161
	 * Verifies the signature of the current request.
5162
	 *
5163
	 * This function has side effects and should not be used. Instead,
5164
	 * use the memoized version `->verify_xml_rpc_signature()`.
5165
	 *
5166
	 * @deprecated since 7.7.0
5167
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5168
	 * @internal
5169
	 */
5170
	private function internal_verify_xml_rpc_signature() {
5171
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5172
	}
5173
5174
	/**
5175
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5176
	 *
5177
	 * @deprecated since 7.7.0
5178
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5179
	 *
5180
	 * @param \WP_User|mixed $user     User object if authenticated.
5181
	 * @param string         $username Username.
5182
	 * @param string         $password Password string.
5183
	 * @return \WP_User|mixed Authenticated user or error.
5184
	 */
5185
	public function authenticate_jetpack( $user, $username, $password ) {
5186
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5187
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5188
	}
5189
5190
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5191
	// Uses the existing XMLRPC request signing implementation.
5192
	function wp_rest_authenticate( $user ) {
5193
		if ( ! empty( $user ) ) {
5194
			// Another authentication method is in effect.
5195
			return $user;
5196
		}
5197
5198
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5199
			// Nothing to do for this authentication method.
5200
			return null;
5201
		}
5202
5203
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5204
			// Nothing to do for this authentication method.
5205
			return null;
5206
		}
5207
5208
		// Ensure that we always have the request body available.  At this
5209
		// point, the WP REST API code to determine the request body has not
5210
		// run yet.  That code may try to read from 'php://input' later, but
5211
		// this can only be done once per request in PHP versions prior to 5.6.
5212
		// So we will go ahead and perform this read now if needed, and save
5213
		// the request body where both the Jetpack signature verification code
5214
		// and the WP REST API code can see it.
5215
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5216
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5217
		}
5218
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5219
5220
		// Only support specific request parameters that have been tested and
5221
		// are known to work with signature verification.  A different method
5222
		// can be passed to the WP REST API via the '?_method=' parameter if
5223
		// needed.
5224
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5225
			$this->rest_authentication_status = new WP_Error(
5226
				'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...
5227
				__( 'This request method is not supported.', 'jetpack' ),
5228
				array( 'status' => 400 )
5229
			);
5230
			return null;
5231
		}
5232
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5233
			$this->rest_authentication_status = new WP_Error(
5234
				'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...
5235
				__( 'This request method does not support body parameters.', 'jetpack' ),
5236
				array( 'status' => 400 )
5237
			);
5238
			return null;
5239
		}
5240
5241
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5242
5243
		if (
5244
			$verified &&
5245
			isset( $verified['type'] ) &&
5246
			'user' === $verified['type'] &&
5247
			! empty( $verified['user_id'] )
5248
		) {
5249
			// Authentication successful.
5250
			$this->rest_authentication_status = true;
5251
			return $verified['user_id'];
5252
		}
5253
5254
		// Something else went wrong.  Probably a signature error.
5255
		$this->rest_authentication_status = new WP_Error(
5256
			'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...
5257
			__( 'The request is not signed correctly.', 'jetpack' ),
5258
			array( 'status' => 400 )
5259
		);
5260
		return null;
5261
	}
5262
5263
	/**
5264
	 * Report authentication status to the WP REST API.
5265
	 *
5266
	 * @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...
5267
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5268
	 */
5269
	public function wp_rest_authentication_errors( $value ) {
5270
		if ( $value !== null ) {
5271
			return $value;
5272
		}
5273
		return $this->rest_authentication_status;
5274
	}
5275
5276
	/**
5277
	 * Add our nonce to this request.
5278
	 *
5279
	 * @deprecated since 7.7.0
5280
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5281
	 *
5282
	 * @param int    $timestamp Timestamp of the request.
5283
	 * @param string $nonce     Nonce string.
5284
	 */
5285
	public function add_nonce( $timestamp, $nonce ) {
5286
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5287
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5288
	}
5289
5290
	/**
5291
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5292
	 * Capture it here so we can verify the signature later.
5293
	 *
5294
	 * @deprecated since 7.7.0
5295
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5296
	 *
5297
	 * @param array $methods XMLRPC methods.
5298
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5299
	 */
5300
	public function xmlrpc_methods( $methods ) {
5301
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5302
		return $this->connection_manager->xmlrpc_methods( $methods );
5303
	}
5304
5305
	/**
5306
	 * Register additional public XMLRPC methods.
5307
	 *
5308
	 * @deprecated since 7.7.0
5309
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5310
	 *
5311
	 * @param array $methods Public XMLRPC methods.
5312
	 * @return array Public XMLRPC methods, with the getOptions one.
5313
	 */
5314
	public function public_xmlrpc_methods( $methods ) {
5315
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5316
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5317
	}
5318
5319
	/**
5320
	 * Handles a getOptions XMLRPC method call.
5321
	 *
5322
	 * @deprecated since 7.7.0
5323
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5324
	 *
5325
	 * @param array $args method call arguments.
5326
	 * @return array an amended XMLRPC server options array.
5327
	 */
5328
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5329
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5330
		return $this->connection_manager->jetpack_getOptions( $args );
5331
	}
5332
5333
	/**
5334
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5335
	 *
5336
	 * @deprecated since 7.7.0
5337
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5338
	 *
5339
	 * @param array $options Standard Core options.
5340
	 * @return array Amended options.
5341
	 */
5342
	public function xmlrpc_options( $options ) {
5343
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5344
		return $this->connection_manager->xmlrpc_options( $options );
5345
	}
5346
5347
	/**
5348
	 * Cleans nonces that were saved when calling ::add_nonce.
5349
	 *
5350
	 * @deprecated since 7.7.0
5351
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5352
	 *
5353
	 * @param bool $all whether to clean even non-expired nonces.
5354
	 */
5355
	public static function clean_nonces( $all = false ) {
5356
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5357
		return self::connection()->clean_nonces( $all );
5358
	}
5359
5360
	/**
5361
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5362
	 * SET: state( $key, $value );
5363
	 * GET: $value = state( $key );
5364
	 *
5365
	 * @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...
5366
	 * @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...
5367
	 * @param bool $restate private
5368
	 */
5369
	public static function state( $key = null, $value = null, $restate = false ) {
5370
		static $state = array();
5371
		static $path, $domain;
5372
		if ( ! isset( $path ) ) {
5373
			require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
5374
			$admin_url = Jetpack::admin_url();
5375
			$bits      = wp_parse_url( $admin_url );
5376
5377
			if ( is_array( $bits ) ) {
5378
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5379
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5380
			} else {
5381
				$path = $domain = null;
5382
			}
5383
		}
5384
5385
		// Extract state from cookies and delete cookies
5386
		if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
5387
			$yum = $_COOKIE[ 'jetpackState' ];
5388
			unset( $_COOKIE[ 'jetpackState' ] );
5389
			foreach ( $yum as $k => $v ) {
5390
				if ( strlen( $v ) )
5391
					$state[ $k ] = $v;
5392
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5393
			}
5394
		}
5395
5396
		if ( $restate ) {
5397
			foreach ( $state as $k => $v ) {
5398
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5399
			}
5400
			return;
5401
		}
5402
5403
		// Get a state variable
5404
		if ( isset( $key ) && ! isset( $value ) ) {
5405
			if ( array_key_exists( $key, $state ) )
5406
				return $state[ $key ];
5407
			return null;
5408
		}
5409
5410
		// Set a state variable
5411
		if ( isset ( $key ) && isset( $value ) ) {
5412
			if( is_array( $value ) && isset( $value[0] ) ) {
5413
				$value = $value[0];
5414
			}
5415
			$state[ $key ] = $value;
5416
			setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5417
		}
5418
	}
5419
5420
	public static function restate() {
5421
		Jetpack::state( null, null, true );
5422
	}
5423
5424
	public static function check_privacy( $file ) {
5425
		static $is_site_publicly_accessible = null;
5426
5427
		if ( is_null( $is_site_publicly_accessible ) ) {
5428
			$is_site_publicly_accessible = false;
5429
5430
			$rpc = new Jetpack_IXR_Client();
5431
5432
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5433
			if ( $success ) {
5434
				$response = $rpc->getResponse();
5435
				if ( $response ) {
5436
					$is_site_publicly_accessible = true;
5437
				}
5438
			}
5439
5440
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5441
		}
5442
5443
		if ( $is_site_publicly_accessible ) {
5444
			return;
5445
		}
5446
5447
		$module_slug = self::get_module_slug( $file );
5448
5449
		$privacy_checks = Jetpack::state( 'privacy_checks' );
5450
		if ( ! $privacy_checks ) {
5451
			$privacy_checks = $module_slug;
5452
		} else {
5453
			$privacy_checks .= ",$module_slug";
5454
		}
5455
5456
		Jetpack::state( 'privacy_checks', $privacy_checks );
5457
	}
5458
5459
	/**
5460
	 * Helper method for multicall XMLRPC.
5461
	 */
5462
	public static function xmlrpc_async_call() {
5463
		global $blog_id;
5464
		static $clients = array();
5465
5466
		$client_blog_id = is_multisite() ? $blog_id : 0;
5467
5468
		if ( ! isset( $clients[$client_blog_id] ) ) {
5469
			$clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
5470
			if ( function_exists( 'ignore_user_abort' ) ) {
5471
				ignore_user_abort( true );
5472
			}
5473
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5474
		}
5475
5476
		$args = func_get_args();
5477
5478
		if ( ! empty( $args[0] ) ) {
5479
			call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
5480
		} elseif ( is_multisite() ) {
5481
			foreach ( $clients as $client_blog_id => $client ) {
5482
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5483
					continue;
5484
				}
5485
5486
				$switch_success = switch_to_blog( $client_blog_id, true );
5487
				if ( ! $switch_success ) {
5488
					continue;
5489
				}
5490
5491
				flush();
5492
				$client->query();
5493
5494
				restore_current_blog();
5495
			}
5496
		} else {
5497
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5498
				flush();
5499
				$clients[0]->query();
5500
			}
5501
		}
5502
	}
5503
5504
	public static function staticize_subdomain( $url ) {
5505
5506
		// Extract hostname from URL
5507
		$host = parse_url( $url, PHP_URL_HOST );
5508
5509
		// Explode hostname on '.'
5510
		$exploded_host = explode( '.', $host );
5511
5512
		// Retrieve the name and TLD
5513
		if ( count( $exploded_host ) > 1 ) {
5514
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5515
			$tld = $exploded_host[ count( $exploded_host ) - 1 ];
5516
			// Rebuild domain excluding subdomains
5517
			$domain = $name . '.' . $tld;
5518
		} else {
5519
			$domain = $host;
5520
		}
5521
		// Array of Automattic domains
5522
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5523
5524
		// Return $url if not an Automattic domain
5525
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5526
			return $url;
5527
		}
5528
5529
		if ( is_ssl() ) {
5530
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5531
		}
5532
5533
		srand( crc32( basename( $url ) ) );
5534
		$static_counter = rand( 0, 2 );
5535
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5536
5537
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5538
	}
5539
5540
/* JSON API Authorization */
5541
5542
	/**
5543
	 * Handles the login action for Authorizing the JSON API
5544
	 */
5545
	function login_form_json_api_authorization() {
5546
		$this->verify_json_api_authorization_request();
5547
5548
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5549
5550
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5551
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5552
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5553
	}
5554
5555
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5556
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5557
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5558
			return $url;
5559
		}
5560
5561
		$parsed_url = parse_url( $url );
5562
		$url = strtok( $url, '?' );
5563
		$url = "$url?{$_SERVER['QUERY_STRING']}";
5564
		if ( ! empty( $parsed_url['query'] ) )
5565
			$url .= "&{$parsed_url['query']}";
5566
5567
		return $url;
5568
	}
5569
5570
	// Make sure the POSTed request is handled by the same action
5571
	function preserve_action_in_login_form_for_json_api_authorization() {
5572
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5573
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5574
	}
5575
5576
	// If someone logs in to approve API access, store the Access Code in usermeta
5577
	function store_json_api_authorization_token( $user_login, $user ) {
5578
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5579
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5580
		$token = wp_generate_password( 32, false );
5581
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5582
	}
5583
5584
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
5585
	function allow_wpcom_public_api_domain( $domains ) {
5586
		$domains[] = 'public-api.wordpress.com';
5587
		return $domains;
5588
	}
5589
5590
	static function is_redirect_encoded( $redirect_url ) {
5591
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5592
	}
5593
5594
	// Add all wordpress.com environments to the safe redirect whitelist
5595
	function allow_wpcom_environments( $domains ) {
5596
		$domains[] = 'wordpress.com';
5597
		$domains[] = 'wpcalypso.wordpress.com';
5598
		$domains[] = 'horizon.wordpress.com';
5599
		$domains[] = 'calypso.localhost';
5600
		return $domains;
5601
	}
5602
5603
	// Add the Access Code details to the public-api.wordpress.com redirect
5604
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5605
		return add_query_arg(
5606
			urlencode_deep(
5607
				array(
5608
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5609
					'jetpack-user-id' => (int) $user->ID,
5610
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5611
				)
5612
			),
5613
			$redirect_to
5614
		);
5615
	}
5616
5617
5618
	/**
5619
	 * Verifies the request by checking the signature
5620
	 *
5621
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5622
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5623
	 *
5624
	 * @param null|array $environment
5625
	 */
5626
	function verify_json_api_authorization_request( $environment = null ) {
5627
		$environment = is_null( $environment )
5628
			? $_REQUEST
5629
			: $environment;
5630
5631
		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...
5632
		$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...
5633
		if ( ! $token || empty( $token->secret ) ) {
5634
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
5635
		}
5636
5637
		$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' );
5638
5639
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5640
		if ( Jetpack::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5641
			/**
5642
			 * Jetpack authorisation request Error.
5643
			 *
5644
			 * @since 7.5.0
5645
			 *
5646
			 */
5647
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5648
			$die_error = sprintf(
5649
				/* translators: %s is a URL */
5650
				__( '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' ),
5651
				'https://jetpack.com/support/double-encoding/'
5652
			);
5653
		}
5654
5655
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5656
5657
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5658
			$signature = $jetpack_signature->sign_request(
5659
				$environment['token'],
5660
				$environment['timestamp'],
5661
				$environment['nonce'],
5662
				'',
5663
				'GET',
5664
				$environment['jetpack_json_api_original_query'],
5665
				null,
5666
				true
5667
			);
5668
		} else {
5669
			$signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
5670
		}
5671
5672
		if ( ! $signature ) {
5673
			wp_die( $die_error );
5674
		} else if ( is_wp_error( $signature ) ) {
5675
			wp_die( $die_error );
5676
		} else if ( ! hash_equals( $signature, $environment['signature'] ) ) {
5677
			if ( is_ssl() ) {
5678
				// 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
5679
				$signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
5680
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5681
					wp_die( $die_error );
5682
				}
5683
			} else {
5684
				wp_die( $die_error );
5685
			}
5686
		}
5687
5688
		$timestamp = (int) $environment['timestamp'];
5689
		$nonce     = stripslashes( (string) $environment['nonce'] );
5690
5691
		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...
5692
			// De-nonce the nonce, at least for 5 minutes.
5693
			// 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)
5694
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5695
			if ( $old_nonce_time < time() - 300 ) {
5696
				wp_die( __( 'The authorization process expired.  Please go back and try again.' , 'jetpack' ) );
5697
			}
5698
		}
5699
5700
		$data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5701
		$data_filters = array(
5702
			'state'        => 'opaque',
5703
			'client_id'    => 'int',
5704
			'client_title' => 'string',
5705
			'client_image' => 'url',
5706
		);
5707
5708
		foreach ( $data_filters as $key => $sanitation ) {
5709
			if ( ! isset( $data->$key ) ) {
5710
				wp_die( $die_error );
5711
			}
5712
5713
			switch ( $sanitation ) {
5714
			case 'int' :
5715
				$this->json_api_authorization_request[$key] = (int) $data->$key;
5716
				break;
5717
			case 'opaque' :
5718
				$this->json_api_authorization_request[$key] = (string) $data->$key;
5719
				break;
5720
			case 'string' :
5721
				$this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
5722
				break;
5723
			case 'url' :
5724
				$this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
5725
				break;
5726
			}
5727
		}
5728
5729
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
5730
			wp_die( $die_error );
5731
		}
5732
	}
5733
5734
	function login_message_json_api_authorization( $message ) {
5735
		return '<p class="message">' . sprintf(
5736
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.' , 'jetpack' ),
5737
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
5738
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
5739
	}
5740
5741
	/**
5742
	 * Get $content_width, but with a <s>twist</s> filter.
5743
	 */
5744
	public static function get_content_width() {
5745
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5746
			? $GLOBALS['content_width']
5747
			: false;
5748
		/**
5749
		 * Filter the Content Width value.
5750
		 *
5751
		 * @since 2.2.3
5752
		 *
5753
		 * @param string $content_width Content Width value.
5754
		 */
5755
		return apply_filters( 'jetpack_content_width', $content_width );
5756
	}
5757
5758
	/**
5759
	 * Pings the WordPress.com Mirror Site for the specified options.
5760
	 *
5761
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
5762
	 *
5763
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5764
	 */
5765
	public function get_cloud_site_options( $option_names ) {
5766
		$option_names = array_filter( (array) $option_names, 'is_string' );
5767
5768
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
5769
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
5770
		if ( $xml->isError() ) {
5771
			return array(
5772
				'error_code' => $xml->getErrorCode(),
5773
				'error_msg'  => $xml->getErrorMessage(),
5774
			);
5775
		}
5776
		$cloud_site_options = $xml->getResponse();
5777
5778
		return $cloud_site_options;
5779
	}
5780
5781
	/**
5782
	 * Checks if the site is currently in an identity crisis.
5783
	 *
5784
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5785
	 */
5786
	public static function check_identity_crisis() {
5787
		if ( ! Jetpack::is_active() || Jetpack::is_development_mode() || ! self::validate_sync_error_idc_option() ) {
5788
			return false;
5789
		}
5790
5791
		return Jetpack_Options::get_option( 'sync_error_idc' );
5792
	}
5793
5794
	/**
5795
	 * Checks whether the home and siteurl specifically are whitelisted
5796
	 * Written so that we don't have re-check $key and $value params every time
5797
	 * we want to check if this site is whitelisted, for example in footer.php
5798
	 *
5799
	 * @since  3.8.0
5800
	 * @return bool True = already whitelisted False = not whitelisted
5801
	 */
5802
	public static function is_staging_site() {
5803
		$is_staging = false;
5804
5805
		$known_staging = array(
5806
			'urls' => array(
5807
				'#\.staging\.wpengine\.com$#i', // WP Engine
5808
				'#\.staging\.kinsta\.com$#i',   // Kinsta.com
5809
				'#\.stage\.site$#i'             // DreamPress
5810
			),
5811
			'constants' => array(
5812
				'IS_WPE_SNAPSHOT',      // WP Engine
5813
				'KINSTA_DEV_ENV',       // Kinsta.com
5814
				'WPSTAGECOACH_STAGING', // WP Stagecoach
5815
				'JETPACK_STAGING_MODE', // Generic
5816
			)
5817
		);
5818
		/**
5819
		 * Filters the flags of known staging sites.
5820
		 *
5821
		 * @since 3.9.0
5822
		 *
5823
		 * @param array $known_staging {
5824
		 *     An array of arrays that each are used to check if the current site is staging.
5825
		 *     @type array $urls      URLs of staging sites in regex to check against site_url.
5826
		 *     @type array $constants PHP constants of known staging/developement environments.
5827
		 *  }
5828
		 */
5829
		$known_staging = apply_filters( 'jetpack_known_staging', $known_staging );
5830
5831
		if ( isset( $known_staging['urls'] ) ) {
5832
			foreach ( $known_staging['urls'] as $url ){
5833
				if ( preg_match( $url, site_url() ) ) {
5834
					$is_staging = true;
5835
					break;
5836
				}
5837
			}
5838
		}
5839
5840
		if ( isset( $known_staging['constants'] ) ) {
5841
			foreach ( $known_staging['constants'] as $constant ) {
5842
				if ( defined( $constant ) && constant( $constant ) ) {
5843
					$is_staging = true;
5844
				}
5845
			}
5846
		}
5847
5848
		// Last, let's check if sync is erroring due to an IDC. If so, set the site to staging mode.
5849
		if ( ! $is_staging && self::validate_sync_error_idc_option() ) {
5850
			$is_staging = true;
5851
		}
5852
5853
		/**
5854
		 * Filters is_staging_site check.
5855
		 *
5856
		 * @since 3.9.0
5857
		 *
5858
		 * @param bool $is_staging If the current site is a staging site.
5859
		 */
5860
		return apply_filters( 'jetpack_is_staging_site', $is_staging );
5861
	}
5862
5863
	/**
5864
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
5865
	 *
5866
	 * @since 4.4.0
5867
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
5868
	 *
5869
	 * @return bool
5870
	 */
5871
	public static function validate_sync_error_idc_option() {
5872
		$is_valid = false;
5873
5874
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
5875
		if ( false === $idc_allowed ) {
5876
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
5877
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
5878
				$json = json_decode( wp_remote_retrieve_body( $response ) );
5879
				$idc_allowed = isset( $json, $json->result ) && $json->result ? '1' : '0';
5880
				$transient_duration = HOUR_IN_SECONDS;
5881
			} else {
5882
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
5883
				$idc_allowed = '1';
5884
				$transient_duration = 5 * MINUTE_IN_SECONDS;
5885
			}
5886
5887
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
5888
		}
5889
5890
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
5891
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
5892
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
5893
			$local_options = self::get_sync_error_idc_option();
5894
			if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
5895
				$is_valid = true;
5896
			}
5897
		}
5898
5899
		/**
5900
		 * Filters whether the sync_error_idc option is valid.
5901
		 *
5902
		 * @since 4.4.0
5903
		 *
5904
		 * @param bool $is_valid If the sync_error_idc is valid or not.
5905
		 */
5906
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
5907
5908
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
5909
			// Since the option exists, and did not validate, delete it
5910
			Jetpack_Options::delete_option( 'sync_error_idc' );
5911
		}
5912
5913
		return $is_valid;
5914
	}
5915
5916
	/**
5917
	 * Normalizes a url by doing three things:
5918
	 *  - Strips protocol
5919
	 *  - Strips www
5920
	 *  - Adds a trailing slash
5921
	 *
5922
	 * @since 4.4.0
5923
	 * @param string $url
5924
	 * @return WP_Error|string
5925
	 */
5926
	public static function normalize_url_protocol_agnostic( $url ) {
5927
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5928
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5929
			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...
5930
		}
5931
5932
		// Strip www and protocols
5933
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5934
		return $url;
5935
	}
5936
5937
	/**
5938
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
5939
	 *
5940
	 * @since 4.4.0
5941
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
5942
	 *
5943
	 * @param array $response
5944
	 * @return array Array of the local urls, wpcom urls, and error code
5945
	 */
5946
	public static function get_sync_error_idc_option( $response = array() ) {
5947
		// Since the local options will hit the database directly, store the values
5948
		// in a transient to allow for autoloading and caching on subsequent views.
5949
		$local_options = get_transient( 'jetpack_idc_local' );
5950
		if ( false === $local_options ) {
5951
			$local_options = array(
5952
				'home'    => Functions::home_url(),
5953
				'siteurl' => Functions::site_url(),
5954
			);
5955
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
5956
		}
5957
5958
		$options = array_merge( $local_options, $response );
5959
5960
		$returned_values = array();
5961
		foreach( $options as $key => $option ) {
5962
			if ( 'error_code' === $key ) {
5963
				$returned_values[ $key ] = $option;
5964
				continue;
5965
			}
5966
5967
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
5968
				continue;
5969
			}
5970
5971
			$returned_values[ $key ] = $normalized_url;
5972
		}
5973
5974
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
5975
5976
		return $returned_values;
5977
	}
5978
5979
	/**
5980
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
5981
	 * If set to true, the site will be put into staging mode.
5982
	 *
5983
	 * @since 4.3.2
5984
	 * @return bool
5985
	 */
5986
	public static function sync_idc_optin() {
5987
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
5988
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
5989
		} else {
5990
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
5991
		}
5992
5993
		/**
5994
		 * Allows sites to optin to IDC mitigation which blocks the site from syncing to WordPress.com when the home
5995
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
5996
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
5997
		 *
5998
		 * @since 4.3.2
5999
		 *
6000
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6001
		 */
6002
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6003
	}
6004
6005
	/**
6006
	 * Maybe Use a .min.css stylesheet, maybe not.
6007
	 *
6008
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6009
	 */
6010
	public static function maybe_min_asset( $url, $path, $plugin ) {
6011
		// Short out on things trying to find actual paths.
6012
		if ( ! $path || empty( $plugin ) ) {
6013
			return $url;
6014
		}
6015
6016
		$path = ltrim( $path, '/' );
6017
6018
		// Strip out the abspath.
6019
		$base = dirname( plugin_basename( $plugin ) );
6020
6021
		// Short out on non-Jetpack assets.
6022
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6023
			return $url;
6024
		}
6025
6026
		// File name parsing.
6027
		$file              = "{$base}/{$path}";
6028
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6029
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6030
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6031
		$extension         = array_shift( $file_name_parts_r );
6032
6033
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6034
			// Already pointing at the minified version.
6035
			if ( 'min' === $file_name_parts_r[0] ) {
6036
				return $url;
6037
			}
6038
6039
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6040
			if ( file_exists( $min_full_path ) ) {
6041
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6042
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6043
				if ( 'css' === $extension ) {
6044
					$key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6045
					self::$min_assets[ $key ] = $path;
6046
				}
6047
			}
6048
		}
6049
6050
		return $url;
6051
	}
6052
6053
	/**
6054
	 * If the asset is minified, let's flag .min as the suffix.
6055
	 *
6056
	 * Attached to `style_loader_src` filter.
6057
	 *
6058
	 * @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...
6059
	 * @param string $handle The registered handle of the script in question.
6060
	 * @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...
6061
	 */
6062
	public static function set_suffix_on_min( $src, $handle ) {
6063
		if ( false === strpos( $src, '.min.css' ) ) {
6064
			return $src;
6065
		}
6066
6067
		if ( ! empty( self::$min_assets ) ) {
6068
			foreach ( self::$min_assets as $file => $path ) {
6069
				if ( false !== strpos( $src, $file ) ) {
6070
					wp_style_add_data( $handle, 'suffix', '.min' );
6071
					return $src;
6072
				}
6073
			}
6074
		}
6075
6076
		return $src;
6077
	}
6078
6079
	/**
6080
	 * Maybe inlines a stylesheet.
6081
	 *
6082
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6083
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6084
	 *
6085
	 * Attached to `style_loader_tag` filter.
6086
	 *
6087
	 * @param string $tag The tag that would link to the external asset.
6088
	 * @param string $handle The registered handle of the script in question.
6089
	 *
6090
	 * @return string
6091
	 */
6092
	public static function maybe_inline_style( $tag, $handle ) {
6093
		global $wp_styles;
6094
		$item = $wp_styles->registered[ $handle ];
6095
6096
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6097
			return $tag;
6098
		}
6099
6100
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6101
			$href = $matches[1];
6102
			// Strip off query string
6103
			if ( $pos = strpos( $href, '?' ) ) {
6104
				$href = substr( $href, 0, $pos );
6105
			}
6106
			// Strip off fragment
6107
			if ( $pos = strpos( $href, '#' ) ) {
6108
				$href = substr( $href, 0, $pos );
6109
			}
6110
		} else {
6111
			return $tag;
6112
		}
6113
6114
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6115
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6116
			return $tag;
6117
		}
6118
6119
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6120
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6121
			// And this isn't the pass that actually deals with the RTL version...
6122
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6123
				// Short out, as the RTL version will deal with it in a moment.
6124
				return $tag;
6125
			}
6126
		}
6127
6128
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6129
		$css  = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
6130
		if ( $css ) {
6131
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6132
			if ( empty( $item->extra['after'] ) ) {
6133
				wp_add_inline_style( $handle, $css );
6134
			} else {
6135
				array_unshift( $item->extra['after'], $css );
6136
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6137
			}
6138
		}
6139
6140
		return $tag;
6141
	}
6142
6143
	/**
6144
	 * Loads a view file from the views
6145
	 *
6146
	 * Data passed in with the $data parameter will be available in the
6147
	 * template file as $data['value']
6148
	 *
6149
	 * @param string $template - Template file to load
6150
	 * @param array $data - Any data to pass along to the template
6151
	 * @return boolean - If template file was found
6152
	 **/
6153
	public function load_view( $template, $data = array() ) {
6154
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6155
6156
		if( file_exists( $views_dir . $template ) ) {
6157
			require_once( $views_dir . $template );
6158
			return true;
6159
		}
6160
6161
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6162
		return false;
6163
	}
6164
6165
	/**
6166
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6167
	 */
6168
	public function deprecated_hooks() {
6169
		global $wp_filter;
6170
6171
		/*
6172
		 * Format:
6173
		 * deprecated_filter_name => replacement_name
6174
		 *
6175
		 * If there is no replacement, use null for replacement_name
6176
		 */
6177
		$deprecated_list = array(
6178
			'jetpack_bail_on_shortcode'                              => 'jetpack_shortcodes_to_include',
6179
			'wpl_sharing_2014_1'                                     => null,
6180
			'jetpack-tools-to-include'                               => 'jetpack_tools_to_include',
6181
			'jetpack_identity_crisis_options_to_check'               => null,
6182
			'update_option_jetpack_single_user_site'                 => null,
6183
			'audio_player_default_colors'                            => null,
6184
			'add_option_jetpack_featured_images_enabled'             => null,
6185
			'add_option_jetpack_update_details'                      => null,
6186
			'add_option_jetpack_updates'                             => null,
6187
			'add_option_jetpack_network_name'                        => null,
6188
			'add_option_jetpack_network_allow_new_registrations'     => null,
6189
			'add_option_jetpack_network_add_new_users'               => null,
6190
			'add_option_jetpack_network_site_upload_space'           => null,
6191
			'add_option_jetpack_network_upload_file_types'           => null,
6192
			'add_option_jetpack_network_enable_administration_menus' => null,
6193
			'add_option_jetpack_is_multi_site'                       => null,
6194
			'add_option_jetpack_is_main_network'                     => null,
6195
			'add_option_jetpack_main_network_site'                   => null,
6196
			'jetpack_sync_all_registered_options'                    => null,
6197
			'jetpack_has_identity_crisis'                            => 'jetpack_sync_error_idc_validation',
6198
			'jetpack_is_post_mailable'                               => null,
6199
			'jetpack_seo_site_host'                                  => null,
6200
			'jetpack_installed_plugin'                               => 'jetpack_plugin_installed',
6201
			'jetpack_holiday_snow_option_name'                       => null,
6202
			'jetpack_holiday_chance_of_snow'                         => null,
6203
			'jetpack_holiday_snow_js_url'                            => null,
6204
			'jetpack_is_holiday_snow_season'                         => null,
6205
			'jetpack_holiday_snow_option_updated'                    => null,
6206
			'jetpack_holiday_snowing'                                => null,
6207
			'jetpack_sso_auth_cookie_expirtation'                    => 'jetpack_sso_auth_cookie_expiration',
6208
			'jetpack_cache_plans'                                    => null,
6209
			'jetpack_updated_theme'                                  => 'jetpack_updated_themes',
6210
			'jetpack_lazy_images_skip_image_with_atttributes'        => 'jetpack_lazy_images_skip_image_with_attributes',
6211
			'jetpack_enable_site_verification'                       => null,
6212
			'can_display_jetpack_manage_notice'                      => null,
6213
			// Removed in Jetpack 7.3.0
6214
			'atd_load_scripts'                                       => null,
6215
			'atd_http_post_timeout'                                  => null,
6216
			'atd_http_post_error'                                    => null,
6217
			'atd_service_domain'                                     => null,
6218
			'jetpack_widget_authors_exclude'                         => 'jetpack_widget_authors_params',
6219
		);
6220
6221
		// This is a silly loop depth. Better way?
6222
		foreach( $deprecated_list AS $hook => $hook_alt ) {
6223
			if ( has_action( $hook ) ) {
6224
				foreach( $wp_filter[ $hook ] AS $func => $values ) {
6225
					foreach( $values AS $hooked ) {
6226
						if ( is_callable( $hooked['function'] ) ) {
6227
							$function_name = 'an anonymous function';
6228
						} else {
6229
							$function_name = $hooked['function'];
6230
						}
6231
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6232
					}
6233
				}
6234
			}
6235
		}
6236
	}
6237
6238
	/**
6239
	 * Converts any url in a stylesheet, to the correct absolute url.
6240
	 *
6241
	 * Considerations:
6242
	 *  - Normal, relative URLs     `feh.png`
6243
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6244
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6245
	 *  - Absolute URLs             `http://domain.com/feh.png`
6246
	 *  - Domain root relative URLs `/feh.png`
6247
	 *
6248
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6249
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6250
	 *
6251
	 * @return mixed|string
6252
	 */
6253
	public static function absolutize_css_urls( $css, $css_file_url ) {
6254
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6255
		$css_dir = dirname( $css_file_url );
6256
		$p       = parse_url( $css_dir );
6257
		$domain  = sprintf(
6258
					'%1$s//%2$s%3$s%4$s',
6259
					isset( $p['scheme'] )           ? "{$p['scheme']}:" : '',
6260
					isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6261
					$p['host'],
6262
					isset( $p['port'] )             ? ":{$p['port']}" : ''
6263
				);
6264
6265
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6266
			$find = $replace = array();
6267
			foreach ( $matches as $match ) {
6268
				$url = trim( $match['path'], "'\" \t" );
6269
6270
				// If this is a data url, we don't want to mess with it.
6271
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6272
					continue;
6273
				}
6274
6275
				// If this is an absolute or protocol-agnostic url,
6276
				// we don't want to mess with it.
6277
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6278
					continue;
6279
				}
6280
6281
				switch ( substr( $url, 0, 1 ) ) {
6282
					case '/':
6283
						$absolute = $domain . $url;
6284
						break;
6285
					default:
6286
						$absolute = $css_dir . '/' . $url;
6287
				}
6288
6289
				$find[]    = $match[0];
6290
				$replace[] = sprintf( 'url("%s")', $absolute );
6291
			}
6292
			$css = str_replace( $find, $replace, $css );
6293
		}
6294
6295
		return $css;
6296
	}
6297
6298
	/**
6299
	 * This methods removes all of the registered css files on the front end
6300
	 * from Jetpack in favor of using a single file. In effect "imploding"
6301
	 * all the files into one file.
6302
	 *
6303
	 * Pros:
6304
	 * - Uses only ONE css asset connection instead of 15
6305
	 * - Saves a minimum of 56k
6306
	 * - Reduces server load
6307
	 * - Reduces time to first painted byte
6308
	 *
6309
	 * Cons:
6310
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6311
	 *		should not cause any issues with themes.
6312
	 * - Plugins/themes dequeuing styles no longer do anything. See
6313
	 *		jetpack_implode_frontend_css filter for a workaround
6314
	 *
6315
	 * For some situations developers may wish to disable css imploding and
6316
	 * instead operate in legacy mode where each file loads seperately and
6317
	 * can be edited individually or dequeued. This can be accomplished with
6318
	 * the following line:
6319
	 *
6320
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6321
	 *
6322
	 * @since 3.2
6323
	 **/
6324
	public function implode_frontend_css( $travis_test = false ) {
6325
		$do_implode = true;
6326
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6327
			$do_implode = false;
6328
		}
6329
6330
		// Do not implode CSS when the page loads via the AMP plugin.
6331
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6332
			$do_implode = false;
6333
		}
6334
6335
		/**
6336
		 * Allow CSS to be concatenated into a single jetpack.css file.
6337
		 *
6338
		 * @since 3.2.0
6339
		 *
6340
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6341
		 */
6342
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6343
6344
		// Do not use the imploded file when default behavior was altered through the filter
6345
		if ( ! $do_implode ) {
6346
			return;
6347
		}
6348
6349
		// We do not want to use the imploded file in dev mode, or if not connected
6350
		if ( Jetpack::is_development_mode() || ! self::is_active() ) {
6351
			if ( ! $travis_test ) {
6352
				return;
6353
			}
6354
		}
6355
6356
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6357
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6358
			return;
6359
		}
6360
6361
		/*
6362
		 * Now we assume Jetpack is connected and able to serve the single
6363
		 * file.
6364
		 *
6365
		 * In the future there will be a check here to serve the file locally
6366
		 * or potentially from the Jetpack CDN
6367
		 *
6368
		 * For now:
6369
		 * - Enqueue a single imploded css file
6370
		 * - Zero out the style_loader_tag for the bundled ones
6371
		 * - Be happy, drink scotch
6372
		 */
6373
6374
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6375
6376
		$version = Jetpack::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6377
6378
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6379
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6380
	}
6381
6382
	function concat_remove_style_loader_tag( $tag, $handle ) {
6383
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6384
			$tag = '';
6385
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6386
				$tag = "<!-- `" . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6387
			}
6388
		}
6389
6390
		return $tag;
6391
	}
6392
6393
	/**
6394
	 * Add an async attribute to scripts that can be loaded asynchronously.
6395
	 * https://www.w3schools.com/tags/att_script_async.asp
6396
	 *
6397
	 * @since 7.7.0
6398
	 *
6399
	 * @param string $tag    The <script> tag for the enqueued script.
6400
	 * @param string $handle The script's registered handle.
6401
	 * @param string $src    The script's source URL.
6402
	 */
6403
	public function script_add_async( $tag, $handle, $src ) {
6404
		if ( in_array( $handle, $this->async_script_handles, true ) ) {
6405
			return preg_replace( '/^<script /i', '<script async ', $tag );
6406
		}
6407
6408
		return $tag;
6409
	}
6410
6411
	/*
6412
	 * Check the heartbeat data
6413
	 *
6414
	 * Organizes the heartbeat data by severity.  For example, if the site
6415
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6416
	 *
6417
	 * Data will be added to "caution" array, if it either:
6418
	 *  - Out of date Jetpack version
6419
	 *  - Out of date WP version
6420
	 *  - Out of date PHP version
6421
	 *
6422
	 * $return array $filtered_data
6423
	 */
6424
	public static function jetpack_check_heartbeat_data() {
6425
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6426
6427
		$good    = array();
6428
		$caution = array();
6429
		$bad     = array();
6430
6431
		foreach ( $raw_data as $stat => $value ) {
6432
6433
			// Check jetpack version
6434
			if ( 'version' == $stat ) {
6435
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6436
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__VERSION;
6437
					continue;
6438
				}
6439
			}
6440
6441
			// Check WP version
6442
			if ( 'wp-version' == $stat ) {
6443
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6444
					$caution[ $stat ] = $value . " - min supported is " . JETPACK__MINIMUM_WP_VERSION;
6445
					continue;
6446
				}
6447
			}
6448
6449
			// Check PHP version
6450
			if ( 'php-version' == $stat ) {
6451
				if ( version_compare( PHP_VERSION, '5.2.4', '<' ) ) {
6452
					$caution[ $stat ] = $value . " - min supported is 5.2.4";
6453
					continue;
6454
				}
6455
			}
6456
6457
			// Check ID crisis
6458
			if ( 'identitycrisis' == $stat ) {
6459
				if ( 'yes' == $value ) {
6460
					$bad[ $stat ] = $value;
6461
					continue;
6462
				}
6463
			}
6464
6465
			// The rest are good :)
6466
			$good[ $stat ] = $value;
6467
		}
6468
6469
		$filtered_data = array(
6470
			'good'    => $good,
6471
			'caution' => $caution,
6472
			'bad'     => $bad
6473
		);
6474
6475
		return $filtered_data;
6476
	}
6477
6478
6479
	/*
6480
	 * This method is used to organize all options that can be reset
6481
	 * without disconnecting Jetpack.
6482
	 *
6483
	 * It is used in class.jetpack-cli.php to reset options
6484
	 *
6485
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6486
	 *
6487
	 * @return array of options to delete.
6488
	 */
6489
	public static function get_jetpack_options_for_reset() {
6490
		return Jetpack_Options::get_options_for_reset();
6491
	}
6492
6493
	/*
6494
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6495
	 * so we can bring them directly to their site in calypso.
6496
	 *
6497
	 * @param string | url
6498
	 * @return string | url without the guff
6499
	 */
6500
	public static function build_raw_urls( $url ) {
6501
		$strip_http = '/.*?:\/\//i';
6502
		$url = preg_replace( $strip_http, '', $url  );
6503
		$url = str_replace( '/', '::', $url );
6504
		return $url;
6505
	}
6506
6507
	/**
6508
	 * Stores and prints out domains to prefetch for page speed optimization.
6509
	 *
6510
	 * @param mixed $new_urls
6511
	 */
6512
	public static function dns_prefetch( $new_urls = null ) {
6513
		static $prefetch_urls = array();
6514
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6515
			echo "\r\n";
6516
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6517
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6518
			}
6519
		} elseif ( ! empty( $new_urls ) ) {
6520
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6521
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6522
			}
6523
			foreach ( (array) $new_urls as $this_new_url ) {
6524
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6525
			}
6526
			$prefetch_urls = array_unique( $prefetch_urls );
6527
		}
6528
	}
6529
6530
	public function wp_dashboard_setup() {
6531
		if ( self::is_active() ) {
6532
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6533
		}
6534
6535
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6536
			$jetpack_logo = new Jetpack_Logo();
6537
			$widget_title = sprintf(
6538
				wp_kses(
6539
					/* translators: Placeholder is a Jetpack logo. */
6540
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6541
					array( 'span' => array() )
6542
				),
6543
				$jetpack_logo->get_jp_emblem( true )
6544
			);
6545
6546
			wp_add_dashboard_widget(
6547
				'jetpack_summary_widget',
6548
				$widget_title,
6549
				array( __CLASS__, 'dashboard_widget' )
6550
			);
6551
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6552
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6553
6554
			// If we're inactive and not in development mode, sort our box to the top.
6555
			if ( ! self::is_active() && ! self::is_development_mode() ) {
6556
				global $wp_meta_boxes;
6557
6558
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6559
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6560
6561
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6562
			}
6563
		}
6564
	}
6565
6566
	/**
6567
	 * @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...
6568
	 * @return mixed
6569
	 */
6570
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6571
		if ( ! is_array( $sorted ) ) {
6572
			return $sorted;
6573
		}
6574
6575
		foreach ( $sorted as $box_context => $ids ) {
6576
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6577
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6578
				continue;
6579
			}
6580
6581
			$ids_array = explode( ',', $ids );
6582
			$key = array_search( 'dashboard_stats', $ids_array );
6583
6584
			if ( false !== $key ) {
6585
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6586
				$ids_array[ $key ] = 'jetpack_summary_widget';
6587
				$sorted[ $box_context ] = implode( ',', $ids_array );
6588
				// We've found it, stop searching, and just return.
6589
				break;
6590
			}
6591
		}
6592
6593
		return $sorted;
6594
	}
6595
6596
	public static function dashboard_widget() {
6597
		/**
6598
		 * Fires when the dashboard is loaded.
6599
		 *
6600
		 * @since 3.4.0
6601
		 */
6602
		do_action( 'jetpack_dashboard_widget' );
6603
	}
6604
6605
	public static function dashboard_widget_footer() {
6606
		?>
6607
		<footer>
6608
6609
		<div class="protect">
6610
			<?php if ( Jetpack::is_module_active( 'protect' ) ) : ?>
6611
				<h3><?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?></h3>
6612
				<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>
6613
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! self::is_development_mode() ) : ?>
6614
				<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' ); ?>">
6615
					<?php esc_html_e( 'Activate Protect', 'jetpack' ); ?>
6616
				</a>
6617
			<?php else : ?>
6618
				<?php esc_html_e( 'Protect is inactive.', 'jetpack' ); ?>
6619
			<?php endif; ?>
6620
		</div>
6621
6622
		<div class="akismet">
6623
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6624
				<h3><?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?></h3>
6625
				<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>
6626
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6627
				<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">
6628
					<?php esc_html_e( 'Activate Akismet', 'jetpack' ); ?>
6629
				</a>
6630
			<?php else : ?>
6631
				<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>
6632
			<?php endif; ?>
6633
		</div>
6634
6635
		</footer>
6636
		<?php
6637
	}
6638
6639
	/*
6640
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6641
	 */
6642
	function jetpack_icon_user_connected( $columns ) {
6643
		$columns['user_jetpack'] = '';
6644
		return $columns;
6645
	}
6646
6647
	/*
6648
	 * Show Jetpack icon if the user is linked.
6649
	 */
6650
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
6651
		if ( 'user_jetpack' == $col && Jetpack::is_user_connected( $user_id ) ) {
6652
			$jetpack_logo = new Jetpack_Logo();
6653
			$emblem_html = sprintf(
6654
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
6655
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
6656
				$jetpack_logo->get_jp_emblem()
6657
			);
6658
			return $emblem_html;
6659
		}
6660
6661
		return $val;
6662
	}
6663
6664
	/*
6665
	 * Style the Jetpack user column
6666
	 */
6667
	function jetpack_user_col_style() {
6668
		global $current_screen;
6669
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) { ?>
6670
			<style>
6671
				.fixed .column-user_jetpack {
6672
					width: 21px;
6673
				}
6674
				.jp-emblem-user-admin svg {
6675
					width: 20px;
6676
					height: 20px;
6677
				}
6678
				.jp-emblem-user-admin path {
6679
					fill: #00BE28;
6680
				}
6681
			</style>
6682
		<?php }
6683
	}
6684
6685
	/**
6686
	 * Checks if Akismet is active and working.
6687
	 *
6688
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6689
	 * that implied usage of methods present since more recent version.
6690
	 * See https://github.com/Automattic/jetpack/pull/9585
6691
	 *
6692
	 * @since  5.1.0
6693
	 *
6694
	 * @return bool True = Akismet available. False = Aksimet not available.
6695
	 */
6696
	public static function is_akismet_active() {
6697
		static $status = null;
6698
6699
		if ( ! is_null( $status ) ) {
6700
			return $status;
6701
		}
6702
6703
		// Check if a modern version of Akismet is active.
6704
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6705
			$status = false;
6706
			return $status;
6707
		}
6708
6709
		// Make sure there is a key known to Akismet at all before verifying key.
6710
		$akismet_key = Akismet::get_api_key();
6711
		if ( ! $akismet_key ) {
6712
			$status = false;
6713
			return $status;
6714
		}
6715
6716
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6717
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6718
6719
		// 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.
6720
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6721
		// We cache the result of the Akismet key verification for ten minutes.
6722
		if ( ! $akismet_key_state || $recheck ) {
6723
			$akismet_key_state = Akismet::verify_key( $akismet_key );
6724
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6725
		}
6726
6727
		$status = 'valid' === $akismet_key_state;
6728
6729
		return $status;
6730
	}
6731
6732
	/**
6733
	 * @deprecated
6734
	 *
6735
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
6736
	 */
6737
	public static function is_function_in_backtrace() {
6738
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
6739
	}
6740
6741
	/**
6742
	 * Given a minified path, and a non-minified path, will return
6743
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6744
	 *
6745
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6746
	 * root Jetpack directory.
6747
	 *
6748
	 * @since 5.6.0
6749
	 *
6750
	 * @param string $min_path
6751
	 * @param string $non_min_path
6752
	 * @return string The URL to the file
6753
	 */
6754
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6755
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6756
	}
6757
6758
	/**
6759
	 * Checks for whether Jetpack Backup & Scan is enabled.
6760
	 * Will return true if the state of Backup & Scan is anything except "unavailable".
6761
	 * @return bool|int|mixed
6762
	 */
6763
	public static function is_rewind_enabled() {
6764
		if ( ! Jetpack::is_active() ) {
6765
			return false;
6766
		}
6767
6768
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6769
		if ( false === $rewind_enabled ) {
6770
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
6771
			$rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6772
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
6773
				&& ! empty( $rewind_data['state'] )
6774
				&& 'active' === $rewind_data['state'] )
6775
				? 1
6776
				: 0;
6777
6778
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6779
		}
6780
		return $rewind_enabled;
6781
	}
6782
6783
	/**
6784
	 * Return Calypso environment value; used for developing Jetpack and pairing
6785
	 * it with different Calypso enrionments, such as localhost.
6786
	 *
6787
	 * @since 7.4.0
6788
	 *
6789
	 * @return string Calypso environment
6790
	 */
6791
	public static function get_calypso_env() {
6792
		if ( isset( $_GET['calypso_env'] ) ) {
6793
			return sanitize_key( $_GET['calypso_env'] );
6794
		}
6795
6796
		if ( getenv( 'CALYPSO_ENV' ) ) {
6797
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
6798
		}
6799
6800
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
6801
			return sanitize_key( CALYPSO_ENV );
6802
		}
6803
6804
		return '';
6805
	}
6806
6807
	/**
6808
	 * Checks whether or not TOS has been agreed upon.
6809
	 * Will return true if a user has clicked to register, or is already connected.
6810
	 */
6811
	public static function jetpack_tos_agreed() {
6812
		return Jetpack_Options::get_option( 'tos_agreed' ) || Jetpack::is_active();
6813
	}
6814
6815
	/**
6816
	 * Handles activating default modules as well general cleanup for the new connection.
6817
	 *
6818
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
6819
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6820
	 * @param boolean $send_state_messages          Whether to send state messages.
6821
	 * @return void
6822
	 */
6823
	public static function handle_post_authorization_actions(
6824
		$activate_sso = false,
6825
		$redirect_on_activation_error = false,
6826
		$send_state_messages = true
6827
	) {
6828
		$other_modules = $activate_sso
6829
			? array( 'sso' )
6830
			: array();
6831
6832
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
6833
			Jetpack::delete_active_modules();
6834
6835
			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...
6836
		} else {
6837
			Jetpack::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
6838
		}
6839
6840
		// Since this is a fresh connection, be sure to clear out IDC options
6841
		Jetpack_IDC::clear_all_idc_options();
6842
		Jetpack_Options::delete_raw_option( 'jetpack_last_connect_url_check' );
6843
6844
		// Start nonce cleaner
6845
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
6846
		wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
6847
6848
		if ( $send_state_messages ) {
6849
			Jetpack::state( 'message', 'authorized' );
6850
		}
6851
	}
6852
6853
	/**
6854
	 * Returns a boolean for whether backups UI should be displayed or not.
6855
	 *
6856
	 * @return bool Should backups UI be displayed?
6857
	 */
6858
	public static function show_backups_ui() {
6859
		/**
6860
		 * Whether UI for backups should be displayed.
6861
		 *
6862
		 * @since 6.5.0
6863
		 *
6864
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
6865
		 */
6866
		return Jetpack::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6867
	}
6868
6869
	/*
6870
	 * Deprecated manage functions
6871
	 */
6872
	function prepare_manage_jetpack_notice() {
6873
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6874
	}
6875
	function manage_activate_screen() {
6876
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6877
	}
6878
	function admin_jetpack_manage_notice() {
6879
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6880
	}
6881
	function opt_out_jetpack_manage_url() {
6882
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6883
	}
6884
	function opt_in_jetpack_manage_url() {
6885
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6886
	}
6887
	function opt_in_jetpack_manage_notice() {
6888
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6889
	}
6890
	function can_display_jetpack_manage_notice() {
6891
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
6892
	}
6893
6894
	/**
6895
	 * Clean leftoveruser meta.
6896
	 *
6897
	 * Delete Jetpack-related user meta when it is no longer needed.
6898
	 *
6899
	 * @since 7.3.0
6900
	 *
6901
	 * @param int $user_id User ID being updated.
6902
	 */
6903
	public static function user_meta_cleanup( $user_id ) {
6904
		$meta_keys = array(
6905
			// AtD removed from Jetpack 7.3
6906
			'AtD_options',
6907
			'AtD_check_when',
6908
			'AtD_guess_lang',
6909
			'AtD_ignored_phrases',
6910
		);
6911
6912
		foreach ( $meta_keys as $meta_key ) {
6913
			if ( get_user_meta( $user_id, $meta_key ) ) {
6914
				delete_user_meta( $user_id, $meta_key );
6915
			}
6916
		}
6917
	}
6918
6919
	function is_active_and_not_development_mode( $maybe ) {
6920
		if ( ! \Jetpack::is_active() || \Jetpack::is_development_mode() ) {
6921
			return false;
6922
		}
6923
		return true;
6924
	}
6925
}
6926