Completed
Push — update/move_caps_logic_to_netw... ( 0b4f9e )
by
unknown
16:08 queued 08:18
created

Jetpack::jetpack_custom_caps()   C

Complexity

Conditions 17
Paths 18

Size

Total Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
nc 18
nop 4
dl 0
loc 60
rs 5.2166
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
use Automattic\Jetpack\Assets;
3
use Automattic\Jetpack\Assets\Logo as Jetpack_Logo;
4
use Automattic\Jetpack\Config;
5
use Automattic\Jetpack\Connection\Client;
6
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
7
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
8
use Automattic\Jetpack\Connection\Plugin_Storage as Connection_Plugin_Storage;
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Partner;
11
use Automattic\Jetpack\Roles;
12
use Automattic\Jetpack\Status;
13
use Automattic\Jetpack\Sync\Functions;
14
use Automattic\Jetpack\Sync\Health;
15
use Automattic\Jetpack\Sync\Sender;
16
use Automattic\Jetpack\Sync\Users;
17
use Automattic\Jetpack\Terms_Of_Service;
18
use Automattic\Jetpack\Tracking;
19
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
20
use Automattic\Jetpack\Redirect;
21
22
/*
23
Options:
24
jetpack_options (array)
25
	An array of options.
26
	@see Jetpack_Options::get_option_names()
27
28
jetpack_register (string)
29
	Temporary verification secrets.
30
31
jetpack_activated (int)
32
	1: the plugin was activated normally
33
	2: the plugin was activated on this site because of a network-wide activation
34
	3: the plugin was auto-installed
35
	4: the plugin was manually disconnected (but is still installed)
36
37
jetpack_active_modules (array)
38
	Array of active module slugs.
39
40
jetpack_do_activate (bool)
41
	Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
42
*/
43
44
require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
45
46
class Jetpack {
47
	public $xmlrpc_server = null;
48
49
	private $rest_authentication_status = null;
50
51
	public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
52
53
	/**
54
	 * @var array The handles of styles that are concatenated into jetpack.css.
55
	 *
56
	 * When making changes to that list, you must also update concat_list in tools/builder/frontend-css.js.
57
	 */
58
	public $concatenated_style_handles = array(
59
		'jetpack-carousel',
60
		'grunion.css',
61
		'the-neverending-homepage',
62
		'jetpack_likes',
63
		'jetpack_related-posts',
64
		'sharedaddy',
65
		'jetpack-slideshow',
66
		'presentations',
67
		'quiz',
68
		'jetpack-subscriptions',
69
		'jetpack-responsive-videos-style',
70
		'jetpack-social-menu',
71
		'tiled-gallery',
72
		'jetpack_display_posts_widget',
73
		'gravatar-profile-widget',
74
		'goodreads-widget',
75
		'jetpack_social_media_icons_widget',
76
		'jetpack-top-posts-widget',
77
		'jetpack_image_widget',
78
		'jetpack-my-community-widget',
79
		'jetpack-authors-widget',
80
		'wordads',
81
		'eu-cookie-law-style',
82
		'flickr-widget-style',
83
		'jetpack-search-widget',
84
		'jetpack-simple-payments-widget-style',
85
		'jetpack-widget-social-icons-styles',
86
	);
87
88
	/**
89
	 * Contains all assets that have had their URL rewritten to minified versions.
90
	 *
91
	 * @var array
92
	 */
93
	static $min_assets = array();
94
95
	public $plugins_to_deactivate = array(
96
		'stats'               => array( 'stats/stats.php', 'WordPress.com Stats' ),
97
		'shortlinks'          => array( 'stats/stats.php', 'WordPress.com Stats' ),
98
		'sharedaddy'          => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
99
		'twitter-widget'      => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
100
		'contact-form'        => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
101
		'contact-form'        => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
102
		'custom-css'          => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
103
		'random-redirect'     => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
104
		'videopress'          => array( 'video/video.php', 'VideoPress' ),
105
		'widget-visibility'   => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
106
		'widget-visibility'   => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
107
		'sharedaddy'          => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
108
		'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
109
		'latex'               => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
110
	);
111
112
	/**
113
	 * Map of roles we care about, and their corresponding minimum capabilities.
114
	 *
115
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
116
	 *
117
	 * @access public
118
	 * @static
119
	 *
120
	 * @var array
121
	 */
122
	public static $capability_translations = array(
123
		'administrator' => 'manage_options',
124
		'editor'        => 'edit_others_posts',
125
		'author'        => 'publish_posts',
126
		'contributor'   => 'edit_posts',
127
		'subscriber'    => 'read',
128
	);
129
130
	/**
131
	 * Map of modules that have conflicts with plugins and should not be auto-activated
132
	 * if the plugins are active.  Used by filter_default_modules
133
	 *
134
	 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
135
	 * change `module-slug` and add this to your plugin:
136
	 *
137
	 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
138
	 * function my_jetpack_get_default_modules( $modules ) {
139
	 *     return array_diff( $modules, array( 'module-slug' ) );
140
	 * }
141
	 *
142
	 * @var array
143
	 */
144
	private $conflicting_plugins = array(
145
		'comments'           => array(
146
			'Intense Debate'                 => 'intensedebate/intensedebate.php',
147
			'Disqus'                         => 'disqus-comment-system/disqus.php',
148
			'Livefyre'                       => 'livefyre-comments/livefyre.php',
149
			'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
150
			'Google+ Comments'               => 'google-plus-comments/google-plus-comments.php',
151
			'WP-SpamShield Anti-Spam'        => 'wp-spamshield/wp-spamshield.php',
152
		),
153
		'comment-likes'      => array(
154
			'Epoch' => 'epoch/plugincore.php',
155
		),
156
		'contact-form'       => array(
157
			'Contact Form 7'           => 'contact-form-7/wp-contact-form-7.php',
158
			'Gravity Forms'            => 'gravityforms/gravityforms.php',
159
			'Contact Form Plugin'      => 'contact-form-plugin/contact_form.php',
160
			'Easy Contact Forms'       => 'easy-contact-forms/easy-contact-forms.php',
161
			'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
162
			'Ninja Forms'              => 'ninja-forms/ninja-forms.php',
163
		),
164
		'latex'              => array(
165
			'LaTeX for WordPress'     => 'latex/latex.php',
166
			'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
167
			'Easy WP LaTeX'           => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
168
			'MathJax-LaTeX'           => 'mathjax-latex/mathjax-latex.php',
169
			'Enable Latex'            => 'enable-latex/enable-latex.php',
170
			'WP QuickLaTeX'           => 'wp-quicklatex/wp-quicklatex.php',
171
		),
172
		'protect'            => array(
173
			'Limit Login Attempts'              => 'limit-login-attempts/limit-login-attempts.php',
174
			'Captcha'                           => 'captcha/captcha.php',
175
			'Brute Force Login Protection'      => 'brute-force-login-protection/brute-force-login-protection.php',
176
			'Login Security Solution'           => 'login-security-solution/login-security-solution.php',
177
			'WPSecureOps Brute Force Protect'   => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
178
			'BulletProof Security'              => 'bulletproof-security/bulletproof-security.php',
179
			'SiteGuard WP Plugin'               => 'siteguard/siteguard.php',
180
			'Security-protection'               => 'security-protection/security-protection.php',
181
			'Login Security'                    => 'login-security/login-security.php',
182
			'Botnet Attack Blocker'             => 'botnet-attack-blocker/botnet-attack-blocker.php',
183
			'Wordfence Security'                => 'wordfence/wordfence.php',
184
			'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
185
			'iThemes Security'                  => 'better-wp-security/better-wp-security.php',
186
		),
187
		'random-redirect'    => array(
188
			'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
189
		),
190
		'related-posts'      => array(
191
			'YARPP'                       => 'yet-another-related-posts-plugin/yarpp.php',
192
			'WordPress Related Posts'     => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
193
			'nrelate Related Content'     => 'nrelate-related-content/nrelate-related.php',
194
			'Contextual Related Posts'    => 'contextual-related-posts/contextual-related-posts.php',
195
			'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
196
			'outbrain'                    => 'outbrain/outbrain.php',
197
			'Shareaholic'                 => 'shareaholic/shareaholic.php',
198
			'Sexybookmarks'               => 'sexybookmarks/shareaholic.php',
199
		),
200
		'sharedaddy'         => array(
201
			'AddThis'     => 'addthis/addthis_social_widget.php',
202
			'Add To Any'  => 'add-to-any/add-to-any.php',
203
			'ShareThis'   => 'share-this/sharethis.php',
204
			'Shareaholic' => 'shareaholic/shareaholic.php',
205
		),
206
		'seo-tools'          => array(
207
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
208
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
209
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
210
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
211
			'The SEO Framework'              => 'autodescription/autodescription.php',
212
		),
213
		'verification-tools' => array(
214
			'WordPress SEO by Yoast'         => 'wordpress-seo/wp-seo.php',
215
			'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
216
			'All in One SEO Pack'            => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
217
			'All in One SEO Pack Pro'        => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
218
			'The SEO Framework'              => 'autodescription/autodescription.php',
219
		),
220
		'widget-visibility'  => array(
221
			'Widget Logic'    => 'widget-logic/widget_logic.php',
222
			'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
223
		),
224
		'sitemaps'           => array(
225
			'Google XML Sitemaps'                  => 'google-sitemap-generator/sitemap.php',
226
			'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
227
			'Google XML Sitemaps for qTranslate'   => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
228
			'XML Sitemap & Google News feeds'      => 'xml-sitemap-feed/xml-sitemap.php',
229
			'Google Sitemap by BestWebSoft'        => 'google-sitemap-plugin/google-sitemap-plugin.php',
230
			'WordPress SEO by Yoast'               => 'wordpress-seo/wp-seo.php',
231
			'WordPress SEO Premium by Yoast'       => 'wordpress-seo-premium/wp-seo-premium.php',
232
			'All in One SEO Pack'                  => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
233
			'All in One SEO Pack Pro'              => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
234
			'The SEO Framework'                    => 'autodescription/autodescription.php',
235
			'Sitemap'                              => 'sitemap/sitemap.php',
236
			'Simple Wp Sitemap'                    => 'simple-wp-sitemap/simple-wp-sitemap.php',
237
			'Simple Sitemap'                       => 'simple-sitemap/simple-sitemap.php',
238
			'XML Sitemaps'                         => 'xml-sitemaps/xml-sitemaps.php',
239
			'MSM Sitemaps'                         => 'msm-sitemap/msm-sitemap.php',
240
		),
241
		'lazy-images'        => array(
242
			'Lazy Load'              => 'lazy-load/lazy-load.php',
243
			'BJ Lazy Load'           => 'bj-lazy-load/bj-lazy-load.php',
244
			'Lazy Load by WP Rocket' => 'rocket-lazy-load/rocket-lazy-load.php',
245
		),
246
	);
247
248
	/**
249
	 * Plugins for which we turn off our Facebook OG Tags implementation.
250
	 *
251
	 * Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
252
	 * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
253
	 *
254
	 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
255
	 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
256
	 */
257
	private $open_graph_conflicting_plugins = array(
258
		'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
259
		// 2 Click Social Media Buttons
260
		'add-link-to-facebook/add-link-to-facebook.php',         // Add Link to Facebook
261
		'add-meta-tags/add-meta-tags.php',                       // Add Meta Tags
262
		'complete-open-graph/complete-open-graph.php',           // Complete Open Graph
263
		'easy-facebook-share-thumbnails/esft.php',               // Easy Facebook Share Thumbnail
264
		'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
265
		// Open Graph Meta Tags by Heateor
266
		'facebook/facebook.php',                                 // Facebook (official plugin)
267
		'facebook-awd/AWD_facebook.php',                         // Facebook AWD All in one
268
		'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
269
		// Facebook Featured Image & OG Meta Tags
270
		'facebook-meta-tags/facebook-metatags.php',              // Facebook Meta Tags
271
		'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
272
		// Facebook Open Graph Meta Tags for WordPress
273
		'facebook-revised-open-graph-meta-tag/index.php',        // Facebook Revised Open Graph Meta Tag
274
		'facebook-thumb-fixer/_facebook-thumb-fixer.php',        // Facebook Thumb Fixer
275
		'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
276
		// Fedmich's Facebook Open Graph Meta
277
		'network-publisher/networkpub.php',                      // Network Publisher
278
		'nextgen-facebook/nextgen-facebook.php',                 // NextGEN Facebook OG
279
		'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
280
		// NextScripts SNAP
281
		'og-tags/og-tags.php',                                   // OG Tags
282
		'opengraph/opengraph.php',                               // Open Graph
283
		'open-graph-protocol-framework/open-graph-protocol-framework.php',
284
		// Open Graph Protocol Framework
285
		'seo-facebook-comments/seofacebook.php',                 // SEO Facebook Comments
286
		'seo-ultimate/seo-ultimate.php',                         // SEO Ultimate
287
		'sexybookmarks/sexy-bookmarks.php',                      // Shareaholic
288
		'shareaholic/sexy-bookmarks.php',                        // Shareaholic
289
		'sharepress/sharepress.php',                             // SharePress
290
		'simple-facebook-connect/sfc.php',                       // Simple Facebook Connect
291
		'social-discussions/social-discussions.php',             // Social Discussions
292
		'social-sharing-toolkit/social_sharing_toolkit.php',     // Social Sharing Toolkit
293
		'socialize/socialize.php',                               // Socialize
294
		'squirrly-seo/squirrly.php',                             // SEO by SQUIRRLY™
295
		'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
296
		// Tweet, Like, Google +1 and Share
297
		'wordbooker/wordbooker.php',                             // Wordbooker
298
		'wpsso/wpsso.php',                                       // WordPress Social Sharing Optimization
299
		'wp-caregiver/wp-caregiver.php',                         // WP Caregiver
300
		'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
301
		// WP Facebook Like Send & Open Graph Meta
302
		'wp-facebook-open-graph-protocol/wp-facebook-ogp.php',   // WP Facebook Open Graph protocol
303
		'wp-ogp/wp-ogp.php',                                     // WP-OGP
304
		'zoltonorg-social-plugin/zosp.php',                      // Zolton.org Social Plugin
305
		'wp-fb-share-like-button/wp_fb_share-like_widget.php',   // WP Facebook Like Button
306
		'open-graph-metabox/open-graph-metabox.php',              // Open Graph Metabox
307
	);
308
309
	/**
310
	 * Plugins for which we turn off our Twitter Cards Tags implementation.
311
	 */
312
	private $twitter_cards_conflicting_plugins = array(
313
		// 'twitter/twitter.php',                       // The official one handles this on its own.
314
		// https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
315
			'eewee-twitter-card/index.php',              // Eewee Twitter Card
316
		'ig-twitter-cards/ig-twitter-cards.php',     // IG:Twitter Cards
317
		'jm-twitter-cards/jm-twitter-cards.php',     // JM Twitter Cards
318
		'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
319
		// Pure Web Brilliant's Social Graph Twitter Cards Extension
320
		'twitter-cards/twitter-cards.php',           // Twitter Cards
321
		'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
322
		'wp-to-twitter/wp-to-twitter.php',           // WP to Twitter
323
		'wp-twitter-cards/twitter_cards.php',        // WP Twitter Cards
324
	);
325
326
	/**
327
	 * Message to display in admin_notice
328
	 *
329
	 * @var string
330
	 */
331
	public $message = '';
332
333
	/**
334
	 * Error to display in admin_notice
335
	 *
336
	 * @var string
337
	 */
338
	public $error = '';
339
340
	/**
341
	 * Modules that need more privacy description.
342
	 *
343
	 * @var string
344
	 */
345
	public $privacy_checks = '';
346
347
	/**
348
	 * Stats to record once the page loads
349
	 *
350
	 * @var array
351
	 */
352
	public $stats = array();
353
354
	/**
355
	 * Jetpack_Sync object
356
	 */
357
	public $sync;
358
359
	/**
360
	 * Verified data for JSON authorization request
361
	 */
362
	public $json_api_authorization_request = array();
363
364
	/**
365
	 * @var Automattic\Jetpack\Connection\Manager
366
	 */
367
	protected $connection_manager;
368
369
	/**
370
	 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
371
	 */
372
	public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
373
374
	/**
375
	 * Constant for login redirect key.
376
	 *
377
	 * @var string
378
	 * @since 8.4.0
379
	 */
380
	public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
381
382
	/**
383
	 * Holds the singleton instance of this class
384
	 *
385
	 * @since 2.3.3
386
	 * @var Jetpack
387
	 */
388
	static $instance = false;
389
390
	/**
391
	 * Singleton
392
	 *
393
	 * @static
394
	 */
395
	public static function init() {
396
		if ( ! self::$instance ) {
397
			self::$instance = new Jetpack();
398
			add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
399
		}
400
401
		return self::$instance;
402
	}
403
404
	/**
405
	 * Must never be called statically
406
	 */
407
	function plugin_upgrade() {
408
		if ( self::is_active() ) {
409
			list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
410
			if ( JETPACK__VERSION != $version ) {
411
				// Prevent multiple upgrades at once - only a single process should trigger
412
				// an upgrade to avoid stampedes
413
				if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
414
					return;
415
				}
416
417
				// Set a short lock to prevent multiple instances of the upgrade
418
				set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
419
420
				// check which active modules actually exist and remove others from active_modules list
421
				$unfiltered_modules = self::get_active_modules();
422
				$modules            = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
423
				if ( array_diff( $unfiltered_modules, $modules ) ) {
424
					self::update_active_modules( $modules );
425
				}
426
427
				add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
428
429
				// Upgrade to 4.3.0
430
				if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
431
					Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
432
				}
433
434
				// Make sure Markdown for posts gets turned back on
435
				if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
436
					update_option( 'wpcom_publish_posts_with_markdown', true );
437
				}
438
439
				/*
440
				 * Minileven deprecation. 8.3.0.
441
				 * Only delete options if not using
442
				 * the replacement standalone Minileven plugin.
443
				 */
444
				if (
445
					! self::is_plugin_active( 'minileven-master/minileven.php' )
446
					&& ! self::is_plugin_active( 'minileven/minileven.php' )
447
				) {
448
					if ( get_option( 'wp_mobile_custom_css' ) ) {
449
						delete_option( 'wp_mobile_custom_css' );
450
					}
451
					if ( get_option( 'wp_mobile_excerpt' ) ) {
452
						delete_option( 'wp_mobile_excerpt' );
453
					}
454
					if ( get_option( 'wp_mobile_featured_images' ) ) {
455
						delete_option( 'wp_mobile_featured_images' );
456
					}
457
					if ( get_option( 'wp_mobile_app_promos' ) ) {
458
						delete_option( 'wp_mobile_app_promos' );
459
					}
460
				}
461
462
				// Upgrade to 8.4.0.
463
				if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
464
					Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
465
				}
466
467
				if ( did_action( 'wp_loaded' ) ) {
468
					self::upgrade_on_load();
469
				} else {
470
					add_action(
471
						'wp_loaded',
472
						array( __CLASS__, 'upgrade_on_load' )
473
					);
474
				}
475
			}
476
		}
477
	}
478
479
	/**
480
	 * Runs upgrade routines that need to have modules loaded.
481
	 */
482
	static function upgrade_on_load() {
483
484
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
485
		// This can happen in case Jetpack has been just upgraded and is
486
		// being initialized late during the page load. In this case we wait
487
		// until the next proper admin page load with Jetpack active.
488
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
489
			delete_transient( self::$plugin_upgrade_lock_key );
490
491
			return;
492
		}
493
494
		self::maybe_set_version_option();
495
496
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
497
			Jetpack_Widget_Conditions::migrate_post_type_rules();
498
		}
499
500
		if (
501
			class_exists( 'Jetpack_Sitemap_Manager' )
502
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
503
		) {
504
			do_action( 'jetpack_sitemaps_purge_data' );
505
		}
506
507
		// Delete old stats cache
508
		delete_option( 'jetpack_restapi_stats_cache' );
509
510
		delete_transient( self::$plugin_upgrade_lock_key );
511
	}
512
513
	/**
514
	 * Saves all the currently active modules to options.
515
	 * Also fires Action hooks for each newly activated and deactivated module.
516
	 *
517
	 * @param $modules Array Array of active modules to be saved in options.
518
	 *
519
	 * @return $success bool true for success, false for failure.
0 ignored issues
show
Documentation introduced by
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...
520
	 */
521
	static function update_active_modules( $modules ) {
522
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
523
		$active_modules       = self::get_active_modules();
524
		$new_active_modules   = array_diff( $modules, $current_modules );
525
		$new_inactive_modules = array_diff( $active_modules, $modules );
526
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
527
		$reindexed_modules    = array_values( $new_current_modules );
528
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
529
530
		foreach ( $new_active_modules as $module ) {
531
			/**
532
			 * Fires when a specific module is activated.
533
			 *
534
			 * @since 1.9.0
535
			 *
536
			 * @param string $module Module slug.
537
			 * @param boolean $success whether the module was activated. @since 4.2
538
			 */
539
			do_action( 'jetpack_activate_module', $module, $success );
540
			/**
541
			 * Fires when a module is activated.
542
			 * The dynamic part of the filter, $module, is the module slug.
543
			 *
544
			 * @since 1.9.0
545
			 *
546
			 * @param string $module Module slug.
547
			 */
548
			do_action( "jetpack_activate_module_$module", $module );
549
		}
550
551
		foreach ( $new_inactive_modules as $module ) {
552
			/**
553
			 * Fired after a module has been deactivated.
554
			 *
555
			 * @since 4.2.0
556
			 *
557
			 * @param string $module Module slug.
558
			 * @param boolean $success whether the module was deactivated.
559
			 */
560
			do_action( 'jetpack_deactivate_module', $module, $success );
561
			/**
562
			 * Fires when a module is deactivated.
563
			 * The dynamic part of the filter, $module, is the module slug.
564
			 *
565
			 * @since 1.9.0
566
			 *
567
			 * @param string $module Module slug.
568
			 */
569
			do_action( "jetpack_deactivate_module_$module", $module );
570
		}
571
572
		return $success;
573
	}
574
575
	static function delete_active_modules() {
576
		self::update_active_modules( array() );
577
	}
578
579
	/**
580
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
581
	 * available.
582
	 */
583
	public function add_configure_hook() {
584
		global $wp_filter;
585
586
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
587
		if ( false !== $current_priority ) {
588
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
589
		}
590
591
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
592
		sort( $taken_priorities );
593
594
		$first_priority = array_shift( $taken_priorities );
595
596
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
597
			$new_priority = - PHP_INT_MAX;
598
		} else {
599
			$new_priority = $first_priority - 1;
600
		}
601
602
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
603
	}
604
605
	/**
606
	 * Constructor.  Initializes WordPress hooks
607
	 */
608
	private function __construct() {
609
		/*
610
		 * Check for and alert any deprecated hooks
611
		 */
612
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
613
614
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
615
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
616
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
617
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
618
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
619
620
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
621
622
		add_filter(
623
			'jetpack_signature_check_token',
624
			array( __CLASS__, 'verify_onboarding_token' ),
625
			10,
626
			3
627
		);
628
629
		/**
630
		 * Prepare Gutenberg Editor functionality
631
		 */
632
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
633
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
634
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
635
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
636
637
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
638
639
		// Unlink user before deleting the user from WP.com.
640
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
641
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
642
643
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
644
645
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
646
		add_action( 'login_init', array( $this, 'login_init' ) );
647
648
		add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
649
		add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
650
651
		add_action( 'admin_init', array( $this, 'admin_init' ) );
652
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
653
654
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
655
656
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
657
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
658
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
659
660
		// returns HTTPS support status
661
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
662
663
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
664
665
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
666
667
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
668
669
		/**
670
		 * These actions run checks to load additional files.
671
		 * They check for external files or plugins, so they need to run as late as possible.
672
		 */
673
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
674
		add_action( 'amp_story_head', array( $this, 'check_open_graph' ), 1 );
675
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
676
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
677
678
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
679
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
680
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
681
682
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
683
684
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
685
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
686
687
		// A filter to control all just in time messages
688
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
689
690
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
691
692
		/*
693
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
694
		 * We should make sure to only do this for front end links.
695
		 */
696
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
697
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
698
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
699
700
			/*
701
			 * We'll override wp_notify_postauthor and wp_notify_moderator pluggable functions
702
			 * so they point moderation links on emails to Calypso.
703
			 */
704
			jetpack_require_lib( 'functions.wp-notify' );
705
		}
706
707
		// Hide edit post link if mobile app.
708
		if ( Jetpack_User_Agent_Info::is_mobile_app() ) {
709
			add_filter( 'get_edit_post_link', '__return_empty_string' );
710
		}
711
712
		// Update the Jetpack plan from API on heartbeats.
713
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
714
715
		/**
716
		 * This is the hack to concatenate all css files into one.
717
		 * For description and reasoning see the implode_frontend_css method.
718
		 *
719
		 * Super late priority so we catch all the registered styles.
720
		 */
721
		if ( ! is_admin() ) {
722
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
723
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
724
		}
725
726
		/**
727
		 * These are sync actions that we need to keep track of for jitms
728
		 */
729
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
730
731
		// Actually push the stats on shutdown.
732
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
733
			add_action( 'shutdown', array( $this, 'push_stats' ) );
734
		}
735
736
		// Actions for Manager::authorize().
737
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
738
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
739
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
740
741
		// Filters for the Manager::get_token() urls and request body.
742
		add_filter( 'jetpack_token_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
743
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
744
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
745
	}
746
747
	/**
748
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
749
	 * Config object.
750
	 */
751
	public function configure() {
752
		$config = new Config();
753
754
		foreach (
755
			array(
756
				'sync',
757
				'tracking',
758
				'tos',
759
			)
760
			as $feature
761
		) {
762
			$config->ensure( $feature );
763
		}
764
765
		$config->ensure(
766
			'connection',
767
			array(
768
				'slug' => 'jetpack',
769
				'name' => 'Jetpack',
770
			)
771
		);
772
773
		if ( is_admin() ) {
774
			$config->ensure( 'jitm' );
775
		}
776
777
		if ( ! $this->connection_manager ) {
778
			$this->connection_manager = new Connection_Manager( 'jetpack' );
779
		}
780
781
		/*
782
		 * Load things that should only be in Network Admin.
783
		 *
784
		 * For now blow away everything else until a more full
785
		 * understanding of what is needed at the network level is
786
		 * available
787
		 */
788
		if ( is_multisite() ) {
789
			$network = Jetpack_Network::init();
790
			$network->set_connection( $this->connection_manager );
791
		}
792
793
		if ( $this->connection_manager->is_active() ) {
794
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
795
796
			Jetpack_Heartbeat::init();
797
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
798
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
799
				Jetpack_Search_Performance_Logger::init();
800
			}
801
		}
802
803
		// Initialize remote file upload request handlers.
804
		$this->add_remote_request_handlers();
805
806
		/*
807
		 * Enable enhanced handling of previewing sites in Calypso
808
		 */
809
		if ( self::is_active() ) {
810
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
811
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
812
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
813
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
814
		}
815
	}
816
817
	/**
818
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
819
	 * initialization code.
820
	 *
821
	 * @action plugins_loaded
822
	 */
823
	public function late_initialization() {
824
		add_action( 'plugins_loaded', array( 'Jetpack', 'plugin_textdomain' ), 99 );
825
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
826
827
		Partner::init();
828
829
		/**
830
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
831
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
832
		 *
833
		 * @since 8.1.0
834
		 *
835
		 * @param Jetpack $jetpack the main plugin class object.
836
		 */
837
		do_action( 'jetpack_loaded', $this );
838
839
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
840
	}
841
842
	/**
843
	 * Sets up the XMLRPC request handlers.
844
	 *
845
	 * @deprecated since 7.7.0
846
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
847
	 *
848
	 * @param array                 $request_params Incoming request parameters.
849
	 * @param Boolean               $is_active      Whether the connection is currently active.
850
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
851
	 * @param Jetpack_XMLRPC_Server $xmlrpc_server  (optional) An instance of the server to use instead of instantiating a new one.
0 ignored issues
show
Documentation introduced by
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...
852
	 */
853 View Code Duplication
	public function setup_xmlrpc_handlers(
854
		$request_params,
855
		$is_active,
856
		$is_signed,
857
		Jetpack_XMLRPC_Server $xmlrpc_server = null
858
	) {
859
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
860
861
		if ( ! $this->connection_manager ) {
862
			$this->connection_manager = new Connection_Manager();
863
		}
864
865
		return $this->connection_manager->setup_xmlrpc_handlers(
866
			$request_params,
867
			$is_active,
868
			$is_signed,
869
			$xmlrpc_server
870
		);
871
	}
872
873
	/**
874
	 * Initialize REST API registration connector.
875
	 *
876
	 * @deprecated since 7.7.0
877
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
878
	 */
879 View Code Duplication
	public function initialize_rest_api_registration_connector() {
880
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
881
882
		if ( ! $this->connection_manager ) {
883
			$this->connection_manager = new Connection_Manager();
884
		}
885
886
		$this->connection_manager->initialize_rest_api_registration_connector();
887
	}
888
889
	/**
890
	 * This is ported over from the manage module, which has been deprecated and baked in here.
891
	 *
892
	 * @param $domains
893
	 */
894
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
895
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
896
	}
897
898
	/**
899
	 * Return $domains, with 'wordpress.com' appended.
900
	 * This is ported over from the manage module, which has been deprecated and baked in here.
901
	 *
902
	 * @param $domains
903
	 * @return array
904
	 */
905
	function allow_wpcom_domain( $domains ) {
906
		if ( empty( $domains ) ) {
907
			$domains = array();
908
		}
909
		$domains[] = 'wordpress.com';
910
		return array_unique( $domains );
911
	}
912
913
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
914
		$post = get_post( $post_id );
915
916
		if ( empty( $post ) ) {
917
			return $default_url;
918
		}
919
920
		$post_type = $post->post_type;
921
922
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
923
		// https://en.support.wordpress.com/custom-post-types/
924
		$allowed_post_types = array(
925
			'post',
926
			'page',
927
			'jetpack-portfolio',
928
			'jetpack-testimonial',
929
		);
930
931
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
932
			return $default_url;
933
		}
934
935
		return esc_url(
936
			Redirect::get_url(
937
				'calypso-edit-' . $post_type,
938
				array(
939
					'path' => $post_id,
940
				)
941
			)
942
		);
943
	}
944
945
	function point_edit_comment_links_to_calypso( $url ) {
946
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
947
		wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
0 ignored issues
show
Bug introduced by
The variable $query_args does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
948
949
		return esc_url(
950
			Redirect::get_url(
951
				'calypso-edit-comment',
952
				array(
953
					'path' => $query_args['amp;c'],
954
				)
955
			)
956
		);
957
958
	}
959
960
	function jetpack_track_last_sync_callback( $params ) {
961
		/**
962
		 * Filter to turn off jitm caching
963
		 *
964
		 * @since 5.4.0
965
		 *
966
		 * @param bool false Whether to cache just in time messages
967
		 */
968
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
969
			return $params;
970
		}
971
972
		if ( is_array( $params ) && isset( $params[0] ) ) {
973
			$option = $params[0];
974
			if ( 'active_plugins' === $option ) {
975
				// use the cache if we can, but not terribly important if it gets evicted
976
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
977
			}
978
		}
979
980
		return $params;
981
	}
982
983
	function jetpack_connection_banner_callback() {
984
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
985
986
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
987
		if (
988
			isset( $_REQUEST['dismissBanner'] ) &&
989
			! Jetpack_Connection_Banner::force_display()
990
		) {
991
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
992
			wp_send_json_success();
993
		}
994
995
		wp_die();
996
	}
997
998
	/**
999
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1000
	 * Only used in our alternate XML-RPC endpoint, where we want to
1001
	 * ensure that Core and other plugins' methods are not exposed.
1002
	 *
1003
	 * @deprecated since 7.7.0
1004
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1005
	 *
1006
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1007
	 * @return array Filtered $methods
1008
	 */
1009 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1010
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1011
1012
		if ( ! $this->connection_manager ) {
1013
			$this->connection_manager = new Connection_Manager();
1014
		}
1015
1016
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1017
	}
1018
1019
	/**
1020
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1021
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1022
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1023
	 * which is accessible via a different URI. Most of the below is copied directly
1024
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1025
	 *
1026
	 * @deprecated since 7.7.0
1027
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1028
	 */
1029 View Code Duplication
	public function alternate_xmlrpc() {
1030
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1031
1032
		if ( ! $this->connection_manager ) {
1033
			$this->connection_manager = new Connection_Manager();
1034
		}
1035
1036
		$this->connection_manager->alternate_xmlrpc();
1037
	}
1038
1039
	/**
1040
	 * The callback for the JITM ajax requests.
1041
	 *
1042
	 * @deprecated since 7.9.0
1043
	 */
1044
	function jetpack_jitm_ajax_callback() {
1045
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1046
	}
1047
1048
	/**
1049
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1050
	 */
1051
	function push_stats() {
1052
		if ( ! empty( $this->stats ) ) {
1053
			$this->do_stats( 'server_side' );
1054
		}
1055
	}
1056
1057
	/**
1058
	 * Sets the Jetpack custom capabilities.
1059
	 *
1060
	 * @param string[] $caps    Array of the user's capabilities.
1061
	 * @param string   $cap     Capability name.
1062
	 * @param int      $user_id The user ID.
1063
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1064
	 */
1065
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1066
		$is_development_mode = ( new Status() )->is_development_mode();
1067
		switch ( $cap ) {
1068
			case 'jetpack_connect':
1069
			case 'jetpack_reconnect':
1070
				if ( $is_development_mode ) {
1071
					$caps = array( 'do_not_allow' );
1072
					break;
1073
				}
1074
				// Pass through. If it's not development mode, these should match disconnect.
1075
				// Let users disconnect if it's development mode, just in case things glitch.
1076
			case 'jetpack_disconnect':
1077
				/**
1078
				 * Filters the jetpack_disconnect capability.
1079
				 *
1080
				 * @since 8.7.0
1081
				 *
1082
				 * @param array An array containing the capability name.
1083
				 */
1084
				$caps = apply_filters( 'jetpack_disconnect_cap', array( 'manage_options' ) );
1085
				break;
1086
			case 'jetpack_manage_modules':
1087
			case 'jetpack_activate_modules':
1088
			case 'jetpack_deactivate_modules':
1089
				$caps = array( 'manage_options' );
1090
				break;
1091
			case 'jetpack_configure_modules':
1092
				$caps = array( 'manage_options' );
1093
				break;
1094
			case 'jetpack_manage_autoupdates':
1095
				$caps = array(
1096
					'manage_options',
1097
					'update_plugins',
1098
				);
1099
				break;
1100
			case 'jetpack_network_admin_page':
1101
			case 'jetpack_network_settings_page':
1102
				$caps = array( 'manage_network_plugins' );
1103
				break;
1104
			case 'jetpack_network_sites_page':
1105
				$caps = array( 'manage_sites' );
1106
				break;
1107
			case 'jetpack_admin_page':
1108
				if ( $is_development_mode ) {
1109
					$caps = array( 'manage_options' );
1110
					break;
1111
				} else {
1112
					$caps = array( 'read' );
1113
				}
1114
				break;
1115
			case 'jetpack_connect_user':
1116
				if ( $is_development_mode ) {
1117
					$caps = array( 'do_not_allow' );
1118
					break;
1119
				}
1120
				$caps = array( 'read' );
1121
				break;
1122
		}
1123
		return $caps;
1124
	}
1125
1126
	/**
1127
	 * Require a Jetpack authentication.
1128
	 *
1129
	 * @deprecated since 7.7.0
1130
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1131
	 */
1132 View Code Duplication
	public function require_jetpack_authentication() {
1133
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1134
1135
		if ( ! $this->connection_manager ) {
1136
			$this->connection_manager = new Connection_Manager();
1137
		}
1138
1139
		$this->connection_manager->require_jetpack_authentication();
1140
	}
1141
1142
	/**
1143
	 * Load language files
1144
	 *
1145
	 * @action plugins_loaded
1146
	 */
1147
	public static function plugin_textdomain() {
1148
		// Note to self, the third argument must not be hardcoded, to account for relocated folders.
1149
		load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
1150
	}
1151
1152
	/**
1153
	 * Register assets for use in various modules and the Jetpack admin page.
1154
	 *
1155
	 * @uses wp_script_is, wp_register_script, plugins_url
1156
	 * @action wp_loaded
1157
	 * @return null
1158
	 */
1159
	public function register_assets() {
1160
		if ( ! wp_script_is( 'spin', 'registered' ) ) {
1161
			wp_register_script(
1162
				'spin',
1163
				Assets::get_file_url_for_environment( '_inc/build/spin.min.js', '_inc/spin.js' ),
1164
				false,
1165
				'1.3'
1166
			);
1167
		}
1168
1169 View Code Duplication
		if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
1170
			wp_register_script(
1171
				'jquery.spin',
1172
				Assets::get_file_url_for_environment( '_inc/build/jquery.spin.min.js', '_inc/jquery.spin.js' ),
1173
				array( 'jquery', 'spin' ),
1174
				'1.3'
1175
			);
1176
		}
1177
1178 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1179
			wp_register_script(
1180
				'jetpack-gallery-settings',
1181
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1182
				array( 'media-views' ),
1183
				'20121225'
1184
			);
1185
		}
1186
1187 View Code Duplication
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1188
			wp_register_script(
1189
				'jetpack-twitter-timeline',
1190
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1191
				array( 'jquery' ),
1192
				'4.0.0',
1193
				true
1194
			);
1195
		}
1196
1197
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1198
			wp_register_script(
1199
				'jetpack-facebook-embed',
1200
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1201
				array(),
1202
				null,
1203
				true
1204
			);
1205
1206
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1207
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1208
			if ( ! is_numeric( $fb_app_id ) ) {
1209
				$fb_app_id = '';
1210
			}
1211
			wp_localize_script(
1212
				'jetpack-facebook-embed',
1213
				'jpfbembed',
1214
				array(
1215
					'appid'  => $fb_app_id,
1216
					'locale' => $this->get_locale(),
1217
				)
1218
			);
1219
		}
1220
1221
		/**
1222
		 * As jetpack_register_genericons is by default fired off a hook,
1223
		 * the hook may have already fired by this point.
1224
		 * So, let's just trigger it manually.
1225
		 */
1226
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1227
		jetpack_register_genericons();
1228
1229
		/**
1230
		 * Register the social logos
1231
		 */
1232
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1233
		jetpack_register_social_logos();
1234
1235 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1236
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1237
		}
1238
	}
1239
1240
	/**
1241
	 * Guess locale from language code.
1242
	 *
1243
	 * @param string $lang Language code.
1244
	 * @return string|bool
1245
	 */
1246 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1247
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1248
			return 'en_US';
1249
		}
1250
1251
		if ( ! class_exists( 'GP_Locales' ) ) {
1252
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1253
				return false;
1254
			}
1255
1256
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1257
		}
1258
1259
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1260
			// WP.com: get_locale() returns 'it'
1261
			$locale = GP_Locales::by_slug( $lang );
1262
		} else {
1263
			// Jetpack: get_locale() returns 'it_IT';
1264
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1265
		}
1266
1267
		if ( ! $locale ) {
1268
			return false;
1269
		}
1270
1271
		if ( empty( $locale->facebook_locale ) ) {
1272
			if ( empty( $locale->wp_locale ) ) {
1273
				return false;
1274
			} else {
1275
				// Facebook SDK is smart enough to fall back to en_US if a
1276
				// locale isn't supported. Since supported Facebook locales
1277
				// can fall out of sync, we'll attempt to use the known
1278
				// wp_locale value and rely on said fallback.
1279
				return $locale->wp_locale;
1280
			}
1281
		}
1282
1283
		return $locale->facebook_locale;
1284
	}
1285
1286
	/**
1287
	 * Get the locale.
1288
	 *
1289
	 * @return string|bool
1290
	 */
1291
	function get_locale() {
1292
		$locale = $this->guess_locale_from_lang( get_locale() );
1293
1294
		if ( ! $locale ) {
1295
			$locale = 'en_US';
1296
		}
1297
1298
		return $locale;
1299
	}
1300
1301
	/**
1302
	 * Return the network_site_url so that .com knows what network this site is a part of.
1303
	 *
1304
	 * @param  bool $option
1305
	 * @return string
1306
	 */
1307
	public function jetpack_main_network_site_option( $option ) {
1308
		return network_site_url();
1309
	}
1310
	/**
1311
	 * Network Name.
1312
	 */
1313
	static function network_name( $option = null ) {
1314
		global $current_site;
1315
		return $current_site->site_name;
1316
	}
1317
	/**
1318
	 * Does the network allow new user and site registrations.
1319
	 *
1320
	 * @return string
1321
	 */
1322
	static function network_allow_new_registrations( $option = null ) {
1323
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1324
	}
1325
	/**
1326
	 * Does the network allow admins to add new users.
1327
	 *
1328
	 * @return boolian
1329
	 */
1330
	static function network_add_new_users( $option = null ) {
1331
		return (bool) get_site_option( 'add_new_users' );
1332
	}
1333
	/**
1334
	 * File upload psace left per site in MB.
1335
	 *  -1 means NO LIMIT.
1336
	 *
1337
	 * @return number
1338
	 */
1339
	static function network_site_upload_space( $option = null ) {
1340
		// value in MB
1341
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1342
	}
1343
1344
	/**
1345
	 * Network allowed file types.
1346
	 *
1347
	 * @return string
1348
	 */
1349
	static function network_upload_file_types( $option = null ) {
1350
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1351
	}
1352
1353
	/**
1354
	 * Maximum file upload size set by the network.
1355
	 *
1356
	 * @return number
1357
	 */
1358
	static function network_max_upload_file_size( $option = null ) {
1359
		// value in KB
1360
		return get_site_option( 'fileupload_maxk', 300 );
1361
	}
1362
1363
	/**
1364
	 * Lets us know if a site allows admins to manage the network.
1365
	 *
1366
	 * @return array
1367
	 */
1368
	static function network_enable_administration_menus( $option = null ) {
1369
		return get_site_option( 'menu_items' );
1370
	}
1371
1372
	/**
1373
	 * If a user has been promoted to or demoted from admin, we need to clear the
1374
	 * jetpack_other_linked_admins transient.
1375
	 *
1376
	 * @since 4.3.2
1377
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1378
	 *
1379
	 * @param int    $user_id   The user ID whose role changed.
1380
	 * @param string $role      The new role.
1381
	 * @param array  $old_roles An array of the user's previous roles.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $old_roles not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1382
	 */
1383
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1384
		if ( 'administrator' == $role
1385
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1386
			|| is_null( $old_roles )
1387
		) {
1388
			delete_transient( 'jetpack_other_linked_admins' );
1389
		}
1390
	}
1391
1392
	/**
1393
	 * Checks to see if there are any other users available to become primary
1394
	 * Users must both:
1395
	 * - Be linked to wpcom
1396
	 * - Be an admin
1397
	 *
1398
	 * @return mixed False if no other users are linked, Int if there are.
1399
	 */
1400
	static function get_other_linked_admins() {
1401
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1402
1403
		if ( false === $other_linked_users ) {
1404
			$admins = get_users( array( 'role' => 'administrator' ) );
1405
			if ( count( $admins ) > 1 ) {
1406
				$available = array();
1407
				foreach ( $admins as $admin ) {
1408
					if ( self::is_user_connected( $admin->ID ) ) {
1409
						$available[] = $admin->ID;
1410
					}
1411
				}
1412
1413
				$count_connected_admins = count( $available );
1414
				if ( count( $available ) > 1 ) {
1415
					$other_linked_users = $count_connected_admins;
1416
				} else {
1417
					$other_linked_users = 0;
1418
				}
1419
			} else {
1420
				$other_linked_users = 0;
1421
			}
1422
1423
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1424
		}
1425
1426
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1427
	}
1428
1429
	/**
1430
	 * Return whether we are dealing with a multi network setup or not.
1431
	 * The reason we are type casting this is because we want to avoid the situation where
1432
	 * the result is false since when is_main_network_option return false it cases
1433
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1434
	 * database which could be set to anything as opposed to what this function returns.
1435
	 *
1436
	 * @param  bool $option
1437
	 *
1438
	 * @return boolean
1439
	 */
1440
	public function is_main_network_option( $option ) {
1441
		// return '1' or ''
1442
		return (string) (bool) self::is_multi_network();
1443
	}
1444
1445
	/**
1446
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1447
	 *
1448
	 * @param  string $option
1449
	 * @return boolean
1450
	 */
1451
	public function is_multisite( $option ) {
1452
		return (string) (bool) is_multisite();
1453
	}
1454
1455
	/**
1456
	 * Implemented since there is no core is multi network function
1457
	 * Right now there is no way to tell if we which network is the dominant network on the system
1458
	 *
1459
	 * @since  3.3
1460
	 * @return boolean
1461
	 */
1462 View Code Duplication
	public static function is_multi_network() {
1463
		global  $wpdb;
1464
1465
		// if we don't have a multi site setup no need to do any more
1466
		if ( ! is_multisite() ) {
1467
			return false;
1468
		}
1469
1470
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1471
		if ( $num_sites > 1 ) {
1472
			return true;
1473
		} else {
1474
			return false;
1475
		}
1476
	}
1477
1478
	/**
1479
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1480
	 *
1481
	 * @return null
1482
	 */
1483
	function update_jetpack_main_network_site_option() {
1484
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1485
	}
1486
	/**
1487
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1488
	 */
1489
	function update_jetpack_network_settings() {
1490
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1491
		// Only sync this info for the main network site.
1492
	}
1493
1494
	/**
1495
	 * Get back if the current site is single user site.
1496
	 *
1497
	 * @return bool
1498
	 */
1499 View Code Duplication
	public static function is_single_user_site() {
1500
		global $wpdb;
1501
1502
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1503
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1504
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1505
		}
1506
		return 1 === (int) $some_users;
1507
	}
1508
1509
	/**
1510
	 * Returns true if the site has file write access false otherwise.
1511
	 *
1512
	 * @return string ( '1' | '0' )
1513
	 **/
1514
	public static function file_system_write_access() {
1515
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1516
			require_once ABSPATH . 'wp-admin/includes/file.php';
1517
		}
1518
1519
		require_once ABSPATH . 'wp-admin/includes/template.php';
1520
1521
		$filesystem_method = get_filesystem_method();
1522
		if ( $filesystem_method === 'direct' ) {
1523
			return 1;
1524
		}
1525
1526
		ob_start();
1527
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1528
		ob_end_clean();
1529
		if ( $filesystem_credentials_are_stored ) {
1530
			return 1;
1531
		}
1532
		return 0;
1533
	}
1534
1535
	/**
1536
	 * Finds out if a site is using a version control system.
1537
	 *
1538
	 * @return string ( '1' | '0' )
1539
	 **/
1540
	public static function is_version_controlled() {
1541
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1542
		return (string) (int) Functions::is_version_controlled();
1543
	}
1544
1545
	/**
1546
	 * Determines whether the current theme supports featured images or not.
1547
	 *
1548
	 * @return string ( '1' | '0' )
1549
	 */
1550
	public static function featured_images_enabled() {
1551
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1552
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1553
	}
1554
1555
	/**
1556
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1557
	 *
1558
	 * @deprecated 4.7 use get_avatar_url instead.
1559
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1560
	 * @param int               $size Size of the avatar image
1561
	 * @param string            $default URL to a default image to use if no avatar is available
1562
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1563
	 *
1564
	 * @return array
1565
	 */
1566
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1567
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1568
		return get_avatar_url(
1569
			$id_or_email,
1570
			array(
1571
				'size'          => $size,
1572
				'default'       => $default,
1573
				'force_default' => $force_display,
1574
			)
1575
		);
1576
	}
1577
1578
	/**
1579
	 * jetpack_updates is saved in the following schema:
1580
	 *
1581
	 * array (
1582
	 *      'plugins'                       => (int) Number of plugin updates available.
1583
	 *      'themes'                        => (int) Number of theme updates available.
1584
	 *      'wordpress'                     => (int) Number of WordPress core updates available. // phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
1585
	 *      'translations'                  => (int) Number of translation updates available.
1586
	 *      'total'                         => (int) Total of all available updates.
1587
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1588
	 * )
1589
	 *
1590
	 * @return array
1591
	 */
1592
	public static function get_updates() {
1593
		$update_data = wp_get_update_data();
1594
1595
		// Stores the individual update counts as well as the total count.
1596
		if ( isset( $update_data['counts'] ) ) {
1597
			$updates = $update_data['counts'];
1598
		}
1599
1600
		// If we need to update WordPress core, let's find the latest version number.
1601 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1602
			$cur = get_preferred_from_update_core();
1603
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1604
				$updates['wp_update_version'] = $cur->current;
1605
			}
1606
		}
1607
		return isset( $updates ) ? $updates : array();
1608
	}
1609
1610
	public static function get_update_details() {
1611
		$update_details = array(
1612
			'update_core'    => get_site_transient( 'update_core' ),
1613
			'update_plugins' => get_site_transient( 'update_plugins' ),
1614
			'update_themes'  => get_site_transient( 'update_themes' ),
1615
		);
1616
		return $update_details;
1617
	}
1618
1619
	public static function refresh_update_data() {
1620
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1621
1622
	}
1623
1624
	public static function refresh_theme_data() {
1625
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1626
	}
1627
1628
	/**
1629
	 * Is Jetpack active?
1630
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1631
	 *
1632
	 * @return bool
1633
	 */
1634
	public static function is_active() {
1635
		return self::connection()->is_active();
1636
	}
1637
1638
	/**
1639
	 * Make an API call to WordPress.com for plan status
1640
	 *
1641
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1642
	 *
1643
	 * @return bool True if plan is updated, false if no update
1644
	 */
1645
	public static function refresh_active_plan_from_wpcom() {
1646
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1647
		return Jetpack_Plan::refresh_from_wpcom();
1648
	}
1649
1650
	/**
1651
	 * Get the plan that this Jetpack site is currently using
1652
	 *
1653
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1654
	 * @return array Active Jetpack plan details.
1655
	 */
1656
	public static function get_active_plan() {
1657
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1658
		return Jetpack_Plan::get();
1659
	}
1660
1661
	/**
1662
	 * Determine whether the active plan supports a particular feature
1663
	 *
1664
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1665
	 * @return bool True if plan supports feature, false if not.
1666
	 */
1667
	public static function active_plan_supports( $feature ) {
1668
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1669
		return Jetpack_Plan::supports( $feature );
1670
	}
1671
1672
	/**
1673
	 * Deprecated: Is Jetpack in development (offline) mode?
1674
	 *
1675
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1676
	 * and themes still use it, and we do not want to flood them with notices.
1677
	 *
1678
	 * Please use Automattic\Jetpack\Status()->is_development_mode() instead.
1679
	 *
1680
	 * @deprecated since 8.0.
1681
	 */
1682
	public static function is_development_mode() {
1683
		return ( new Status() )->is_development_mode();
1684
	}
1685
1686
	/**
1687
	 * Whether the site is currently onboarding or not.
1688
	 * A site is considered as being onboarded if it currently has an onboarding token.
1689
	 *
1690
	 * @since 5.8
1691
	 *
1692
	 * @access public
1693
	 * @static
1694
	 *
1695
	 * @return bool True if the site is currently onboarding, false otherwise
1696
	 */
1697
	public static function is_onboarding() {
1698
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1699
	}
1700
1701
	/**
1702
	 * Determines reason for Jetpack development mode.
1703
	 */
1704
	public static function development_mode_trigger_text() {
1705
		if ( ! ( new Status() )->is_development_mode() ) {
1706
			return __( 'Jetpack is not in Development Mode.', 'jetpack' );
1707
		}
1708
1709
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1710
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1711
		} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
1712
			$notice = __( 'The site URL lacking a dot (e.g. http://localhost).', 'jetpack' );
1713
		} else {
1714
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1715
		}
1716
1717
		return $notice;
1718
1719
	}
1720
	/**
1721
	 * Get Jetpack development mode notice text and notice class.
1722
	 *
1723
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_development_mode
1724
	 */
1725
	public static function show_development_mode_notice() {
1726 View Code Duplication
		if ( ( new Status() )->is_development_mode() ) {
1727
			$notice = sprintf(
1728
				/* translators: %s is a URL */
1729
				__( 'In <a href="%s" target="_blank">Development Mode</a>:', 'jetpack' ),
1730
				Redirect::get_url( 'jetpack-support-development-mode' )
1731
			);
1732
1733
			$notice .= ' ' . self::development_mode_trigger_text();
1734
1735
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1736
		}
1737
1738
		// Throw up a notice if using a development version and as for feedback.
1739
		if ( self::is_development_version() ) {
1740
			/* translators: %s is a URL */
1741
			$notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), Redirect::get_url( 'jetpack-contact-support-beta-group' ) );
1742
1743
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1744
		}
1745
		// Throw up a notice if using staging mode
1746 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1747
			/* translators: %s is a URL */
1748
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1749
1750
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1751
		}
1752
	}
1753
1754
	/**
1755
	 * Whether Jetpack's version maps to a public release, or a development version.
1756
	 */
1757
	public static function is_development_version() {
1758
		/**
1759
		 * Allows filtering whether this is a development version of Jetpack.
1760
		 *
1761
		 * This filter is especially useful for tests.
1762
		 *
1763
		 * @since 4.3.0
1764
		 *
1765
		 * @param bool $development_version Is this a develoment version of Jetpack?
1766
		 */
1767
		return (bool) apply_filters(
1768
			'jetpack_development_version',
1769
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1770
		);
1771
	}
1772
1773
	/**
1774
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1775
	 */
1776
	public static function is_user_connected( $user_id = false ) {
1777
		return self::connection()->is_user_connected( $user_id );
1778
	}
1779
1780
	/**
1781
	 * Get the wpcom user data of the current|specified connected user.
1782
	 */
1783 View Code Duplication
	public static function get_connected_user_data( $user_id = null ) {
1784
		// TODO: remove in favor of Connection_Manager->get_connected_user_data
1785
		if ( ! $user_id ) {
1786
			$user_id = get_current_user_id();
1787
		}
1788
1789
		$transient_key = "jetpack_connected_user_data_$user_id";
1790
1791
		if ( $cached_user_data = get_transient( $transient_key ) ) {
1792
			return $cached_user_data;
1793
		}
1794
1795
		$xml = new Jetpack_IXR_Client(
1796
			array(
1797
				'user_id' => $user_id,
1798
			)
1799
		);
1800
		$xml->query( 'wpcom.getUser' );
1801
		if ( ! $xml->isError() ) {
1802
			$user_data = $xml->getResponse();
1803
			set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
1804
			return $user_data;
1805
		}
1806
1807
		return false;
1808
	}
1809
1810
	/**
1811
	 * Get the wpcom email of the current|specified connected user.
1812
	 */
1813
	public static function get_connected_user_email( $user_id = null ) {
1814
		if ( ! $user_id ) {
1815
			$user_id = get_current_user_id();
1816
		}
1817
1818
		$xml = new Jetpack_IXR_Client(
1819
			array(
1820
				'user_id' => $user_id,
1821
			)
1822
		);
1823
		$xml->query( 'wpcom.getUserEmail' );
1824
		if ( ! $xml->isError() ) {
1825
			return $xml->getResponse();
1826
		}
1827
		return false;
1828
	}
1829
1830
	/**
1831
	 * Get the wpcom email of the master user.
1832
	 */
1833
	public static function get_master_user_email() {
1834
		$master_user_id = Jetpack_Options::get_option( 'master_user' );
1835
		if ( $master_user_id ) {
1836
			return self::get_connected_user_email( $master_user_id );
1837
		}
1838
		return '';
1839
	}
1840
1841
	/**
1842
	 * Whether the current user is the connection owner.
1843
	 *
1844
	 * @deprecated since 7.7
1845
	 *
1846
	 * @return bool Whether the current user is the connection owner.
1847
	 */
1848
	public function current_user_is_connection_owner() {
1849
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::is_connection_owner' );
1850
		return self::connection()->is_connection_owner();
1851
	}
1852
1853
	/**
1854
	 * Gets current user IP address.
1855
	 *
1856
	 * @param  bool $check_all_headers Check all headers? Default is `false`.
1857
	 *
1858
	 * @return string                  Current user IP address.
1859
	 */
1860
	public static function current_user_ip( $check_all_headers = false ) {
1861
		if ( $check_all_headers ) {
1862
			foreach ( array(
1863
				'HTTP_CF_CONNECTING_IP',
1864
				'HTTP_CLIENT_IP',
1865
				'HTTP_X_FORWARDED_FOR',
1866
				'HTTP_X_FORWARDED',
1867
				'HTTP_X_CLUSTER_CLIENT_IP',
1868
				'HTTP_FORWARDED_FOR',
1869
				'HTTP_FORWARDED',
1870
				'HTTP_VIA',
1871
			) as $key ) {
1872
				if ( ! empty( $_SERVER[ $key ] ) ) {
1873
					return $_SERVER[ $key ];
1874
				}
1875
			}
1876
		}
1877
1878
		return ! empty( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
1879
	}
1880
1881
	/**
1882
	 * Synchronize connected user role changes
1883
	 */
1884
	function user_role_change( $user_id ) {
1885
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Users::user_role_change()' );
1886
		Users::user_role_change( $user_id );
1887
	}
1888
1889
	/**
1890
	 * Loads the currently active modules.
1891
	 */
1892
	public static function load_modules() {
1893
		$is_development_mode = ( new Status() )->is_development_mode();
1894
		if (
1895
			! self::is_active()
1896
			&& ! $is_development_mode
1897
			&& ! self::is_onboarding()
1898
			&& (
1899
				! is_multisite()
1900
				|| ! get_site_option( 'jetpack_protect_active' )
1901
			)
1902
		) {
1903
			return;
1904
		}
1905
1906
		$version = Jetpack_Options::get_option( 'version' );
1907 View Code Duplication
		if ( ! $version ) {
1908
			$version = $old_version = JETPACK__VERSION . ':' . time();
1909
			/** This action is documented in class.jetpack.php */
1910
			do_action( 'updating_jetpack_version', $version, false );
1911
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1912
		}
1913
		list( $version ) = explode( ':', $version );
1914
1915
		$modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1916
1917
		$modules_data = array();
1918
1919
		// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1920
		if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1921
			$updated_modules = array();
1922
			foreach ( $modules as $module ) {
1923
				$modules_data[ $module ] = self::get_module( $module );
1924
				if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1925
					continue;
1926
				}
1927
1928
				if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1929
					continue;
1930
				}
1931
1932
				$updated_modules[] = $module;
1933
			}
1934
1935
			$modules = array_diff( $modules, $updated_modules );
1936
		}
1937
1938
		foreach ( $modules as $index => $module ) {
1939
			// If we're in dev mode, disable modules requiring a connection
1940
			if ( $is_development_mode ) {
1941
				// Prime the pump if we need to
1942
				if ( empty( $modules_data[ $module ] ) ) {
1943
					$modules_data[ $module ] = self::get_module( $module );
1944
				}
1945
				// If the module requires a connection, but we're in local mode, don't include it.
1946
				if ( $modules_data[ $module ]['requires_connection'] ) {
1947
					continue;
1948
				}
1949
			}
1950
1951
			if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1952
				continue;
1953
			}
1954
1955
			if ( ! include_once self::get_module_path( $module ) ) {
1956
				unset( $modules[ $index ] );
1957
				self::update_active_modules( array_values( $modules ) );
1958
				continue;
1959
			}
1960
1961
			/**
1962
			 * Fires when a specific module is loaded.
1963
			 * The dynamic part of the hook, $module, is the module slug.
1964
			 *
1965
			 * @since 1.1.0
1966
			 */
1967
			do_action( 'jetpack_module_loaded_' . $module );
1968
		}
1969
1970
		/**
1971
		 * Fires when all the modules are loaded.
1972
		 *
1973
		 * @since 1.1.0
1974
		 */
1975
		do_action( 'jetpack_modules_loaded' );
1976
1977
		// 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.
1978
		require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
1979
	}
1980
1981
	/**
1982
	 * Check if Jetpack's REST API compat file should be included
1983
	 *
1984
	 * @action plugins_loaded
1985
	 * @return null
1986
	 */
1987
	public function check_rest_api_compat() {
1988
		/**
1989
		 * Filters the list of REST API compat files to be included.
1990
		 *
1991
		 * @since 2.2.5
1992
		 *
1993
		 * @param array $args Array of REST API compat files to include.
1994
		 */
1995
		$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
1996
1997
		foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
1998
			require_once $_jetpack_rest_api_compat_include;
1999
		}
2000
	}
2001
2002
	/**
2003
	 * Gets all plugins currently active in values, regardless of whether they're
2004
	 * traditionally activated or network activated.
2005
	 *
2006
	 * @todo Store the result in core's object cache maybe?
2007
	 */
2008
	public static function get_active_plugins() {
2009
		$active_plugins = (array) get_option( 'active_plugins', array() );
2010
2011
		if ( is_multisite() ) {
2012
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
2013
			// whereas active_plugins stores them in the values.
2014
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
2015
			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...
2016
				$active_plugins = array_merge( $active_plugins, $network_plugins );
2017
			}
2018
		}
2019
2020
		sort( $active_plugins );
2021
2022
		return array_unique( $active_plugins );
2023
	}
2024
2025
	/**
2026
	 * Gets and parses additional plugin data to send with the heartbeat data
2027
	 *
2028
	 * @since 3.8.1
2029
	 *
2030
	 * @return array Array of plugin data
2031
	 */
2032
	public static function get_parsed_plugin_data() {
2033
		if ( ! function_exists( 'get_plugins' ) ) {
2034
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
2035
		}
2036
		/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2037
		$all_plugins    = apply_filters( 'all_plugins', get_plugins() );
2038
		$active_plugins = self::get_active_plugins();
2039
2040
		$plugins = array();
2041
		foreach ( $all_plugins as $path => $plugin_data ) {
2042
			$plugins[ $path ] = array(
2043
				'is_active' => in_array( $path, $active_plugins ),
2044
				'file'      => $path,
2045
				'name'      => $plugin_data['Name'],
2046
				'version'   => $plugin_data['Version'],
2047
				'author'    => $plugin_data['Author'],
2048
			);
2049
		}
2050
2051
		return $plugins;
2052
	}
2053
2054
	/**
2055
	 * Gets and parses theme data to send with the heartbeat data
2056
	 *
2057
	 * @since 3.8.1
2058
	 *
2059
	 * @return array Array of theme data
2060
	 */
2061
	public static function get_parsed_theme_data() {
2062
		$all_themes  = wp_get_themes( array( 'allowed' => true ) );
2063
		$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2064
2065
		$themes = array();
2066
		foreach ( $all_themes as $slug => $theme_data ) {
2067
			$theme_headers = array();
2068
			foreach ( $header_keys as $header_key ) {
2069
				$theme_headers[ $header_key ] = $theme_data->get( $header_key );
2070
			}
2071
2072
			$themes[ $slug ] = array(
2073
				'is_active_theme' => $slug == wp_get_theme()->get_template(),
2074
				'slug'            => $slug,
2075
				'theme_root'      => $theme_data->get_theme_root_uri(),
2076
				'parent'          => $theme_data->parent(),
2077
				'headers'         => $theme_headers,
2078
			);
2079
		}
2080
2081
		return $themes;
2082
	}
2083
2084
	/**
2085
	 * Checks whether a specific plugin is active.
2086
	 *
2087
	 * We don't want to store these in a static variable, in case
2088
	 * there are switch_to_blog() calls involved.
2089
	 */
2090
	public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2091
		return in_array( $plugin, self::get_active_plugins() );
2092
	}
2093
2094
	/**
2095
	 * Check if Jetpack's Open Graph tags should be used.
2096
	 * If certain plugins are active, Jetpack's og tags are suppressed.
2097
	 *
2098
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2099
	 * @action plugins_loaded
2100
	 * @return null
2101
	 */
2102
	public function check_open_graph() {
2103
		if ( in_array( 'publicize', self::get_active_modules() ) || in_array( 'sharedaddy', self::get_active_modules() ) ) {
2104
			add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2105
		}
2106
2107
		$active_plugins = self::get_active_plugins();
2108
2109
		if ( ! empty( $active_plugins ) ) {
2110
			foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2111
				if ( in_array( $plugin, $active_plugins ) ) {
2112
					add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2113
					break;
2114
				}
2115
			}
2116
		}
2117
2118
		/**
2119
		 * Allow the addition of Open Graph Meta Tags to all pages.
2120
		 *
2121
		 * @since 2.0.3
2122
		 *
2123
		 * @param bool false Should Open Graph Meta tags be added. Default to false.
2124
		 */
2125
		if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2126
			require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2127
		}
2128
	}
2129
2130
	/**
2131
	 * Check if Jetpack's Twitter tags should be used.
2132
	 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2133
	 *
2134
	 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2135
	 * @action plugins_loaded
2136
	 * @return null
2137
	 */
2138
	public function check_twitter_tags() {
2139
2140
		$active_plugins = self::get_active_plugins();
2141
2142
		if ( ! empty( $active_plugins ) ) {
2143
			foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2144
				if ( in_array( $plugin, $active_plugins ) ) {
2145
					add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2146
					break;
2147
				}
2148
			}
2149
		}
2150
2151
		/**
2152
		 * Allow Twitter Card Meta tags to be disabled.
2153
		 *
2154
		 * @since 2.6.0
2155
		 *
2156
		 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2157
		 */
2158
		if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2159
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2160
		}
2161
	}
2162
2163
	/**
2164
	 * Allows plugins to submit security reports.
2165
	 *
2166
	 * @param string $type         Report type (login_form, backup, file_scanning, spam)
2167
	 * @param string $plugin_file  Plugin __FILE__, so that we can pull plugin data
2168
	 * @param array  $args         See definitions above
2169
	 */
2170
	public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
2171
		_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
2172
	}
2173
2174
	/* Jetpack Options API */
2175
2176
	public static function get_option_names( $type = 'compact' ) {
2177
		return Jetpack_Options::get_option_names( $type );
2178
	}
2179
2180
	/**
2181
	 * Returns the requested option.  Looks in jetpack_options or jetpack_$name as appropriate.
2182
	 *
2183
	 * @param string $name    Option name
2184
	 * @param mixed  $default (optional)
2185
	 */
2186
	public static function get_option( $name, $default = false ) {
2187
		return Jetpack_Options::get_option( $name, $default );
2188
	}
2189
2190
	/**
2191
	 * Updates the single given option.  Updates jetpack_options or jetpack_$name as appropriate.
2192
	 *
2193
	 * @deprecated 3.4 use Jetpack_Options::update_option() instead.
2194
	 * @param string $name  Option name
2195
	 * @param mixed  $value Option value
2196
	 */
2197
	public static function update_option( $name, $value ) {
2198
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
2199
		return Jetpack_Options::update_option( $name, $value );
2200
	}
2201
2202
	/**
2203
	 * Updates the multiple given options.  Updates jetpack_options and/or jetpack_$name as appropriate.
2204
	 *
2205
	 * @deprecated 3.4 use Jetpack_Options::update_options() instead.
2206
	 * @param array $array array( option name => option value, ... )
2207
	 */
2208
	public static function update_options( $array ) {
2209
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
2210
		return Jetpack_Options::update_options( $array );
2211
	}
2212
2213
	/**
2214
	 * Deletes the given option.  May be passed multiple option names as an array.
2215
	 * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
2216
	 *
2217
	 * @deprecated 3.4 use Jetpack_Options::delete_option() instead.
2218
	 * @param string|array $names
2219
	 */
2220
	public static function delete_option( $names ) {
2221
		_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
2222
		return Jetpack_Options::delete_option( $names );
2223
	}
2224
2225
	/**
2226
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::update_user_token() instead.
2227
	 *
2228
	 * Enters a user token into the user_tokens option
2229
	 *
2230
	 * @param int    $user_id The user id.
2231
	 * @param string $token The user token.
2232
	 * @param bool   $is_master_user Whether the user is the master user.
2233
	 * @return bool
2234
	 */
2235
	public static function update_user_token( $user_id, $token, $is_master_user ) {
2236
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::update_user_token' );
2237
		return Connection_Utils::update_user_token( $user_id, $token, $is_master_user );
2238
	}
2239
2240
	/**
2241
	 * Returns an array of all PHP files in the specified absolute path.
2242
	 * Equivalent to glob( "$absolute_path/*.php" ).
2243
	 *
2244
	 * @param string $absolute_path The absolute path of the directory to search.
2245
	 * @return array Array of absolute paths to the PHP files.
2246
	 */
2247
	public static function glob_php( $absolute_path ) {
2248
		if ( function_exists( 'glob' ) ) {
2249
			return glob( "$absolute_path/*.php" );
2250
		}
2251
2252
		$absolute_path = untrailingslashit( $absolute_path );
2253
		$files         = array();
2254
		if ( ! $dir = @opendir( $absolute_path ) ) {
2255
			return $files;
2256
		}
2257
2258
		while ( false !== $file = readdir( $dir ) ) {
2259
			if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
2260
				continue;
2261
			}
2262
2263
			$file = "$absolute_path/$file";
2264
2265
			if ( ! is_file( $file ) ) {
2266
				continue;
2267
			}
2268
2269
			$files[] = $file;
2270
		}
2271
2272
		closedir( $dir );
2273
2274
		return $files;
2275
	}
2276
2277
	public static function activate_new_modules( $redirect = false ) {
2278
		if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
2279
			return;
2280
		}
2281
2282
		$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
2283 View Code Duplication
		if ( ! $jetpack_old_version ) {
2284
			$jetpack_old_version = $version = $old_version = '1.1:' . time();
2285
			/** This action is documented in class.jetpack.php */
2286
			do_action( 'updating_jetpack_version', $version, false );
2287
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2288
		}
2289
2290
		list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
2291
2292
		if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2293
			return;
2294
		}
2295
2296
		$active_modules     = self::get_active_modules();
2297
		$reactivate_modules = array();
2298
		foreach ( $active_modules as $active_module ) {
2299
			$module = self::get_module( $active_module );
2300
			if ( ! isset( $module['changed'] ) ) {
2301
				continue;
2302
			}
2303
2304
			if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2305
				continue;
2306
			}
2307
2308
			$reactivate_modules[] = $active_module;
2309
			self::deactivate_module( $active_module );
2310
		}
2311
2312
		$new_version = JETPACK__VERSION . ':' . time();
2313
		/** This action is documented in class.jetpack.php */
2314
		do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2315
		Jetpack_Options::update_options(
2316
			array(
2317
				'version'     => $new_version,
2318
				'old_version' => $jetpack_old_version,
2319
			)
2320
		);
2321
2322
		self::state( 'message', 'modules_activated' );
2323
2324
		self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
0 ignored issues
show
Documentation introduced by
JETPACK__VERSION is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
2325
2326
		if ( $redirect ) {
2327
			$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
2328
			if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
2329
				$page = $_GET['page'];
2330
			}
2331
2332
			wp_safe_redirect( self::admin_url( 'page=' . $page ) );
2333
			exit;
2334
		}
2335
	}
2336
2337
	/**
2338
	 * List available Jetpack modules. Simply lists .php files in /modules/.
2339
	 * Make sure to tuck away module "library" files in a sub-directory.
2340
	 */
2341
	public static function get_available_modules( $min_version = false, $max_version = false ) {
2342
		static $modules = null;
2343
2344
		if ( ! isset( $modules ) ) {
2345
			$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
2346
			// Use the cache if we're on the front-end and it's available...
2347
			if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
2348
				$modules = $available_modules_option[ JETPACK__VERSION ];
2349
			} else {
2350
				$files = self::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
2351
2352
				$modules = array();
2353
2354
				foreach ( $files as $file ) {
2355
					if ( ! $headers = self::get_module( $file ) ) {
2356
						continue;
2357
					}
2358
2359
					$modules[ self::get_module_slug( $file ) ] = $headers['introduced'];
2360
				}
2361
2362
				Jetpack_Options::update_option(
2363
					'available_modules',
2364
					array(
2365
						JETPACK__VERSION => $modules,
2366
					)
2367
				);
2368
			}
2369
		}
2370
2371
		/**
2372
		 * Filters the array of modules available to be activated.
2373
		 *
2374
		 * @since 2.4.0
2375
		 *
2376
		 * @param array $modules Array of available modules.
2377
		 * @param string $min_version Minimum version number required to use modules.
2378
		 * @param string $max_version Maximum version number required to use modules.
2379
		 */
2380
		$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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...
2381
2382
		if ( ! $min_version && ! $max_version ) {
2383
			return array_keys( $mods );
2384
		}
2385
2386
		$r = array();
2387
		foreach ( $mods as $slug => $introduced ) {
2388
			if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
2389
				continue;
2390
			}
2391
2392
			if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
2393
				continue;
2394
			}
2395
2396
			$r[] = $slug;
2397
		}
2398
2399
		return $r;
2400
	}
2401
2402
	/**
2403
	 * Default modules loaded on activation.
2404
	 */
2405
	public static function get_default_modules( $min_version = false, $max_version = false ) {
2406
		$return = array();
2407
2408
		foreach ( self::get_available_modules( $min_version, $max_version ) as $module ) {
2409
			$module_data = self::get_module( $module );
2410
2411
			switch ( strtolower( $module_data['auto_activate'] ) ) {
2412
				case 'yes':
2413
					$return[] = $module;
2414
					break;
2415
				case 'public':
2416
					if ( Jetpack_Options::get_option( 'public' ) ) {
2417
						$return[] = $module;
2418
					}
2419
					break;
2420
				case 'no':
2421
				default:
2422
					break;
2423
			}
2424
		}
2425
		/**
2426
		 * Filters the array of default modules.
2427
		 *
2428
		 * @since 2.5.0
2429
		 *
2430
		 * @param array $return Array of default modules.
2431
		 * @param string $min_version Minimum version number required to use modules.
2432
		 * @param string $max_version Maximum version number required to use modules.
2433
		 */
2434
		return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $min_version.

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...
2435
	}
2436
2437
	/**
2438
	 * Checks activated modules during auto-activation to determine
2439
	 * if any of those modules are being deprecated.  If so, close
2440
	 * them out, and add any replacement modules.
2441
	 *
2442
	 * Runs at priority 99 by default.
2443
	 *
2444
	 * This is run late, so that it can still activate a module if
2445
	 * the new module is a replacement for another that the user
2446
	 * currently has active, even if something at the normal priority
2447
	 * would kibosh everything.
2448
	 *
2449
	 * @since 2.6
2450
	 * @uses jetpack_get_default_modules filter
2451
	 * @param array $modules
2452
	 * @return array
2453
	 */
2454
	function handle_deprecated_modules( $modules ) {
2455
		$deprecated_modules = array(
2456
			'debug'            => null,  // Closed out and moved to the debugger library.
2457
			'wpcc'             => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2458
			'gplus-authorship' => null,  // Closed out in 3.2 -- Google dropped support.
2459
			'minileven'        => null,  // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2460
		);
2461
2462
		// Don't activate SSO if they never completed activating WPCC.
2463
		if ( self::is_module_active( 'wpcc' ) ) {
2464
			$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2465
			if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2466
				$deprecated_modules['wpcc'] = null;
2467
			}
2468
		}
2469
2470
		foreach ( $deprecated_modules as $module => $replacement ) {
2471
			if ( self::is_module_active( $module ) ) {
2472
				self::deactivate_module( $module );
2473
				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...
2474
					$modules[] = $replacement;
2475
				}
2476
			}
2477
		}
2478
2479
		return array_unique( $modules );
2480
	}
2481
2482
	/**
2483
	 * Checks activated plugins during auto-activation to determine
2484
	 * if any of those plugins are in the list with a corresponding module
2485
	 * that is not compatible with the plugin. The module will not be allowed
2486
	 * to auto-activate.
2487
	 *
2488
	 * @since 2.6
2489
	 * @uses jetpack_get_default_modules filter
2490
	 * @param array $modules
2491
	 * @return array
2492
	 */
2493
	function filter_default_modules( $modules ) {
2494
2495
		$active_plugins = self::get_active_plugins();
2496
2497
		if ( ! empty( $active_plugins ) ) {
2498
2499
			// For each module we'd like to auto-activate...
2500
			foreach ( $modules as $key => $module ) {
2501
				// If there are potential conflicts for it...
2502
				if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2503
					// For each potential conflict...
2504
					foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
2505
						// If that conflicting plugin is active...
2506
						if ( in_array( $plugin, $active_plugins ) ) {
2507
							// Remove that item from being auto-activated.
2508
							unset( $modules[ $key ] );
2509
						}
2510
					}
2511
				}
2512
			}
2513
		}
2514
2515
		return $modules;
2516
	}
2517
2518
	/**
2519
	 * Extract a module's slug from its full path.
2520
	 */
2521
	public static function get_module_slug( $file ) {
2522
		return str_replace( '.php', '', basename( $file ) );
2523
	}
2524
2525
	/**
2526
	 * Generate a module's path from its slug.
2527
	 */
2528
	public static function get_module_path( $slug ) {
2529
		/**
2530
		 * Filters the path of a modules.
2531
		 *
2532
		 * @since 7.4.0
2533
		 *
2534
		 * @param array $return The absolute path to a module's root php file
2535
		 * @param string $slug The module slug
2536
		 */
2537
		return apply_filters( 'jetpack_get_module_path', JETPACK__PLUGIN_DIR . "modules/$slug.php", $slug );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $slug.

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...
2538
	}
2539
2540
	/**
2541
	 * Load module data from module file. Headers differ from WordPress
2542
	 * plugin headers to avoid them being identified as standalone
2543
	 * plugins on the WordPress plugins page.
2544
	 */
2545
	public static function get_module( $module ) {
2546
		$headers = array(
2547
			'name'                      => 'Module Name',
2548
			'description'               => 'Module Description',
2549
			'sort'                      => 'Sort Order',
2550
			'recommendation_order'      => 'Recommendation Order',
2551
			'introduced'                => 'First Introduced',
2552
			'changed'                   => 'Major Changes In',
2553
			'deactivate'                => 'Deactivate',
2554
			'free'                      => 'Free',
2555
			'requires_connection'       => 'Requires Connection',
2556
			'auto_activate'             => 'Auto Activate',
2557
			'module_tags'               => 'Module Tags',
2558
			'feature'                   => 'Feature',
2559
			'additional_search_queries' => 'Additional Search Queries',
2560
			'plan_classes'              => 'Plans',
2561
		);
2562
2563
		$file = self::get_module_path( self::get_module_slug( $module ) );
2564
2565
		$mod = self::get_file_data( $file, $headers );
2566
		if ( empty( $mod['name'] ) ) {
2567
			return false;
2568
		}
2569
2570
		$mod['sort']                 = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
2571
		$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
2572
		$mod['deactivate']           = empty( $mod['deactivate'] );
2573
		$mod['free']                 = empty( $mod['free'] );
2574
		$mod['requires_connection']  = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
2575
2576
		if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
2577
			$mod['auto_activate'] = 'No';
2578
		} else {
2579
			$mod['auto_activate'] = (string) $mod['auto_activate'];
2580
		}
2581
2582
		if ( $mod['module_tags'] ) {
2583
			$mod['module_tags'] = explode( ',', $mod['module_tags'] );
2584
			$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
2585
			$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
2586
		} else {
2587
			$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
2588
		}
2589
2590 View Code Duplication
		if ( $mod['plan_classes'] ) {
2591
			$mod['plan_classes'] = explode( ',', $mod['plan_classes'] );
2592
			$mod['plan_classes'] = array_map( 'strtolower', array_map( 'trim', $mod['plan_classes'] ) );
2593
		} else {
2594
			$mod['plan_classes'] = array( 'free' );
2595
		}
2596
2597 View Code Duplication
		if ( $mod['feature'] ) {
2598
			$mod['feature'] = explode( ',', $mod['feature'] );
2599
			$mod['feature'] = array_map( 'trim', $mod['feature'] );
2600
		} else {
2601
			$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
2602
		}
2603
2604
		/**
2605
		 * Filters the feature array on a module.
2606
		 *
2607
		 * This filter allows you to control where each module is filtered: Recommended,
2608
		 * and the default "Other" listing.
2609
		 *
2610
		 * @since 3.5.0
2611
		 *
2612
		 * @param array   $mod['feature'] The areas to feature this module:
2613
		 *     'Recommended' shows on the main Jetpack admin screen.
2614
		 *     'Other' should be the default if no other value is in the array.
2615
		 * @param string  $module The slug of the module, e.g. sharedaddy.
2616
		 * @param array   $mod All the currently assembled module data.
2617
		 */
2618
		$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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...
2619
2620
		/**
2621
		 * Filter the returned data about a module.
2622
		 *
2623
		 * This filter allows overriding any info about Jetpack modules. It is dangerous,
2624
		 * so please be careful.
2625
		 *
2626
		 * @since 3.6.0
2627
		 *
2628
		 * @param array   $mod    The details of the requested module.
2629
		 * @param string  $module The slug of the module, e.g. sharedaddy
2630
		 * @param string  $file   The path to the module source file.
2631
		 */
2632
		return apply_filters( 'jetpack_get_module', $mod, $module, $file );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $module.

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...
2633
	}
2634
2635
	/**
2636
	 * Like core's get_file_data implementation, but caches the result.
2637
	 */
2638
	public static function get_file_data( $file, $headers ) {
2639
		// Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
2640
		$file_name = basename( $file );
2641
2642
		$cache_key = 'jetpack_file_data_' . JETPACK__VERSION;
2643
2644
		$file_data_option = get_transient( $cache_key );
2645
2646
		if ( ! is_array( $file_data_option ) ) {
2647
			delete_transient( $cache_key );
2648
			$file_data_option = false;
2649
		}
2650
2651
		if ( false === $file_data_option ) {
2652
			$file_data_option = array();
2653
		}
2654
2655
		$key           = md5( $file_name . serialize( $headers ) );
2656
		$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
2657
2658
		// If we don't need to refresh the cache, and already have the value, short-circuit!
2659
		if ( ! $refresh_cache && isset( $file_data_option[ $key ] ) ) {
2660
			return $file_data_option[ $key ];
2661
		}
2662
2663
		$data = get_file_data( $file, $headers );
2664
2665
		$file_data_option[ $key ] = $data;
2666
2667
		set_transient( $cache_key, $file_data_option, 29 * DAY_IN_SECONDS );
2668
2669
		return $data;
2670
	}
2671
2672
2673
	/**
2674
	 * Return translated module tag.
2675
	 *
2676
	 * @param string $tag Tag as it appears in each module heading.
2677
	 *
2678
	 * @return mixed
2679
	 */
2680
	public static function translate_module_tag( $tag ) {
2681
		return jetpack_get_module_i18n_tag( $tag );
2682
	}
2683
2684
	/**
2685
	 * Get i18n strings as a JSON-encoded string
2686
	 *
2687
	 * @return string The locale as JSON
2688
	 */
2689
	public static function get_i18n_data_json() {
2690
2691
		// WordPress 5.0 uses md5 hashes of file paths to associate translation
2692
		// JSON files with the file they should be included for. This is an md5
2693
		// of '_inc/build/admin.js'.
2694
		$path_md5 = '1bac79e646a8bf4081a5011ab72d5807';
2695
2696
		$i18n_json =
2697
				   JETPACK__PLUGIN_DIR
2698
				   . 'languages/json/jetpack-'
2699
				   . get_user_locale()
2700
				   . '-'
2701
				   . $path_md5
2702
				   . '.json';
2703
2704
		if ( is_file( $i18n_json ) && is_readable( $i18n_json ) ) {
2705
			$locale_data = @file_get_contents( $i18n_json );
2706
			if ( $locale_data ) {
2707
				return $locale_data;
2708
			}
2709
		}
2710
2711
		// Return valid empty Jed locale
2712
		return '{ "locale_data": { "messages": { "": {} } } }';
2713
	}
2714
2715
	/**
2716
	 * Add locale data setup to wp-i18n
2717
	 *
2718
	 * Any Jetpack script that depends on wp-i18n should use this method to set up the locale.
2719
	 *
2720
	 * The locale setup depends on an adding inline script. This is error-prone and could easily
2721
	 * result in multiple additions of the same script when exactly 0 or 1 is desireable.
2722
	 *
2723
	 * This method provides a safe way to request the setup multiple times but add the script at
2724
	 * most once.
2725
	 *
2726
	 * @since 6.7.0
2727
	 *
2728
	 * @return void
2729
	 */
2730
	public static function setup_wp_i18n_locale_data() {
2731
		static $script_added = false;
2732
		if ( ! $script_added ) {
2733
			$script_added = true;
2734
			wp_add_inline_script(
2735
				'wp-i18n',
2736
				'wp.i18n.setLocaleData( ' . self::get_i18n_data_json() . ', \'jetpack\' );'
2737
			);
2738
		}
2739
	}
2740
2741
	/**
2742
	 * Return module name translation. Uses matching string created in modules/module-headings.php.
2743
	 *
2744
	 * @since 3.9.2
2745
	 *
2746
	 * @param array $modules
2747
	 *
2748
	 * @return string|void
2749
	 */
2750
	public static function get_translated_modules( $modules ) {
2751
		foreach ( $modules as $index => $module ) {
2752
			$i18n_module = jetpack_get_module_i18n( $module['module'] );
2753
			if ( isset( $module['name'] ) ) {
2754
				$modules[ $index ]['name'] = $i18n_module['name'];
2755
			}
2756
			if ( isset( $module['description'] ) ) {
2757
				$modules[ $index ]['description']       = $i18n_module['description'];
2758
				$modules[ $index ]['short_description'] = $i18n_module['description'];
2759
			}
2760
		}
2761
		return $modules;
2762
	}
2763
2764
	/**
2765
	 * Get a list of activated modules as an array of module slugs.
2766
	 */
2767
	public static function get_active_modules() {
2768
		$active = Jetpack_Options::get_option( 'active_modules' );
2769
2770
		if ( ! is_array( $active ) ) {
2771
			$active = array();
2772
		}
2773
2774
		if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
2775
			$active[] = 'vaultpress';
2776
		} else {
2777
			$active = array_diff( $active, array( 'vaultpress' ) );
2778
		}
2779
2780
		// If protect is active on the main site of a multisite, it should be active on all sites.
2781
		if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
2782
			$active[] = 'protect';
2783
		}
2784
2785
		/**
2786
		 * Allow filtering of the active modules.
2787
		 *
2788
		 * Gives theme and plugin developers the power to alter the modules that
2789
		 * are activated on the fly.
2790
		 *
2791
		 * @since 5.8.0
2792
		 *
2793
		 * @param array $active Array of active module slugs.
2794
		 */
2795
		$active = apply_filters( 'jetpack_active_modules', $active );
2796
2797
		return array_unique( $active );
2798
	}
2799
2800
	/**
2801
	 * Check whether or not a Jetpack module is active.
2802
	 *
2803
	 * @param string $module The slug of a Jetpack module.
2804
	 * @return bool
2805
	 *
2806
	 * @static
2807
	 */
2808
	public static function is_module_active( $module ) {
2809
		return in_array( $module, self::get_active_modules() );
2810
	}
2811
2812
	public static function is_module( $module ) {
2813
		return ! empty( $module ) && ! validate_file( $module, self::get_available_modules() );
2814
	}
2815
2816
	/**
2817
	 * Catches PHP errors.  Must be used in conjunction with output buffering.
2818
	 *
2819
	 * @param bool $catch True to start catching, False to stop.
2820
	 *
2821
	 * @static
2822
	 */
2823
	public static function catch_errors( $catch ) {
2824
		static $display_errors, $error_reporting;
2825
2826
		if ( $catch ) {
2827
			$display_errors  = @ini_set( 'display_errors', 1 );
2828
			$error_reporting = @error_reporting( E_ALL );
2829
			add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2830
		} else {
2831
			@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...
2832
			@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...
2833
			remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
2834
		}
2835
	}
2836
2837
	/**
2838
	 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2839
	 */
2840
	public static function catch_errors_on_shutdown() {
2841
		self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2842
	}
2843
2844
	/**
2845
	 * Rewrite any string to make paths easier to read.
2846
	 *
2847
	 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2848
	 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2849
	 *
2850
	 * @param $string
2851
	 * @return mixed
2852
	 */
2853
	public static function alias_directories( $string ) {
2854
		// ABSPATH has a trailing slash.
2855
		$string = str_replace( ABSPATH, 'ABSPATH/', $string );
2856
		// WP_CONTENT_DIR does not have a trailing slash.
2857
		$string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2858
2859
		return $string;
2860
	}
2861
2862
	public static function activate_default_modules(
2863
		$min_version = false,
2864
		$max_version = false,
2865
		$other_modules = array(),
2866
		$redirect = null,
2867
		$send_state_messages = null
2868
	) {
2869
		$jetpack = self::init();
2870
2871
		if ( is_null( $redirect ) ) {
2872
			if (
2873
				( defined( 'REST_REQUEST' ) && REST_REQUEST )
2874
			||
2875
				( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2876
			||
2877
				( defined( 'WP_CLI' ) && WP_CLI )
2878
			||
2879
				( defined( 'DOING_CRON' ) && DOING_CRON )
2880
			||
2881
				( defined( 'DOING_AJAX' ) && DOING_AJAX )
2882
			) {
2883
				$redirect = false;
2884
			} elseif ( is_admin() ) {
2885
				$redirect = true;
2886
			} else {
2887
				$redirect = false;
2888
			}
2889
		}
2890
2891
		if ( is_null( $send_state_messages ) ) {
2892
			$send_state_messages = current_user_can( 'jetpack_activate_modules' );
2893
		}
2894
2895
		$modules = self::get_default_modules( $min_version, $max_version );
2896
		$modules = array_merge( $other_modules, $modules );
2897
2898
		// Look for standalone plugins and disable if active.
2899
2900
		$to_deactivate = array();
2901
		foreach ( $modules as $module ) {
2902
			if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2903
				$to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2904
			}
2905
		}
2906
2907
		$deactivated = array();
2908
		foreach ( $to_deactivate as $module => $deactivate_me ) {
2909
			list( $probable_file, $probable_title ) = $deactivate_me;
2910
			if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2911
				$deactivated[] = $module;
2912
			}
2913
		}
2914
2915
		if ( $deactivated ) {
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...
2916
			if ( $send_state_messages ) {
2917
				self::state( 'deactivated_plugins', join( ',', $deactivated ) );
2918
			}
2919
2920
			if ( $redirect ) {
2921
				$url = add_query_arg(
2922
					array(
2923
						'action'   => 'activate_default_modules',
2924
						'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2925
					),
2926
					add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2927
				);
2928
				wp_safe_redirect( $url );
2929
				exit;
2930
			}
2931
		}
2932
2933
		/**
2934
		 * Fires before default modules are activated.
2935
		 *
2936
		 * @since 1.9.0
2937
		 *
2938
		 * @param string $min_version Minimum version number required to use modules.
2939
		 * @param string $max_version Maximum version number required to use modules.
2940
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
2941
		 */
2942
		do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
2943
2944
		// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
2945
		if ( $send_state_messages ) {
2946
			self::restate();
2947
			self::catch_errors( true );
2948
		}
2949
2950
		$active = self::get_active_modules();
2951
2952
		foreach ( $modules as $module ) {
2953
			if ( did_action( "jetpack_module_loaded_$module" ) ) {
2954
				$active[] = $module;
2955
				self::update_active_modules( $active );
2956
				continue;
2957
			}
2958
2959
			if ( $send_state_messages && in_array( $module, $active ) ) {
2960
				$module_info = self::get_module( $module );
2961 View Code Duplication
				if ( ! $module_info['deactivate'] ) {
2962
					$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2963
					if ( $active_state = self::state( $state ) ) {
2964
						$active_state = explode( ',', $active_state );
2965
					} else {
2966
						$active_state = array();
2967
					}
2968
					$active_state[] = $module;
2969
					self::state( $state, implode( ',', $active_state ) );
2970
				}
2971
				continue;
2972
			}
2973
2974
			$file = self::get_module_path( $module );
2975
			if ( ! file_exists( $file ) ) {
2976
				continue;
2977
			}
2978
2979
			// we'll override this later if the plugin can be included without fatal error
2980
			if ( $redirect ) {
2981
				wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2982
			}
2983
2984
			if ( $send_state_messages ) {
2985
				self::state( 'error', 'module_activation_failed' );
2986
				self::state( 'module', $module );
2987
			}
2988
2989
			ob_start();
2990
			require_once $file;
2991
2992
			$active[] = $module;
2993
2994 View Code Duplication
			if ( $send_state_messages ) {
2995
2996
				$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
2997
				if ( $active_state = self::state( $state ) ) {
2998
					$active_state = explode( ',', $active_state );
2999
				} else {
3000
					$active_state = array();
3001
				}
3002
				$active_state[] = $module;
3003
				self::state( $state, implode( ',', $active_state ) );
3004
			}
3005
3006
			self::update_active_modules( $active );
3007
3008
			ob_end_clean();
3009
		}
3010
3011
		if ( $send_state_messages ) {
3012
			self::state( 'error', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3013
			self::state( 'module', false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3014
		}
3015
3016
		self::catch_errors( false );
3017
		/**
3018
		 * Fires when default modules are activated.
3019
		 *
3020
		 * @since 1.9.0
3021
		 *
3022
		 * @param string $min_version Minimum version number required to use modules.
3023
		 * @param string $max_version Maximum version number required to use modules.
3024
		 * @param array $other_modules Array of other modules to activate alongside the default modules.
3025
		 */
3026
		do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
3027
	}
3028
3029
	public static function activate_module( $module, $exit = true, $redirect = true ) {
3030
		/**
3031
		 * Fires before a module is activated.
3032
		 *
3033
		 * @since 2.6.0
3034
		 *
3035
		 * @param string $module Module slug.
3036
		 * @param bool $exit Should we exit after the module has been activated. Default to true.
3037
		 * @param bool $redirect Should the user be redirected after module activation? Default to true.
3038
		 */
3039
		do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
3040
3041
		$jetpack = self::init();
3042
3043
		if ( ! strlen( $module ) ) {
3044
			return false;
3045
		}
3046
3047
		if ( ! self::is_module( $module ) ) {
3048
			return false;
3049
		}
3050
3051
		// If it's already active, then don't do it again
3052
		$active = self::get_active_modules();
3053
		foreach ( $active as $act ) {
3054
			if ( $act == $module ) {
3055
				return true;
3056
			}
3057
		}
3058
3059
		$module_data = self::get_module( $module );
3060
3061
		$is_development_mode = ( new Status() )->is_development_mode();
3062
		if ( ! self::is_active() ) {
3063
			if ( ! $is_development_mode && ! self::is_onboarding() ) {
3064
				return false;
3065
			}
3066
3067
			// If we're not connected but in development mode, make sure the module doesn't require a connection
3068
			if ( $is_development_mode && $module_data['requires_connection'] ) {
3069
				return false;
3070
			}
3071
		}
3072
3073
		// Check and see if the old plugin is active
3074
		if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
3075
			// Deactivate the old plugin
3076
			if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
3077
				// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
3078
				// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
3079
				self::state( 'deactivated_plugins', $module );
3080
				wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
3081
				exit;
3082
			}
3083
		}
3084
3085
		// Protect won't work with mis-configured IPs
3086
		if ( 'protect' === $module ) {
3087
			include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
3088
			if ( ! jetpack_protect_get_ip() ) {
3089
				self::state( 'message', 'protect_misconfigured_ip' );
3090
				return false;
3091
			}
3092
		}
3093
3094
		if ( ! Jetpack_Plan::supports( $module ) ) {
3095
			return false;
3096
		}
3097
3098
		// Check the file for fatal errors, a la wp-admin/plugins.php::activate
3099
		self::state( 'module', $module );
3100
		self::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
3101
3102
		self::catch_errors( true );
3103
		ob_start();
3104
		require self::get_module_path( $module );
3105
		/** This action is documented in class.jetpack.php */
3106
		do_action( 'jetpack_activate_module', $module );
3107
		$active[] = $module;
3108
		self::update_active_modules( $active );
3109
3110
		self::state( 'error', false ); // the override
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3111
		ob_end_clean();
3112
		self::catch_errors( false );
3113
3114
		if ( $redirect ) {
3115
			wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
3116
		}
3117
		if ( $exit ) {
3118
			exit;
3119
		}
3120
		return true;
3121
	}
3122
3123
	function activate_module_actions( $module ) {
3124
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
3125
	}
3126
3127
	public static function deactivate_module( $module ) {
3128
		/**
3129
		 * Fires when a module is deactivated.
3130
		 *
3131
		 * @since 1.9.0
3132
		 *
3133
		 * @param string $module Module slug.
3134
		 */
3135
		do_action( 'jetpack_pre_deactivate_module', $module );
3136
3137
		$jetpack = self::init();
0 ignored issues
show
Unused Code introduced by
$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...
3138
3139
		$active = self::get_active_modules();
3140
		$new    = array_filter( array_diff( $active, (array) $module ) );
3141
3142
		return self::update_active_modules( $new );
3143
	}
3144
3145
	public static function enable_module_configurable( $module ) {
3146
		$module = self::get_module_slug( $module );
3147
		add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
3148
	}
3149
3150
	/**
3151
	 * Composes a module configure URL. It uses Jetpack settings search as default value
3152
	 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
3153
	 *
3154
	 * @param string $module Module slug
3155
	 * @return string $url module configuration URL
3156
	 */
3157
	public static function module_configuration_url( $module ) {
3158
		$module      = self::get_module_slug( $module );
3159
		$default_url = self::admin_url() . "#/settings?term=$module";
3160
		/**
3161
		 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
3162
		 *
3163
		 * @since 6.9.0
3164
		 *
3165
		 * @param string $default_url Default url, which redirects to jetpack settings page.
3166
		 */
3167
		$url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
3168
3169
		return $url;
3170
	}
3171
3172
	/* Installation */
3173
	public static function bail_on_activation( $message, $deactivate = true ) {
3174
		?>
3175
<!doctype html>
3176
<html>
3177
<head>
3178
<meta charset="<?php bloginfo( 'charset' ); ?>">
3179
<style>
3180
* {
3181
	text-align: center;
3182
	margin: 0;
3183
	padding: 0;
3184
	font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
3185
}
3186
p {
3187
	margin-top: 1em;
3188
	font-size: 18px;
3189
}
3190
</style>
3191
<body>
3192
<p><?php echo esc_html( $message ); ?></p>
3193
</body>
3194
</html>
3195
		<?php
3196
		if ( $deactivate ) {
3197
			$plugins = get_option( 'active_plugins' );
3198
			$jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
3199
			$update  = false;
3200
			foreach ( $plugins as $i => $plugin ) {
3201
				if ( $plugin === $jetpack ) {
3202
					$plugins[ $i ] = false;
3203
					$update        = true;
3204
				}
3205
			}
3206
3207
			if ( $update ) {
3208
				update_option( 'active_plugins', array_filter( $plugins ) );
3209
			}
3210
		}
3211
		exit;
3212
	}
3213
3214
	/**
3215
	 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
3216
	 *
3217
	 * @static
3218
	 */
3219
	public static function plugin_activation( $network_wide ) {
3220
		Jetpack_Options::update_option( 'activated', 1 );
3221
3222
		if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
3223
			self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
3224
		}
3225
3226
		if ( $network_wide ) {
3227
			self::state( 'network_nag', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3228
		}
3229
3230
		// For firing one-off events (notices) immediately after activation
3231
		set_transient( 'activated_jetpack', true, .1 * MINUTE_IN_SECONDS );
3232
3233
		update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
3234
3235
		Health::on_jetpack_activated();
3236
3237
		self::plugin_initialize();
3238
	}
3239
3240
	public static function get_activation_source( $referer_url ) {
3241
3242
		if ( defined( 'WP_CLI' ) && WP_CLI ) {
3243
			return array( 'wp-cli', null );
3244
		}
3245
3246
		$referer = wp_parse_url( $referer_url );
3247
3248
		$source_type  = 'unknown';
3249
		$source_query = null;
3250
3251
		if ( ! is_array( $referer ) ) {
3252
			return array( $source_type, $source_query );
3253
		}
3254
3255
		$plugins_path         = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3256
		$plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

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...
3257
3258
		if ( isset( $referer['query'] ) ) {
3259
			parse_str( $referer['query'], $query_parts );
3260
		} else {
3261
			$query_parts = array();
3262
		}
3263
3264
		if ( $plugins_path === $referer['path'] ) {
3265
			$source_type = 'list';
3266
		} elseif ( $plugins_install_path === $referer['path'] ) {
3267
			$tab = isset( $query_parts['tab'] ) ? $query_parts['tab'] : 'featured';
3268
			switch ( $tab ) {
3269
				case 'popular':
3270
					$source_type = 'popular';
3271
					break;
3272
				case 'recommended':
3273
					$source_type = 'recommended';
3274
					break;
3275
				case 'favorites':
3276
					$source_type = 'favorites';
3277
					break;
3278
				case 'search':
3279
					$source_type  = 'search-' . ( isset( $query_parts['type'] ) ? $query_parts['type'] : 'term' );
3280
					$source_query = isset( $query_parts['s'] ) ? $query_parts['s'] : null;
3281
					break;
3282
				default:
3283
					$source_type = 'featured';
3284
			}
3285
		}
3286
3287
		return array( $source_type, $source_query );
3288
	}
3289
3290
	/**
3291
	 * Runs before bumping version numbers up to a new version
3292
	 *
3293
	 * @param string $version    Version:timestamp.
3294
	 * @param string $old_version Old Version:timestamp or false if not set yet.
3295
	 */
3296
	public static function do_version_bump( $version, $old_version ) {
3297
		if ( $old_version ) { // For existing Jetpack installations.
3298
3299
			// If a front end page is visited after the update, the 'wp' action will fire.
3300
			add_action( 'wp', 'Jetpack::set_update_modal_display' );
3301
3302
			// If an admin page is visited after the update, the 'current_screen' action will fire.
3303
			add_action( 'current_screen', 'Jetpack::set_update_modal_display' );
3304
		}
3305
	}
3306
3307
	/**
3308
	 * Sets the display_update_modal state.
3309
	 */
3310
	public static function set_update_modal_display() {
3311
		self::state( 'display_update_modal', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
3312
	}
3313
3314
	/**
3315
	 * Sets the internal version number and activation state.
3316
	 *
3317
	 * @static
3318
	 */
3319
	public static function plugin_initialize() {
3320
		if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3321
			Jetpack_Options::update_option( 'activated', 2 );
3322
		}
3323
3324 View Code Duplication
		if ( ! Jetpack_Options::get_option( 'version' ) ) {
3325
			$version = $old_version = JETPACK__VERSION . ':' . time();
3326
			/** This action is documented in class.jetpack.php */
3327
			do_action( 'updating_jetpack_version', $version, false );
3328
			Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3329
		}
3330
3331
		self::load_modules();
3332
3333
		Jetpack_Options::delete_option( 'do_activate' );
3334
		Jetpack_Options::delete_option( 'dismissed_connection_banner' );
3335
	}
3336
3337
	/**
3338
	 * Removes all connection options
3339
	 *
3340
	 * @static
3341
	 */
3342
	public static function plugin_deactivation() {
3343
		require_once ABSPATH . '/wp-admin/includes/plugin.php';
3344
		$tracking = new Tracking();
3345
		$tracking->record_user_event( 'deactivate_plugin', array() );
3346
		if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3347
			Jetpack_Network::init()->deactivate();
3348
		} else {
3349
			self::disconnect( false );
3350
			// Jetpack_Heartbeat::init()->deactivate();
3351
		}
3352
	}
3353
3354
	/**
3355
	 * Disconnects from the Jetpack servers.
3356
	 * Forgets all connection details and tells the Jetpack servers to do the same.
3357
	 *
3358
	 * @static
3359
	 */
3360
	public static function disconnect( $update_activated_state = true ) {
3361
		wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
3362
		$connection = self::connection();
3363
		$connection->clean_nonces( true );
3364
3365
		// If the site is in an IDC because sync is not allowed,
3366
		// let's make sure to not disconnect the production site.
3367
		if ( ! self::validate_sync_error_idc_option() ) {
3368
			$tracking = new Tracking();
3369
			$tracking->record_user_event( 'disconnect_site', array() );
3370
3371
			$connection->disconnect_site_wpcom();
3372
		}
3373
3374
		$connection->delete_all_connection_tokens();
3375
		Jetpack_IDC::clear_all_idc_options();
3376
3377
		if ( $update_activated_state ) {
3378
			Jetpack_Options::update_option( 'activated', 4 );
3379
		}
3380
3381
		if ( $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' ) ) {
3382
			// Check then record unique disconnection if site has never been disconnected previously
3383
			if ( - 1 == $jetpack_unique_connection['disconnected'] ) {
3384
				$jetpack_unique_connection['disconnected'] = 1;
3385
			} else {
3386
				if ( 0 == $jetpack_unique_connection['disconnected'] ) {
3387
					// track unique disconnect
3388
					$jetpack = self::init();
3389
3390
					$jetpack->stat( 'connections', 'unique-disconnect' );
3391
					$jetpack->do_stats( 'server_side' );
3392
				}
3393
				// increment number of times disconnected
3394
				$jetpack_unique_connection['disconnected'] += 1;
3395
			}
3396
3397
			Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
3398
		}
3399
3400
		// Delete all the sync related data. Since it could be taking up space.
3401
		Sender::get_instance()->uninstall();
3402
3403
		// Disable the Heartbeat cron
3404
		Jetpack_Heartbeat::init()->deactivate();
3405
	}
3406
3407
	/**
3408
	 * Unlinks the current user from the linked WordPress.com user.
3409
	 *
3410
	 * @deprecated since 7.7
3411
	 * @see Automattic\Jetpack\Connection\Manager::disconnect_user()
3412
	 *
3413
	 * @param Integer $user_id the user identifier.
0 ignored issues
show
Documentation introduced by
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...
3414
	 * @return Boolean Whether the disconnection of the user was successful.
3415
	 */
3416
	public static function unlink_user( $user_id = null ) {
3417
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::disconnect_user' );
3418
		return Connection_Manager::disconnect_user( $user_id );
3419
	}
3420
3421
	/**
3422
	 * Attempts Jetpack registration.  If it fail, a state flag is set: @see ::admin_page_load()
3423
	 */
3424
	public static function try_registration() {
3425
		$terms_of_service = new Terms_Of_Service();
3426
		// The user has agreed to the TOS at some point by now.
3427
		$terms_of_service->agree();
3428
3429
		// Let's get some testing in beta versions and such.
3430
		if ( self::is_development_version() && defined( 'PHP_URL_HOST' ) ) {
3431
			// Before attempting to connect, let's make sure that the domains are viable.
3432
			$domains_to_check = array_unique(
3433
				array(
3434
					'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3435
					'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
3436
				)
3437
			);
3438
			foreach ( $domains_to_check as $domain ) {
3439
				$result = self::connection()->is_usable_domain( $domain );
0 ignored issues
show
Documentation introduced by
$domain is of type array<string,string>|false, but the function expects a string.

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...
3440
				if ( is_wp_error( $result ) ) {
3441
					return $result;
3442
				}
3443
			}
3444
		}
3445
3446
		$result = self::register();
3447
3448
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3449
		if ( ! $result || is_wp_error( $result ) ) {
3450
			return $result;
3451
		} else {
3452
			return true;
3453
		}
3454
	}
3455
3456
	/**
3457
	 * Tracking an internal event log. Try not to put too much chaff in here.
3458
	 *
3459
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3460
	 */
3461
	public static function log( $code, $data = null ) {
3462
		// only grab the latest 200 entries
3463
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3464
3465
		// Append our event to the log
3466
		$log_entry = array(
3467
			'time'    => time(),
3468
			'user_id' => get_current_user_id(),
3469
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3470
			'code'    => $code,
3471
		);
3472
		// Don't bother storing it unless we've got some.
3473
		if ( ! is_null( $data ) ) {
3474
			$log_entry['data'] = $data;
3475
		}
3476
		$log[] = $log_entry;
3477
3478
		// Try add_option first, to make sure it's not autoloaded.
3479
		// @todo: Add an add_option method to Jetpack_Options
3480
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3481
			Jetpack_Options::update_option( 'log', $log );
3482
		}
3483
3484
		/**
3485
		 * Fires when Jetpack logs an internal event.
3486
		 *
3487
		 * @since 3.0.0
3488
		 *
3489
		 * @param array $log_entry {
3490
		 *  Array of details about the log entry.
3491
		 *
3492
		 *  @param string time Time of the event.
3493
		 *  @param int user_id ID of the user who trigerred the event.
3494
		 *  @param int blog_id Jetpack Blog ID.
3495
		 *  @param string code Unique name for the event.
3496
		 *  @param string data Data about the event.
3497
		 * }
3498
		 */
3499
		do_action( 'jetpack_log_entry', $log_entry );
3500
	}
3501
3502
	/**
3503
	 * Get the internal event log.
3504
	 *
3505
	 * @param $event (string) - only return the specific log events
3506
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3507
	 *
3508
	 * @return array of log events || WP_Error for invalid params
3509
	 */
3510
	public static function get_log( $event = false, $num = false ) {
3511
		if ( $event && ! is_string( $event ) ) {
3512
			return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
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...
3513
		}
3514
3515
		if ( $num && ! is_numeric( $num ) ) {
3516
			return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
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...
3517
		}
3518
3519
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3520
3521
		// If nothing set - act as it did before, otherwise let's start customizing the output
3522
		if ( ! $num && ! $event ) {
3523
			return $entire_log;
3524
		} else {
3525
			$entire_log = array_reverse( $entire_log );
3526
		}
3527
3528
		$custom_log_output = array();
3529
3530
		if ( $event ) {
3531
			foreach ( $entire_log as $log_event ) {
3532
				if ( $event == $log_event['code'] ) {
3533
					$custom_log_output[] = $log_event;
3534
				}
3535
			}
3536
		} else {
3537
			$custom_log_output = $entire_log;
3538
		}
3539
3540
		if ( $num ) {
3541
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3542
		}
3543
3544
		return $custom_log_output;
3545
	}
3546
3547
	/**
3548
	 * Log modification of important settings.
3549
	 */
3550
	public static function log_settings_change( $option, $old_value, $value ) {
3551
		switch ( $option ) {
3552
			case 'jetpack_sync_non_public_post_stati':
3553
				self::log( $option, $value );
3554
				break;
3555
		}
3556
	}
3557
3558
	/**
3559
	 * Return stat data for WPCOM sync
3560
	 */
3561
	public static function get_stat_data( $encode = true, $extended = true ) {
3562
		$data = Jetpack_Heartbeat::generate_stats_array();
3563
3564
		if ( $extended ) {
3565
			$additional_data = self::get_additional_stat_data();
3566
			$data            = array_merge( $data, $additional_data );
3567
		}
3568
3569
		if ( $encode ) {
3570
			return json_encode( $data );
3571
		}
3572
3573
		return $data;
3574
	}
3575
3576
	/**
3577
	 * Get additional stat data to sync to WPCOM
3578
	 */
3579
	public static function get_additional_stat_data( $prefix = '' ) {
3580
		$return[ "{$prefix}themes" ]        = self::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...
3581
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3582
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3583
		$return[ "{$prefix}site-count" ]    = 0;
3584
3585
		if ( function_exists( 'get_blog_count' ) ) {
3586
			$return[ "{$prefix}site-count" ] = get_blog_count();
3587
		}
3588
		return $return;
3589
	}
3590
3591
	private static function get_site_user_count() {
3592
		global $wpdb;
3593
3594
		if ( function_exists( 'wp_is_large_network' ) ) {
3595
			if ( wp_is_large_network( 'users' ) ) {
3596
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3597
			}
3598
		}
3599
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3600
			// It wasn't there, so regenerate the data and save the transient
3601
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3602
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3603
		}
3604
		return $user_count;
3605
	}
3606
3607
	/* Admin Pages */
3608
3609
	function admin_init() {
3610
		// If the plugin is not connected, display a connect message.
3611
		if (
3612
			// the plugin was auto-activated and needs its candy
3613
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3614
		||
3615
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3616
			! Jetpack_Options::get_option( 'activated' )
3617
		) {
3618
			self::plugin_initialize();
3619
		}
3620
3621
		$is_development_mode = ( new Status() )->is_development_mode();
3622
		if ( ! self::is_active() && ! $is_development_mode ) {
3623
			Jetpack_Connection_Banner::init();
3624
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3625
			// Upgrade: 1.1 -> 1.1.1
3626
			// Check and see if host can verify the Jetpack servers' SSL certificate
3627
			$args       = array();
3628
			$connection = self::connection();
3629
			Client::_wp_remote_request(
3630
				Connection_Utils::fix_url_for_bad_hosts( $connection->api_url( 'test' ) ),
3631
				$args,
3632
				true
3633
			);
3634
		}
3635
3636
		Jetpack_Wizard_Banner::init();
3637
3638
		if ( current_user_can( 'manage_options' ) && 'AUTO' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
3639
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3640
		}
3641
3642
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3643
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3644
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3645
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3646
3647
		if ( self::is_active() || $is_development_mode ) {
3648
			// Artificially throw errors in certain whitelisted cases during plugin activation
3649
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3650
		}
3651
3652
		// Add custom column in wp-admin/users.php to show whether user is linked.
3653
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3654
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3655
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3656
	}
3657
3658
	function admin_body_class( $admin_body_class = '' ) {
3659
		$classes = explode( ' ', trim( $admin_body_class ) );
3660
3661
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3662
3663
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3664
		return " $admin_body_class ";
3665
	}
3666
3667
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3668
		return $admin_body_class . ' jetpack-pagestyles ';
3669
	}
3670
3671
	/**
3672
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3673
	 * This function artificially throws errors for such cases (whitelisted).
3674
	 *
3675
	 * @param string $plugin The activated plugin.
3676
	 */
3677
	function throw_error_on_activate_plugin( $plugin ) {
3678
		$active_modules = self::get_active_modules();
3679
3680
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3681
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3682
			$throw = false;
3683
3684
			// Try and make sure it really was the stats plugin
3685
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3686
				if ( 'stats.php' == basename( $plugin ) ) {
3687
					$throw = true;
3688
				}
3689
			} else {
3690
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3691
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3692
					$throw = true;
3693
				}
3694
			}
3695
3696
			if ( $throw ) {
3697
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3698
			}
3699
		}
3700
	}
3701
3702
	function intercept_plugin_error_scrape_init() {
3703
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3704
	}
3705
3706
	function intercept_plugin_error_scrape( $action, $result ) {
3707
		if ( ! $result ) {
3708
			return;
3709
		}
3710
3711
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3712
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3713
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3714
			}
3715
		}
3716
	}
3717
3718
	/**
3719
	 * Register the remote file upload request handlers, if needed.
3720
	 *
3721
	 * @access public
3722
	 */
3723
	public function add_remote_request_handlers() {
3724
		// Remote file uploads are allowed only via AJAX requests.
3725
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3726
			return;
3727
		}
3728
3729
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3730
		$remote_request_actions = array(
3731
			'jetpack_upload_file',
3732
			'jetpack_update_file',
3733
		);
3734
3735
		// phpcs:ignore WordPress.Security.NonceVerification
3736
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3737
			return;
3738
		}
3739
3740
		// Require Jetpack authentication for the remote file upload AJAX requests.
3741
		if ( ! $this->connection_manager ) {
3742
			$this->connection_manager = new Connection_Manager();
3743
		}
3744
3745
		$this->connection_manager->require_jetpack_authentication();
3746
3747
		// Register the remote file upload AJAX handlers.
3748
		foreach ( $remote_request_actions as $action ) {
3749
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3750
		}
3751
	}
3752
3753
	/**
3754
	 * Handler for Jetpack remote file uploads.
3755
	 *
3756
	 * @access public
3757
	 */
3758
	public function remote_request_handlers() {
3759
		$action = current_filter();
0 ignored issues
show
Unused Code introduced by
$action is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
3760
3761
		switch ( current_filter() ) {
3762
			case 'wp_ajax_nopriv_jetpack_upload_file':
3763
				$response = $this->upload_handler();
3764
				break;
3765
3766
			case 'wp_ajax_nopriv_jetpack_update_file':
3767
				$response = $this->upload_handler( true );
3768
				break;
3769
			default:
3770
				$response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
0 ignored issues
show
Unused Code introduced by
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...
3771
				break;
3772
		}
3773
3774
		if ( ! $response ) {
3775
			$response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
0 ignored issues
show
Unused Code introduced by
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...
3776
		}
3777
3778
		if ( is_wp_error( $response ) ) {
3779
			$status_code       = $response->get_error_data();
0 ignored issues
show
Bug introduced by
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...
3780
			$error             = $response->get_error_code();
0 ignored issues
show
Bug introduced by
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...
3781
			$error_description = $response->get_error_message();
0 ignored issues
show
Bug introduced by
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...
3782
3783
			if ( ! is_int( $status_code ) ) {
3784
				$status_code = 400;
3785
			}
3786
3787
			status_header( $status_code );
3788
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3789
		}
3790
3791
		status_header( 200 );
3792
		if ( true === $response ) {
3793
			exit;
3794
		}
3795
3796
		die( json_encode( (object) $response ) );
3797
	}
3798
3799
	/**
3800
	 * Uploads a file gotten from the global $_FILES.
3801
	 * If `$update_media_item` is true and `post_id` is defined
3802
	 * the attachment file of the media item (gotten through of the post_id)
3803
	 * will be updated instead of add a new one.
3804
	 *
3805
	 * @param  boolean $update_media_item - update media attachment
3806
	 * @return array - An array describing the uploadind files process
3807
	 */
3808
	function upload_handler( $update_media_item = false ) {
3809
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3810
			return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
0 ignored issues
show
Unused Code introduced by
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...
3811
		}
3812
3813
		$user = wp_authenticate( '', '' );
3814
		if ( ! $user || is_wp_error( $user ) ) {
3815
			return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
0 ignored issues
show
Unused Code introduced by
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...
3816
		}
3817
3818
		wp_set_current_user( $user->ID );
3819
3820
		if ( ! current_user_can( 'upload_files' ) ) {
3821
			return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
0 ignored issues
show
Unused Code introduced by
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...
3822
		}
3823
3824
		if ( empty( $_FILES ) ) {
3825
			return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
0 ignored issues
show
Unused Code introduced by
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...
3826
		}
3827
3828
		foreach ( array_keys( $_FILES ) as $files_key ) {
3829
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3830
				return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
0 ignored issues
show
Unused Code introduced by
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...
3831
			}
3832
		}
3833
3834
		$media_keys = array_keys( $_FILES['media'] );
3835
3836
		$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...
3837
		if ( ! $token || is_wp_error( $token ) ) {
3838
			return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
0 ignored issues
show
Unused Code introduced by
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...
3839
		}
3840
3841
		$uploaded_files = array();
3842
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3843
		unset( $GLOBALS['post'] );
3844
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3845
			$file = array();
3846
			foreach ( $media_keys as $media_key ) {
3847
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3848
			}
3849
3850
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3851
3852
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3853
			if ( $hmac_provided !== $hmac_file ) {
3854
				$uploaded_files[ $index ] = (object) array(
3855
					'error'             => 'invalid_hmac',
3856
					'error_description' => 'The corresponding HMAC for this file does not match',
3857
				);
3858
				continue;
3859
			}
3860
3861
			$_FILES['.jetpack.upload.'] = $file;
3862
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3863
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3864
				$post_id = 0;
3865
			}
3866
3867
			if ( $update_media_item ) {
3868
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3869
					return new Jetpack_Error( 'invalid_input', 'Media ID must be defined.', 400 );
0 ignored issues
show
Unused Code introduced by
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...
3870
				}
3871
3872
				$media_array = $_FILES['media'];
3873
3874
				$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...
3875
				$file_array['type']     = $media_array['type'][0];
3876
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3877
				$file_array['error']    = $media_array['error'][0];
3878
				$file_array['size']     = $media_array['size'][0];
3879
3880
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3881
3882
				if ( is_wp_error( $edited_media_item ) ) {
3883
					return $edited_media_item;
3884
				}
3885
3886
				$response = (object) array(
3887
					'id'   => (string) $post_id,
3888
					'file' => (string) $edited_media_item->post_title,
3889
					'url'  => (string) wp_get_attachment_url( $post_id ),
3890
					'type' => (string) $edited_media_item->post_mime_type,
3891
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3892
				);
3893
3894
				return (array) array( $response );
3895
			}
3896
3897
			$attachment_id = media_handle_upload(
3898
				'.jetpack.upload.',
3899
				$post_id,
3900
				array(),
3901
				array(
3902
					'action' => 'jetpack_upload_file',
3903
				)
3904
			);
3905
3906
			if ( ! $attachment_id ) {
3907
				$uploaded_files[ $index ] = (object) array(
3908
					'error'             => 'unknown',
3909
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3910
				);
3911
			} elseif ( is_wp_error( $attachment_id ) ) {
3912
				$uploaded_files[ $index ] = (object) array(
3913
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3914
					'error_description' => $attachment_id->get_error_message(),
3915
				);
3916
			} else {
3917
				$attachment               = get_post( $attachment_id );
3918
				$uploaded_files[ $index ] = (object) array(
3919
					'id'   => (string) $attachment_id,
3920
					'file' => $attachment->post_title,
3921
					'url'  => wp_get_attachment_url( $attachment_id ),
3922
					'type' => $attachment->post_mime_type,
3923
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3924
				);
3925
				// Zip files uploads are not supported unless they are done for installation purposed
3926
				// lets delete them in case something goes wrong in this whole process
3927
				if ( 'application/zip' === $attachment->post_mime_type ) {
3928
					// Schedule a cleanup for 2 hours from now in case of failed install.
3929
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3930
				}
3931
			}
3932
		}
3933
		if ( ! is_null( $global_post ) ) {
3934
			$GLOBALS['post'] = $global_post;
3935
		}
3936
3937
		return $uploaded_files;
3938
	}
3939
3940
	/**
3941
	 * Add help to the Jetpack page
3942
	 *
3943
	 * @since Jetpack (1.2.3)
3944
	 * @return false if not the Jetpack page
3945
	 */
3946
	function admin_help() {
3947
		$current_screen = get_current_screen();
3948
3949
		// Overview
3950
		$current_screen->add_help_tab(
3951
			array(
3952
				'id'      => 'home',
3953
				'title'   => __( 'Home', 'jetpack' ),
3954
				'content' =>
3955
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3956
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3957
					'<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>',
3958
			)
3959
		);
3960
3961
		// Screen Content
3962
		if ( current_user_can( 'manage_options' ) ) {
3963
			$current_screen->add_help_tab(
3964
				array(
3965
					'id'      => 'settings',
3966
					'title'   => __( 'Settings', 'jetpack' ),
3967
					'content' =>
3968
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3969
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3970
						'<ol>' .
3971
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3972
							'<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>' .
3973
						'</ol>' .
3974
						'<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>',
3975
				)
3976
			);
3977
		}
3978
3979
		// Help Sidebar
3980
		$support_url = Redirect::get_url( 'jetpack-support' );
3981
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3982
		$current_screen->set_help_sidebar(
3983
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3984
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3985
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3986
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3987
		);
3988
	}
3989
3990
	function admin_menu_css() {
3991
		wp_enqueue_style( 'jetpack-icons' );
3992
	}
3993
3994
	function admin_menu_order() {
3995
		return true;
3996
	}
3997
3998 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
3999
		$jp_menu_order = array();
4000
4001
		foreach ( $menu_order as $index => $item ) {
4002
			if ( $item != 'jetpack' ) {
4003
				$jp_menu_order[] = $item;
4004
			}
4005
4006
			if ( $index == 0 ) {
4007
				$jp_menu_order[] = 'jetpack';
4008
			}
4009
		}
4010
4011
		return $jp_menu_order;
4012
	}
4013
4014
	function admin_banner_styles() {
4015
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4016
4017 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4018
			wp_register_style(
4019
				'jetpack-dops-style',
4020
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4021
				array(),
4022
				JETPACK__VERSION
4023
			);
4024
		}
4025
4026
		wp_enqueue_style(
4027
			'jetpack',
4028
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4029
			array( 'jetpack-dops-style' ),
4030
			JETPACK__VERSION . '-20121016'
4031
		);
4032
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4033
		wp_style_add_data( 'jetpack', 'suffix', $min );
4034
	}
4035
4036
	function plugin_action_links( $actions ) {
4037
4038
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
4039
4040
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_development_mode() ) ) {
4041
			return array_merge(
4042
				$jetpack_home,
4043
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4044
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4045
				$actions
4046
			);
4047
		}
4048
4049
		return array_merge( $jetpack_home, $actions );
4050
	}
4051
4052
	/**
4053
	 * Adds the deactivation warning modal if there are other active plugins using the connection
4054
	 *
4055
	 * @param string $hook The current admin page.
4056
	 *
4057
	 * @return void
4058
	 */
4059
	public function deactivate_dialog( $hook ) {
4060
		if (
4061
			'plugins.php' === $hook
4062
			&& self::is_active()
4063
		) {
4064
4065
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4066
4067
			if ( count( $active_plugins_using_connection ) > 1 ) {
4068
4069
				add_thickbox();
4070
4071
				wp_register_script(
4072
					'jp-tracks',
4073
					'//stats.wp.com/w.js',
4074
					array(),
4075
					gmdate( 'YW' ),
4076
					true
4077
				);
4078
4079
				wp_register_script(
4080
					'jp-tracks-functions',
4081
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4082
					array( 'jp-tracks' ),
4083
					JETPACK__VERSION,
4084
					false
4085
				);
4086
4087
				wp_enqueue_script(
4088
					'jetpack-deactivate-dialog-js',
4089
					Assets::get_file_url_for_environment(
4090
						'_inc/build/jetpack-deactivate-dialog.min.js',
4091
						'_inc/jetpack-deactivate-dialog.js'
4092
					),
4093
					array( 'jquery', 'jp-tracks-functions' ),
4094
					JETPACK__VERSION,
4095
					true
4096
				);
4097
4098
				wp_localize_script(
4099
					'jetpack-deactivate-dialog-js',
4100
					'deactivate_dialog',
4101
					array(
4102
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4103
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4104
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4105
					)
4106
				);
4107
4108
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4109
4110
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4111
			}
4112
		}
4113
	}
4114
4115
	/**
4116
	 * Outputs the content of the deactivation modal
4117
	 *
4118
	 * @return void
4119
	 */
4120
	public function deactivate_dialog_content() {
4121
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4122
		unset( $active_plugins_using_connection['jetpack'] );
4123
		$this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
0 ignored issues
show
Bug introduced by
It seems like $active_plugins_using_connection defined by \Automattic\Jetpack\Conn...ugin_Storage::get_all() on line 4121 can also be of type object<WP_Error>; however, Jetpack::load_view() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
4124
	}
4125
4126
	/**
4127
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4128
	 *
4129
	 * @param string $login_url The wp-login URL.
4130
	 * @param string $redirect  URL to redirect users after logging in.
4131
	 * @since Jetpack 8.4
4132
	 * @return string
4133
	 */
4134
	public function login_url( $login_url, $redirect ) {
4135
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
4136
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4137
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4138
		}
4139
		return $login_url;
4140
	}
4141
4142
	/**
4143
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4144
	 *
4145
	 * @since Jetpack 8.4
4146
	 */
4147
	public function login_init() {
4148
		// phpcs:ignore WordPress.Security.NonceVerification
4149
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4150
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4151
			wp_safe_redirect(
4152
				add_query_arg(
4153
					array(
4154
						'forceInstall' => 1,
4155
						'url'          => rawurlencode( get_site_url() ),
4156
					),
4157
					// @todo provide way to go to specific calypso env.
4158
					self::get_calypso_host() . 'jetpack/connect'
4159
				)
4160
			);
4161
			exit;
4162
		}
4163
	}
4164
4165
	/*
4166
	 * Registration flow:
4167
	 * 1 - ::admin_page_load() action=register
4168
	 * 2 - ::try_registration()
4169
	 * 3 - ::register()
4170
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4171
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4172
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4173
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4174
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4175
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4176
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4177
	 *       jetpack_id, jetpack_secret, jetpack_public
4178
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4179
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4180
	 * 5 - user logs in with WP.com account
4181
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4182
	 *		- Manager::authorize()
4183
	 *		- Manager::get_token()
4184
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4185
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4186
	 *			- which responds with access_token, token_type, scope
4187
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4188
	 *		- Jetpack::activate_default_modules()
4189
	 *     		- Deactivates deprecated plugins
4190
	 *     		- Activates all default modules
4191
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4192
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4193
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4194
	 *     Done!
4195
	 */
4196
4197
	/**
4198
	 * Handles the page load events for the Jetpack admin page
4199
	 */
4200
	function admin_page_load() {
4201
		$error = false;
4202
4203
		// Make sure we have the right body class to hook stylings for subpages off of.
4204
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4205
4206
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4207
			// Should only be used in intermediate redirects to preserve state across redirects
4208
			self::restate();
4209
		}
4210
4211
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4212
			// @todo: Add validation against a known whitelist
4213
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4214
			// User clicked in the iframe to link their accounts
4215
			if ( ! self::is_user_connected() ) {
4216
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4217
4218
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4219
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4220
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4221
4222
				if ( isset( $_GET['notes_iframe'] ) ) {
4223
					$connect_url .= '&notes_iframe';
4224
				}
4225
				wp_redirect( $connect_url );
4226
				exit;
4227
			} else {
4228
				if ( ! isset( $_GET['calypso_env'] ) ) {
4229
					self::state( 'message', 'already_authorized' );
4230
					wp_safe_redirect( self::admin_url() );
4231
					exit;
4232
				} else {
4233
					$connect_url  = $this->build_connect_url( true, false, $from );
4234
					$connect_url .= '&already_authorized=true';
4235
					wp_redirect( $connect_url );
4236
					exit;
4237
				}
4238
			}
4239
		}
4240
4241
		if ( isset( $_GET['action'] ) ) {
4242
			switch ( $_GET['action'] ) {
4243
				case 'authorize':
4244
					if ( self::is_active() && self::is_user_connected() ) {
4245
						self::state( 'message', 'already_authorized' );
4246
						wp_safe_redirect( self::admin_url() );
4247
						exit;
4248
					}
4249
					self::log( 'authorize' );
4250
					$client_server = new Jetpack_Client_Server();
4251
					$client_server->client_authorize();
4252
					exit;
4253
				case 'register':
4254
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4255
						$error = 'cheatin';
4256
						break;
4257
					}
4258
					check_admin_referer( 'jetpack-register' );
4259
					self::log( 'register' );
4260
					self::maybe_set_version_option();
4261
					$registered = self::try_registration();
4262 View Code Duplication
					if ( is_wp_error( $registered ) ) {
4263
						$error = $registered->get_error_code();
0 ignored issues
show
Bug introduced by
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...
4264
						self::state( 'error', $error );
4265
						self::state( 'error', $registered->get_error_message() );
0 ignored issues
show
Bug introduced by
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...
4266
4267
						/**
4268
						 * Jetpack registration Error.
4269
						 *
4270
						 * @since 7.5.0
4271
						 *
4272
						 * @param string|int $error The error code.
4273
						 * @param \WP_Error $registered The error object.
4274
						 */
4275
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4276
						break;
4277
					}
4278
4279
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4280
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4281
4282
					/**
4283
					 * Jetpack registration Success.
4284
					 *
4285
					 * @since 7.5.0
4286
					 *
4287
					 * @param string $from 'from' GET parameter;
4288
					 */
4289
					do_action( 'jetpack_connection_register_success', $from );
4290
4291
					$url = $this->build_connect_url( true, $redirect, $from );
4292
4293
					if ( ! empty( $_GET['onboarding'] ) ) {
4294
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4295
					}
4296
4297
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4298
						$url = add_query_arg( 'auth_approved', 'true', $url );
4299
					}
4300
4301
					wp_redirect( $url );
4302
					exit;
4303
				case 'activate':
4304
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4305
						$error = 'cheatin';
4306
						break;
4307
					}
4308
4309
					$module = stripslashes( $_GET['module'] );
4310
					check_admin_referer( "jetpack_activate-$module" );
4311
					self::log( 'activate', $module );
4312
					if ( ! self::activate_module( $module ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression self::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...
4313
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4314
					}
4315
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4316
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4317
					exit;
4318
				case 'activate_default_modules':
4319
					check_admin_referer( 'activate_default_modules' );
4320
					self::log( 'activate_default_modules' );
4321
					self::restate();
4322
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4323
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4324
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4325
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4326
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4327
					exit;
4328
				case 'disconnect':
4329
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4330
						$error = 'cheatin';
4331
						break;
4332
					}
4333
4334
					check_admin_referer( 'jetpack-disconnect' );
4335
					self::log( 'disconnect' );
4336
					self::disconnect();
4337
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4338
					exit;
4339
				case 'reconnect':
4340
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4341
						$error = 'cheatin';
4342
						break;
4343
					}
4344
4345
					check_admin_referer( 'jetpack-reconnect' );
4346
					self::log( 'reconnect' );
4347
					$this->disconnect();
4348
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4349
					exit;
4350 View Code Duplication
				case 'deactivate':
4351
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4352
						$error = 'cheatin';
4353
						break;
4354
					}
4355
4356
					$modules = stripslashes( $_GET['module'] );
4357
					check_admin_referer( "jetpack_deactivate-$modules" );
4358
					foreach ( explode( ',', $modules ) as $module ) {
4359
						self::log( 'deactivate', $module );
4360
						self::deactivate_module( $module );
4361
						self::state( 'message', 'module_deactivated' );
4362
					}
4363
					self::state( 'module', $modules );
4364
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4365
					exit;
4366
				case 'unlink':
4367
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4368
					check_admin_referer( 'jetpack-unlink' );
4369
					self::log( 'unlink' );
4370
					Connection_Manager::disconnect_user();
4371
					self::state( 'message', 'unlinked' );
4372
					if ( 'sub-unlink' == $redirect ) {
4373
						wp_safe_redirect( admin_url() );
4374
					} else {
4375
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4376
					}
4377
					exit;
4378
				case 'onboard':
4379
					if ( ! current_user_can( 'manage_options' ) ) {
4380
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4381
					} else {
4382
						self::create_onboarding_token();
4383
						$url = $this->build_connect_url( true );
4384
4385
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4386
							$url = add_query_arg( 'onboarding', $token, $url );
4387
						}
4388
4389
						$calypso_env = $this->get_calypso_env();
4390
						if ( ! empty( $calypso_env ) ) {
4391
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4392
						}
4393
4394
						wp_redirect( $url );
4395
						exit;
4396
					}
4397
					exit;
4398
				default:
4399
					/**
4400
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4401
					 *
4402
					 * @since 2.6.0
4403
					 *
4404
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4405
					 */
4406
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4407
			}
4408
		}
4409
4410
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4411
			self::activate_new_modules( true );
4412
		}
4413
4414
		$message_code = self::state( 'message' );
4415
		if ( self::state( 'optin-manage' ) ) {
4416
			$activated_manage = $message_code;
4417
			$message_code     = 'jetpack-manage';
4418
		}
4419
4420
		switch ( $message_code ) {
4421
			case 'jetpack-manage':
4422
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4423
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4424
				$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' ), $sites_url ) . '</strong>';
4425
				if ( $activated_manage ) {
0 ignored issues
show
Bug introduced by
The variable $activated_manage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
4426
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4427
				}
4428
				break;
4429
4430
		}
4431
4432
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4433
4434
		if ( ! empty( $deactivated_plugins ) ) {
4435
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4436
			$deactivated_titles  = array();
4437
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4438
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4439
					continue;
4440
				}
4441
4442
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4443
			}
4444
4445
			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...
4446
				if ( $this->message ) {
4447
					$this->message .= "<br /><br />\n";
4448
				}
4449
4450
				$this->message .= wp_sprintf(
4451
					_n(
4452
						'Jetpack contains the most recent version of the old %l plugin.',
4453
						'Jetpack contains the most recent versions of the old %l plugins.',
4454
						count( $deactivated_titles ),
4455
						'jetpack'
4456
					),
4457
					$deactivated_titles
4458
				);
4459
4460
				$this->message .= "<br />\n";
4461
4462
				$this->message .= _n(
4463
					'The old version has been deactivated and can be removed from your site.',
4464
					'The old versions have been deactivated and can be removed from your site.',
4465
					count( $deactivated_titles ),
4466
					'jetpack'
4467
				);
4468
			}
4469
		}
4470
4471
		$this->privacy_checks = self::state( 'privacy_checks' );
4472
4473
		if ( $this->message || $this->error || $this->privacy_checks ) {
4474
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4475
		}
4476
4477
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4478
	}
4479
4480
	function admin_notices() {
4481
4482
		if ( $this->error ) {
4483
			?>
4484
<div id="message" class="jetpack-message jetpack-err">
4485
	<div class="squeezer">
4486
		<h2>
4487
			<?php
4488
			echo wp_kses(
4489
				$this->error,
4490
				array(
4491
					'a'      => array( 'href' => array() ),
4492
					'small'  => true,
4493
					'code'   => true,
4494
					'strong' => true,
4495
					'br'     => true,
4496
					'b'      => true,
4497
				)
4498
			);
4499
			?>
4500
			</h2>
4501
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4502
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4503
<?php	endif; ?>
4504
	</div>
4505
</div>
4506
			<?php
4507
		}
4508
4509
		if ( $this->message ) {
4510
			?>
4511
<div id="message" class="jetpack-message">
4512
	<div class="squeezer">
4513
		<h2>
4514
			<?php
4515
			echo wp_kses(
4516
				$this->message,
4517
				array(
4518
					'strong' => array(),
4519
					'a'      => array( 'href' => true ),
4520
					'br'     => true,
4521
				)
4522
			);
4523
			?>
4524
			</h2>
4525
	</div>
4526
</div>
4527
			<?php
4528
		}
4529
4530
		if ( $this->privacy_checks ) :
4531
			$module_names = $module_slugs = array();
4532
4533
			$privacy_checks = explode( ',', $this->privacy_checks );
4534
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4535
			foreach ( $privacy_checks as $module_slug ) {
4536
				$module = self::get_module( $module_slug );
4537
				if ( ! $module ) {
4538
					continue;
4539
				}
4540
4541
				$module_slugs[] = $module_slug;
4542
				$module_names[] = "<strong>{$module['name']}</strong>";
4543
			}
4544
4545
			$module_slugs = join( ',', $module_slugs );
4546
			?>
4547
<div id="message" class="jetpack-message jetpack-err">
4548
	<div class="squeezer">
4549
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4550
		<p>
4551
			<?php
4552
			echo wp_kses(
4553
				wptexturize(
4554
					wp_sprintf(
4555
						_nx(
4556
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4557
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4558
							count( $privacy_checks ),
4559
							'%l = list of Jetpack module/feature names',
4560
							'jetpack'
4561
						),
4562
						$module_names
4563
					)
4564
				),
4565
				array( 'strong' => true )
4566
			);
4567
4568
			echo "\n<br />\n";
4569
4570
			echo wp_kses(
4571
				sprintf(
4572
					_nx(
4573
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4574
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4575
						count( $privacy_checks ),
4576
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4577
						'jetpack'
4578
					),
4579
					wp_nonce_url(
4580
						self::admin_url(
4581
							array(
4582
								'page'   => 'jetpack',
4583
								'action' => 'deactivate',
4584
								'module' => urlencode( $module_slugs ),
4585
							)
4586
						),
4587
						"jetpack_deactivate-$module_slugs"
4588
					),
4589
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4590
				),
4591
				array(
4592
					'a' => array(
4593
						'href'  => true,
4594
						'title' => true,
4595
					),
4596
				)
4597
			);
4598
			?>
4599
		</p>
4600
	</div>
4601
</div>
4602
			<?php
4603
endif;
4604
	}
4605
4606
	/**
4607
	 * We can't always respond to a signed XML-RPC request with a
4608
	 * helpful error message. In some circumstances, doing so could
4609
	 * leak information.
4610
	 *
4611
	 * Instead, track that the error occurred via a Jetpack_Option,
4612
	 * and send that data back in the heartbeat.
4613
	 * All this does is increment a number, but it's enough to find
4614
	 * trends.
4615
	 *
4616
	 * @param WP_Error $xmlrpc_error The error produced during
4617
	 *                               signature validation.
4618
	 */
4619
	function track_xmlrpc_error( $xmlrpc_error ) {
4620
		$code = is_wp_error( $xmlrpc_error )
4621
			? $xmlrpc_error->get_error_code()
0 ignored issues
show
Bug introduced by
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...
4622
			: 'should-not-happen';
4623
4624
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4625
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4626
			// No need to update the option if we already have
4627
			// this code stored.
4628
			return;
4629
		}
4630
		$xmlrpc_errors[ $code ] = true;
4631
4632
		Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
4633
	}
4634
4635
	/**
4636
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4637
	 */
4638
	function stat( $group, $detail ) {
4639
		if ( ! isset( $this->stats[ $group ] ) ) {
4640
			$this->stats[ $group ] = array();
4641
		}
4642
		$this->stats[ $group ][] = $detail;
4643
	}
4644
4645
	/**
4646
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4647
	 */
4648
	function do_stats( $method = '' ) {
4649
		if ( is_array( $this->stats ) && count( $this->stats ) ) {
4650
			foreach ( $this->stats as $group => $stats ) {
4651
				if ( is_array( $stats ) && count( $stats ) ) {
4652
					$args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
4653
					if ( 'server_side' === $method ) {
4654
						self::do_server_side_stat( $args );
4655
					} else {
4656
						echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
4657
					}
4658
				}
4659
				unset( $this->stats[ $group ] );
4660
			}
4661
		}
4662
	}
4663
4664
	/**
4665
	 * Runs stats code for a one-off, server-side.
4666
	 *
4667
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4668
	 *
4669
	 * @return bool If it worked.
4670
	 */
4671
	static function do_server_side_stat( $args ) {
4672
		$response = wp_remote_get( esc_url_raw( self::build_stats_url( $args ) ) );
4673
		if ( is_wp_error( $response ) ) {
4674
			return false;
4675
		}
4676
4677
		if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4678
			return false;
4679
		}
4680
4681
		return true;
4682
	}
4683
4684
	/**
4685
	 * Builds the stats url.
4686
	 *
4687
	 * @param $args array|string The arguments to append to the URL.
4688
	 *
4689
	 * @return string The URL to be pinged.
4690
	 */
4691
	static function build_stats_url( $args ) {
4692
		$defaults = array(
4693
			'v'    => 'wpcom2',
4694
			'rand' => md5( mt_rand( 0, 999 ) . time() ),
4695
		);
4696
		$args     = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,string,{"v"...ring","rand":"string"}>, but the function expects a string.

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...
4697
		/**
4698
		 * Filter the URL used as the Stats tracking pixel.
4699
		 *
4700
		 * @since 2.3.2
4701
		 *
4702
		 * @param string $url Base URL used as the Stats tracking pixel.
4703
		 */
4704
		$base_url = apply_filters(
4705
			'jetpack_stats_base_url',
4706
			'https://pixel.wp.com/g.gif'
4707
		);
4708
		$url      = add_query_arg( $args, $base_url );
4709
		return $url;
4710
	}
4711
4712
	/**
4713
	 * Get the role of the current user.
4714
	 *
4715
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4716
	 *
4717
	 * @access public
4718
	 * @static
4719
	 *
4720
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4721
	 */
4722
	public static function translate_current_user_to_role() {
4723
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4724
4725
		$roles = new Roles();
4726
		return $roles->translate_current_user_to_role();
4727
	}
4728
4729
	/**
4730
	 * Get the role of a particular user.
4731
	 *
4732
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4733
	 *
4734
	 * @access public
4735
	 * @static
4736
	 *
4737
	 * @param \WP_User $user User object.
4738
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4739
	 */
4740
	public static function translate_user_to_role( $user ) {
4741
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4742
4743
		$roles = new Roles();
4744
		return $roles->translate_user_to_role( $user );
4745
	}
4746
4747
	/**
4748
	 * Get the minimum capability for a role.
4749
	 *
4750
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4751
	 *
4752
	 * @access public
4753
	 * @static
4754
	 *
4755
	 * @param string $role Role name.
4756
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4757
	 */
4758
	public static function translate_role_to_cap( $role ) {
4759
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4760
4761
		$roles = new Roles();
4762
		return $roles->translate_role_to_cap( $role );
4763
	}
4764
4765
	/**
4766
	 * Sign a user role with the master access token.
4767
	 * If not specified, will default to the current user.
4768
	 *
4769
	 * @deprecated since 7.7
4770
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4771
	 *
4772
	 * @access public
4773
	 * @static
4774
	 *
4775
	 * @param string $role    User role.
4776
	 * @param int    $user_id ID of the user.
0 ignored issues
show
Documentation introduced by
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...
4777
	 * @return string Signed user role.
4778
	 */
4779
	public static function sign_role( $role, $user_id = null ) {
4780
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4781
		return self::connection()->sign_role( $role, $user_id );
4782
	}
4783
4784
	/**
4785
	 * Builds a URL to the Jetpack connection auth page
4786
	 *
4787
	 * @since 3.9.5
4788
	 *
4789
	 * @param bool        $raw If true, URL will not be escaped.
4790
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4791
	 *                              If string, will be a custom redirect.
4792
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4793
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4794
	 *
4795
	 * @return string Connect URL
4796
	 */
4797
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4798
		$site_id    = Jetpack_Options::get_option( 'id' );
4799
		$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...
4800
4801
		if ( $register || ! $blog_token || ! $site_id ) {
4802
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4803
4804
			if ( ! empty( $redirect ) ) {
4805
				$url = add_query_arg(
4806
					'redirect',
4807
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4808
					$url
4809
				);
4810
			}
4811
4812
			if ( is_network_admin() ) {
4813
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4814
			}
4815
4816
			$calypso_env = self::get_calypso_env();
4817
4818
			if ( ! empty( $calypso_env ) ) {
4819
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4820
			}
4821
		} else {
4822
4823
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4824
			// because otherwise this logic can get us in to a loop.
4825
			$last_connect_url_check = intval( Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' ) );
4826
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4827
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4828
4829
				$response = Client::wpcom_json_api_request_as_blog(
4830
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4831
					'1.1'
4832
				);
4833
4834
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4835
4836
					// Generating a register URL instead to refresh the existing token
4837
					return $this->build_connect_url( $raw, $redirect, $from, true );
4838
				}
4839
			}
4840
4841
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4797 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...
4842
		}
4843
4844
		if ( $from ) {
4845
			$url = add_query_arg( 'from', $from, $url );
4846
		}
4847
4848
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4849
		/**
4850
		 * Filter the URL used when connecting a user to a WordPress.com account.
4851
		 *
4852
		 * @since 8.1.0
4853
		 *
4854
		 * @param string $url Connection URL.
4855
		 * @param bool   $raw If true, URL will not be escaped.
4856
		 */
4857
		return apply_filters( 'jetpack_build_connection_url', $url, $raw );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $raw.

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...
4858
	}
4859
4860
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4861
4862
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4863
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4864
		add_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4865
4866
		if ( $iframe ) {
4867
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4868
		}
4869
4870
		$c8n = self::connection();
4871
		$url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
0 ignored issues
show
Documentation introduced by
$redirect 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...
4872
4873
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4874
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4875
		remove_filter( 'jetpack_connect_processing_url', array( __CLASS__, 'filter_connect_processing_url' ) );
4876
4877
		if ( $iframe ) {
4878
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4879
		}
4880
4881
		return $url;
4882
	}
4883
4884
	/**
4885
	 * Filters the connection URL parameter array.
4886
	 *
4887
	 * @param array $args default URL parameters used by the package.
4888
	 * @return array the modified URL arguments array.
4889
	 */
4890
	public static function filter_connect_request_body( $args ) {
4891
		if (
4892
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4893
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4894
		) {
4895
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4896
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4897
				? $gp_locale->slug
4898
				: '';
4899
		}
4900
4901
		$tracking        = new Tracking();
4902
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4903
4904
		$args = array_merge(
4905
			$args,
4906
			array(
4907
				'_ui' => $tracks_identity['_ui'],
4908
				'_ut' => $tracks_identity['_ut'],
4909
			)
4910
		);
4911
4912
		$calypso_env = self::get_calypso_env();
4913
4914
		if ( ! empty( $calypso_env ) ) {
4915
			$args['calypso_env'] = $calypso_env;
4916
		}
4917
4918
		return $args;
4919
	}
4920
4921
	/**
4922
	 * Filters the URL that will process the connection data. It can be different from the URL
4923
	 * that we send the user to after everything is done.
4924
	 *
4925
	 * @param String $processing_url the default redirect URL used by the package.
4926
	 * @return String the modified URL.
4927
	 */
4928
	public static function filter_connect_processing_url( $processing_url ) {
4929
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4930
		return $processing_url;
4931
	}
4932
4933
	/**
4934
	 * Filters the redirection URL that is used for connect requests. The redirect
4935
	 * URL should return the user back to the Jetpack console.
4936
	 *
4937
	 * @param String $redirect the default redirect URL used by the package.
4938
	 * @return String the modified URL.
4939
	 */
4940
	public static function filter_connect_redirect_url( $redirect ) {
4941
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4942
		$redirect           = $redirect
4943
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4944
			: $jetpack_admin_page;
4945
4946
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4947
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4948
		}
4949
4950
		return $redirect;
4951
	}
4952
4953
	/**
4954
	 * This action fires at the beginning of the Manager::authorize method.
4955
	 */
4956
	public static function authorize_starting() {
4957
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4958
		// Checking if site has been active/connected previously before recording unique connection.
4959
		if ( ! $jetpack_unique_connection ) {
4960
			// jetpack_unique_connection option has never been set.
4961
			$jetpack_unique_connection = array(
4962
				'connected'    => 0,
4963
				'disconnected' => 0,
4964
				'version'      => '3.6.1',
4965
			);
4966
4967
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4968
4969
			// Track unique connection.
4970
			$jetpack = self::init();
4971
4972
			$jetpack->stat( 'connections', 'unique-connection' );
4973
			$jetpack->do_stats( 'server_side' );
4974
		}
4975
4976
		// Increment number of times connected.
4977
		$jetpack_unique_connection['connected'] += 1;
4978
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4979
	}
4980
4981
	/**
4982
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4983
	 * linked.
4984
	 */
4985
	public static function authorize_ending_linked() {
4986
		// Don't activate anything since we are just connecting a user.
4987
		self::state( 'message', 'linked' );
4988
	}
4989
4990
	/**
4991
	 * This action fires at the end of the Manager::authorize method when the master user is
4992
	 * authorized.
4993
	 *
4994
	 * @param array $data The request data.
4995
	 */
4996
	public static function authorize_ending_authorized( $data ) {
4997
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4998
		self::invalidate_onboarding_token();
4999
5000
		// If redirect_uri is SSO, ensure SSO module is enabled.
5001
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_QUERY.

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...
5002
5003
		/** This filter is documented in class.jetpack-cli.php */
5004
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5005
5006
		$activate_sso = (
5007
			isset( $redirect_options['action'] ) &&
5008
			'jetpack-sso' === $redirect_options['action'] &&
5009
			$jetpack_start_enable_sso
5010
		);
5011
5012
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
5013
5014
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5015
	}
5016
5017
	/**
5018
	 * Get our assumed site creation date.
5019
	 * Calculated based on the earlier date of either:
5020
	 * - Earliest admin user registration date.
5021
	 * - Earliest date of post of any post type.
5022
	 *
5023
	 * @since 7.2.0
5024
	 * @deprecated since 7.8.0
5025
	 *
5026
	 * @return string Assumed site creation date and time.
5027
	 */
5028
	public static function get_assumed_site_creation_date() {
5029
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5030
		return self::connection()->get_assumed_site_creation_date();
5031
	}
5032
5033 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
5034
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5035
5036
		if ( $activation_source_name ) {
5037
			$args['_as'] = urlencode( $activation_source_name );
5038
		}
5039
5040
		if ( $activation_source_keyword ) {
5041
			$args['_ak'] = urlencode( $activation_source_keyword );
5042
		}
5043
	}
5044
5045
	function build_reconnect_url( $raw = false ) {
5046
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5047
		return $raw ? $url : esc_url( $url );
5048
	}
5049
5050
	public static function admin_url( $args = null ) {
5051
		$args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
0 ignored issues
show
Documentation introduced by
array('page' => 'jetpack') is of type array<string,string,{"page":"string"}>, but the function expects a string.

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...
5052
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
5053
		return $url;
5054
	}
5055
5056
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5057
		$actionurl = str_replace( '&amp;', '&', $actionurl );
5058
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5059
	}
5060
5061
	function dismiss_jetpack_notice() {
5062
5063
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5064
			return;
5065
		}
5066
5067
		switch ( $_GET['jetpack-notice'] ) {
5068
			case 'dismiss':
5069
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5070
5071
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5072
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5073
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5074
				}
5075
				break;
5076
		}
5077
	}
5078
5079
	public static function sort_modules( $a, $b ) {
5080
		if ( $a['sort'] == $b['sort'] ) {
5081
			return 0;
5082
		}
5083
5084
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5085
	}
5086
5087
	function ajax_recheck_ssl() {
5088
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5089
		$result = self::permit_ssl( true );
5090
		wp_send_json(
5091
			array(
5092
				'enabled' => $result,
5093
				'message' => get_transient( 'jetpack_https_test_message' ),
5094
			)
5095
		);
5096
	}
5097
5098
	/* Client API */
5099
5100
	/**
5101
	 * Returns the requested Jetpack API URL
5102
	 *
5103
	 * @deprecated since 7.7
5104
	 * @return string
5105
	 */
5106
	public static function api_url( $relative_url ) {
5107
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5108
		$connection = self::connection();
5109
		return $connection->api_url( $relative_url );
5110
	}
5111
5112
	/**
5113
	 * @deprecated 8.0 Use Automattic\Jetpack\Connection\Utils::fix_url_for_bad_hosts() instead.
5114
	 *
5115
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
5116
	 */
5117
	public static function fix_url_for_bad_hosts( $url ) {
5118
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Utils::fix_url_for_bad_hosts' );
5119
		return Connection_Utils::fix_url_for_bad_hosts( $url );
5120
	}
5121
5122
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5123
		// Default to a blog token.
5124
		$token_type = 'blog';
5125
5126
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5127
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5128
			if ( ! empty( $_GET['onboarding'] ) ) {
5129
				$jpo = $_GET;
5130
			} else {
5131
				$jpo = json_decode( $request_data, true );
5132
			}
5133
5134
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5135
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5136
5137
			if (
5138
				isset( $jpo_user )
5139
				&& isset( $jpo_token )
5140
				&& is_email( $jpo_user )
5141
				&& ctype_alnum( $jpo_token )
5142
				&& isset( $_GET['rest_route'] )
5143
				&& self::validate_onboarding_token_action(
5144
					$jpo_token,
5145
					$_GET['rest_route']
5146
				)
5147
			) {
5148
				$jp_user = get_user_by( 'email', $jpo_user );
5149
				if ( is_a( $jp_user, 'WP_User' ) ) {
5150
					wp_set_current_user( $jp_user->ID );
5151
					$user_can = is_multisite()
5152
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5153
						: current_user_can( 'manage_options' );
5154
					if ( $user_can ) {
5155
						$token_type              = 'user';
5156
						$token->external_user_id = $jp_user->ID;
5157
					}
5158
				}
5159
			}
5160
5161
			$token_data['type']    = $token_type;
5162
			$token_data['user_id'] = $token->external_user_id;
5163
		}
5164
5165
		return $token_data;
5166
	}
5167
5168
	/**
5169
	 * Create a random secret for validating onboarding payload
5170
	 *
5171
	 * @return string Secret token
5172
	 */
5173
	public static function create_onboarding_token() {
5174
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5175
			$token = wp_generate_password( 32, false );
5176
			Jetpack_Options::update_option( 'onboarding', $token );
5177
		}
5178
5179
		return $token;
5180
	}
5181
5182
	/**
5183
	 * Remove the onboarding token
5184
	 *
5185
	 * @return bool True on success, false on failure
5186
	 */
5187
	public static function invalidate_onboarding_token() {
5188
		return Jetpack_Options::delete_option( 'onboarding' );
5189
	}
5190
5191
	/**
5192
	 * Validate an onboarding token for a specific action
5193
	 *
5194
	 * @return boolean True if token/action pair is accepted, false if not
5195
	 */
5196
	public static function validate_onboarding_token_action( $token, $action ) {
5197
		// Compare tokens, bail if tokens do not match
5198
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5199
			return false;
5200
		}
5201
5202
		// List of valid actions we can take
5203
		$valid_actions = array(
5204
			'/jetpack/v4/settings',
5205
		);
5206
5207
		// Whitelist the action
5208
		if ( ! in_array( $action, $valid_actions ) ) {
5209
			return false;
5210
		}
5211
5212
		return true;
5213
	}
5214
5215
	/**
5216
	 * Checks to see if the URL is using SSL to connect with Jetpack
5217
	 *
5218
	 * @since 2.3.3
5219
	 * @return boolean
5220
	 */
5221
	public static function permit_ssl( $force_recheck = false ) {
5222
		// Do some fancy tests to see if ssl is being supported
5223
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5224
			$message = '';
5225
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5226
				$ssl = 0;
5227
			} else {
5228
				switch ( JETPACK_CLIENT__HTTPS ) {
5229
					case 'NEVER':
5230
						$ssl     = 0;
5231
						$message = __( 'JETPACK_CLIENT__HTTPS is set to NEVER', 'jetpack' );
5232
						break;
5233
					case 'ALWAYS':
5234
					case 'AUTO':
5235
					default:
5236
						$ssl = 1;
5237
						break;
5238
				}
5239
5240
				// If it's not 'NEVER', test to see
5241
				if ( $ssl ) {
5242
					if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5243
						$ssl     = 0;
5244
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5245
					} else {
5246
						$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5247
						if ( is_wp_error( $response ) ) {
5248
							$ssl     = 0;
5249
							$message = __( 'WordPress reports no SSL support', 'jetpack' );
5250
						} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5251
							$ssl     = 0;
5252
							$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5253
						}
5254
					}
5255
				}
5256
			}
5257
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5258
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5259
		}
5260
5261
		return (bool) $ssl;
5262
	}
5263
5264
	/*
5265
	 * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'AUTO' but SSL isn't working.
5266
	 */
5267
	public function alert_auto_ssl_fail() {
5268
		if ( ! current_user_can( 'manage_options' ) ) {
5269
			return;
5270
		}
5271
5272
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5273
		?>
5274
5275
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5276
			<div class="jp-banner__content">
5277
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5278
				<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>
5279
				<p>
5280
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5281
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5282
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5283
				</p>
5284
				<p>
5285
					<?php
5286
					printf(
5287
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5288
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5289
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5290
					);
5291
					?>
5292
				</p>
5293
			</div>
5294
		</div>
5295
		<style>
5296
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5297
		</style>
5298
		<script type="text/javascript">
5299
			jQuery( document ).ready( function( $ ) {
5300
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5301
					var $this = $( this );
5302
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5303
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5304
					e.preventDefault();
5305
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5306
					$.post( ajaxurl, data )
5307
					  .done( function( response ) {
5308
						  if ( response.enabled ) {
5309
							  $( '#jetpack-ssl-warning' ).hide();
5310
						  } else {
5311
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5312
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5313
						  }
5314
					  }.bind( $this ) );
5315
				} );
5316
			} );
5317
		</script>
5318
5319
		<?php
5320
	}
5321
5322
	/**
5323
	 * Returns the Jetpack XML-RPC API
5324
	 *
5325
	 * @deprecated 8.0 Use Connection_Manager instead.
5326
	 * @return string
5327
	 */
5328
	public static function xmlrpc_api_url() {
5329
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5330
		return self::connection()->xmlrpc_api_url();
5331
	}
5332
5333
	/**
5334
	 * Returns the connection manager object.
5335
	 *
5336
	 * @return Automattic\Jetpack\Connection\Manager
5337
	 */
5338
	public static function connection() {
5339
		$jetpack = static::init();
5340
5341
		// If the connection manager hasn't been instantiated, do that now.
5342
		if ( ! $jetpack->connection_manager ) {
5343
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5344
		}
5345
5346
		return $jetpack->connection_manager;
5347
	}
5348
5349
	/**
5350
	 * Creates two secret tokens and the end of life timestamp for them.
5351
	 *
5352
	 * Note these tokens are unique per call, NOT static per site for connecting.
5353
	 *
5354
	 * @since 2.6
5355
	 * @param String  $action  The action name.
5356
	 * @param Integer $user_id The user identifier.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $user_id not be false|integer?

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...
5357
	 * @param Integer $exp     Expiration time in seconds.
5358
	 * @return array
5359
	 */
5360
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5361
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5362
	}
5363
5364
	public static function get_secrets( $action, $user_id ) {
5365
		$secrets = self::connection()->get_secrets( $action, $user_id );
5366
5367
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5368
			return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
0 ignored issues
show
Unused Code introduced by
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...
5369
		}
5370
5371
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5372
			return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
0 ignored issues
show
Unused Code introduced by
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...
5373
		}
5374
5375
		return $secrets;
5376
	}
5377
5378
	/**
5379
	 * @deprecated 7.5 Use Connection_Manager instead.
5380
	 *
5381
	 * @param $action
5382
	 * @param $user_id
5383
	 */
5384
	public static function delete_secrets( $action, $user_id ) {
5385
		return self::connection()->delete_secrets( $action, $user_id );
5386
	}
5387
5388
	/**
5389
	 * Builds the timeout limit for queries talking with the wpcom servers.
5390
	 *
5391
	 * Based on local php max_execution_time in php.ini
5392
	 *
5393
	 * @since 2.6
5394
	 * @return int
5395
	 * @deprecated
5396
	 **/
5397
	public function get_remote_query_timeout_limit() {
5398
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5399
		return self::get_max_execution_time();
5400
	}
5401
5402
	/**
5403
	 * Builds the timeout limit for queries talking with the wpcom servers.
5404
	 *
5405
	 * Based on local php max_execution_time in php.ini
5406
	 *
5407
	 * @since 5.4
5408
	 * @return int
5409
	 **/
5410
	public static function get_max_execution_time() {
5411
		$timeout = (int) ini_get( 'max_execution_time' );
5412
5413
		// Ensure exec time set in php.ini
5414
		if ( ! $timeout ) {
5415
			$timeout = 30;
5416
		}
5417
		return $timeout;
5418
	}
5419
5420
	/**
5421
	 * Sets a minimum request timeout, and returns the current timeout
5422
	 *
5423
	 * @since 5.4
5424
	 **/
5425 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5426
		$timeout = self::get_max_execution_time();
5427
		if ( $timeout < $min_timeout ) {
5428
			$timeout = $min_timeout;
5429
			set_time_limit( $timeout );
5430
		}
5431
		return $timeout;
5432
	}
5433
5434
	/**
5435
	 * Takes the response from the Jetpack register new site endpoint and
5436
	 * verifies it worked properly.
5437
	 *
5438
	 * @since 2.6
5439
	 * @deprecated since 7.7.0
5440
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5441
	 **/
5442
	public function validate_remote_register_response() {
5443
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5444
	}
5445
5446
	/**
5447
	 * @return bool|WP_Error
5448
	 */
5449
	public static function register() {
5450
		$tracking = new Tracking();
5451
		$tracking->record_user_event( 'jpc_register_begin' );
5452
5453
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5454
5455
		$connection   = self::connection();
5456
		$registration = $connection->register();
5457
5458
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5459
5460
		if ( ! $registration || is_wp_error( $registration ) ) {
5461
			return $registration;
5462
		}
5463
5464
		return true;
5465
	}
5466
5467
	/**
5468
	 * Filters the registration request body to include tracking properties.
5469
	 *
5470
	 * @param array $properties
5471
	 * @return array amended properties.
5472
	 */
5473 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5474
		$tracking        = new Tracking();
5475
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5476
5477
		return array_merge(
5478
			$properties,
5479
			array(
5480
				'_ui' => $tracks_identity['_ui'],
5481
				'_ut' => $tracks_identity['_ut'],
5482
			)
5483
		);
5484
	}
5485
5486
	/**
5487
	 * Filters the token request body to include tracking properties.
5488
	 *
5489
	 * @param array $properties
5490
	 * @return array amended properties.
5491
	 */
5492 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5493
		$tracking        = new Tracking();
5494
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5495
5496
		return array_merge(
5497
			$properties,
5498
			array(
5499
				'_ui' => $tracks_identity['_ui'],
5500
				'_ut' => $tracks_identity['_ut'],
5501
			)
5502
		);
5503
	}
5504
5505
	/**
5506
	 * If the db version is showing something other that what we've got now, bump it to current.
5507
	 *
5508
	 * @return bool: True if the option was incorrect and updated, false if nothing happened.
0 ignored issues
show
Documentation introduced by
The doc-type bool: could not be parsed: Unknown type name "bool:" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
5509
	 */
5510
	public static function maybe_set_version_option() {
5511
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5512
		if ( JETPACK__VERSION != $version ) {
5513
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5514
5515
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5516
				/** This action is documented in class.jetpack.php */
5517
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5518
			}
5519
5520
			return true;
5521
		}
5522
		return false;
5523
	}
5524
5525
	/* Client Server API */
5526
5527
	/**
5528
	 * Loads the Jetpack XML-RPC client.
5529
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5530
	 *
5531
	 * @deprecated since 7.7.0
5532
	 */
5533
	public static function load_xml_rpc_client() {
5534
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5535
	}
5536
5537
	/**
5538
	 * Resets the saved authentication state in between testing requests.
5539
	 */
5540
	public function reset_saved_auth_state() {
5541
		$this->rest_authentication_status = null;
5542
5543
		if ( ! $this->connection_manager ) {
5544
			$this->connection_manager = new Connection_Manager();
5545
		}
5546
5547
		$this->connection_manager->reset_saved_auth_state();
5548
	}
5549
5550
	/**
5551
	 * Verifies the signature of the current request.
5552
	 *
5553
	 * @deprecated since 7.7.0
5554
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5555
	 *
5556
	 * @return false|array
5557
	 */
5558
	public function verify_xml_rpc_signature() {
5559
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5560
		return self::connection()->verify_xml_rpc_signature();
5561
	}
5562
5563
	/**
5564
	 * Verifies the signature of the current request.
5565
	 *
5566
	 * This function has side effects and should not be used. Instead,
5567
	 * use the memoized version `->verify_xml_rpc_signature()`.
5568
	 *
5569
	 * @deprecated since 7.7.0
5570
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5571
	 * @internal
5572
	 */
5573
	private function internal_verify_xml_rpc_signature() {
5574
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5575
	}
5576
5577
	/**
5578
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5579
	 *
5580
	 * @deprecated since 7.7.0
5581
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5582
	 *
5583
	 * @param \WP_User|mixed $user     User object if authenticated.
5584
	 * @param string         $username Username.
5585
	 * @param string         $password Password string.
5586
	 * @return \WP_User|mixed Authenticated user or error.
5587
	 */
5588 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5589
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5590
5591
		if ( ! $this->connection_manager ) {
5592
			$this->connection_manager = new Connection_Manager();
5593
		}
5594
5595
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5596
	}
5597
5598
	// Authenticates requests from Jetpack server to WP REST API endpoints.
5599
	// Uses the existing XMLRPC request signing implementation.
5600
	function wp_rest_authenticate( $user ) {
5601
		if ( ! empty( $user ) ) {
5602
			// Another authentication method is in effect.
5603
			return $user;
5604
		}
5605
5606
		if ( ! isset( $_GET['_for'] ) || $_GET['_for'] !== 'jetpack' ) {
5607
			// Nothing to do for this authentication method.
5608
			return null;
5609
		}
5610
5611
		if ( ! isset( $_GET['token'] ) && ! isset( $_GET['signature'] ) ) {
5612
			// Nothing to do for this authentication method.
5613
			return null;
5614
		}
5615
5616
		// Ensure that we always have the request body available.  At this
5617
		// point, the WP REST API code to determine the request body has not
5618
		// run yet.  That code may try to read from 'php://input' later, but
5619
		// this can only be done once per request in PHP versions prior to 5.6.
5620
		// So we will go ahead and perform this read now if needed, and save
5621
		// the request body where both the Jetpack signature verification code
5622
		// and the WP REST API code can see it.
5623
		if ( ! isset( $GLOBALS['HTTP_RAW_POST_DATA'] ) ) {
5624
			$GLOBALS['HTTP_RAW_POST_DATA'] = file_get_contents( 'php://input' );
5625
		}
5626
		$this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
5627
5628
		// Only support specific request parameters that have been tested and
5629
		// are known to work with signature verification.  A different method
5630
		// can be passed to the WP REST API via the '?_method=' parameter if
5631
		// needed.
5632
		if ( $_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST' ) {
5633
			$this->rest_authentication_status = new WP_Error(
5634
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
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...
5635
				__( 'This request method is not supported.', 'jetpack' ),
5636
				array( 'status' => 400 )
5637
			);
5638
			return null;
5639
		}
5640
		if ( $_SERVER['REQUEST_METHOD'] !== 'POST' && ! empty( $this->HTTP_RAW_POST_DATA ) ) {
5641
			$this->rest_authentication_status = new WP_Error(
5642
				'rest_invalid_request',
0 ignored issues
show
Unused Code introduced by
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...
5643
				__( 'This request method does not support body parameters.', 'jetpack' ),
5644
				array( 'status' => 400 )
5645
			);
5646
			return null;
5647
		}
5648
5649
		if ( ! $this->connection_manager ) {
5650
			$this->connection_manager = new Connection_Manager();
5651
		}
5652
5653
		$verified = $this->connection_manager->verify_xml_rpc_signature();
5654
5655
		if (
5656
			$verified &&
5657
			isset( $verified['type'] ) &&
5658
			'user' === $verified['type'] &&
5659
			! empty( $verified['user_id'] )
5660
		) {
5661
			// Authentication successful.
5662
			$this->rest_authentication_status = true;
5663
			return $verified['user_id'];
5664
		}
5665
5666
		// Something else went wrong.  Probably a signature error.
5667
		$this->rest_authentication_status = new WP_Error(
5668
			'rest_invalid_signature',
0 ignored issues
show
Unused Code introduced by
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...
5669
			__( 'The request is not signed correctly.', 'jetpack' ),
5670
			array( 'status' => 400 )
5671
		);
5672
		return null;
5673
	}
5674
5675
	/**
5676
	 * Report authentication status to the WP REST API.
5677
	 *
5678
	 * @param  WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
5679
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5680
	 */
5681
	public function wp_rest_authentication_errors( $value ) {
5682
		if ( $value !== null ) {
5683
			return $value;
5684
		}
5685
		return $this->rest_authentication_status;
5686
	}
5687
5688
	/**
5689
	 * Add our nonce to this request.
5690
	 *
5691
	 * @deprecated since 7.7.0
5692
	 * @see Automattic\Jetpack\Connection\Manager::add_nonce()
5693
	 *
5694
	 * @param int    $timestamp Timestamp of the request.
5695
	 * @param string $nonce     Nonce string.
5696
	 */
5697 View Code Duplication
	public function add_nonce( $timestamp, $nonce ) {
5698
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::add_nonce' );
5699
5700
		if ( ! $this->connection_manager ) {
5701
			$this->connection_manager = new Connection_Manager();
5702
		}
5703
5704
		return $this->connection_manager->add_nonce( $timestamp, $nonce );
5705
	}
5706
5707
	/**
5708
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5709
	 * Capture it here so we can verify the signature later.
5710
	 *
5711
	 * @deprecated since 7.7.0
5712
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5713
	 *
5714
	 * @param array $methods XMLRPC methods.
5715
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5716
	 */
5717 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5718
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5719
5720
		if ( ! $this->connection_manager ) {
5721
			$this->connection_manager = new Connection_Manager();
5722
		}
5723
5724
		return $this->connection_manager->xmlrpc_methods( $methods );
5725
	}
5726
5727
	/**
5728
	 * Register additional public XMLRPC methods.
5729
	 *
5730
	 * @deprecated since 7.7.0
5731
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5732
	 *
5733
	 * @param array $methods Public XMLRPC methods.
5734
	 * @return array Public XMLRPC methods, with the getOptions one.
5735
	 */
5736 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5737
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5738
5739
		if ( ! $this->connection_manager ) {
5740
			$this->connection_manager = new Connection_Manager();
5741
		}
5742
5743
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5744
	}
5745
5746
	/**
5747
	 * Handles a getOptions XMLRPC method call.
5748
	 *
5749
	 * @deprecated since 7.7.0
5750
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5751
	 *
5752
	 * @param array $args method call arguments.
5753
	 * @return array an amended XMLRPC server options array.
5754
	 */
5755 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5756
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5757
5758
		if ( ! $this->connection_manager ) {
5759
			$this->connection_manager = new Connection_Manager();
5760
		}
5761
5762
		return $this->connection_manager->jetpack_getOptions( $args );
0 ignored issues
show
Bug introduced by
The method jetpack_getOptions() does not exist on Automattic\Jetpack\Connection\Manager. Did you maybe mean jetpack_get_options()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
5763
	}
5764
5765
	/**
5766
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5767
	 *
5768
	 * @deprecated since 7.7.0
5769
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5770
	 *
5771
	 * @param array $options Standard Core options.
5772
	 * @return array Amended options.
5773
	 */
5774 View Code Duplication
	public function xmlrpc_options( $options ) {
5775
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5776
5777
		if ( ! $this->connection_manager ) {
5778
			$this->connection_manager = new Connection_Manager();
5779
		}
5780
5781
		return $this->connection_manager->xmlrpc_options( $options );
5782
	}
5783
5784
	/**
5785
	 * Cleans nonces that were saved when calling ::add_nonce.
5786
	 *
5787
	 * @deprecated since 7.7.0
5788
	 * @see Automattic\Jetpack\Connection\Manager::clean_nonces()
5789
	 *
5790
	 * @param bool $all whether to clean even non-expired nonces.
5791
	 */
5792
	public static function clean_nonces( $all = false ) {
5793
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::clean_nonces' );
5794
		return self::connection()->clean_nonces( $all );
5795
	}
5796
5797
	/**
5798
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5799
	 * SET: state( $key, $value );
5800
	 * GET: $value = state( $key );
5801
	 *
5802
	 * @param string $key
0 ignored issues
show
Documentation introduced by
Should the type for parameter $key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5803
	 * @param string $value
0 ignored issues
show
Documentation introduced by
Should the type for parameter $value not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
5804
	 * @param bool   $restate private
5805
	 */
5806
	public static function state( $key = null, $value = null, $restate = false ) {
5807
		static $state = array();
5808
		static $path, $domain;
5809
		if ( ! isset( $path ) ) {
5810
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5811
			$admin_url = self::admin_url();
5812
			$bits      = wp_parse_url( $admin_url );
5813
5814
			if ( is_array( $bits ) ) {
5815
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5816
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5817
			} else {
5818
				$path = $domain = null;
5819
			}
5820
		}
5821
5822
		// Extract state from cookies and delete cookies
5823
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5824
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5825
			unset( $_COOKIE['jetpackState'] );
5826
			foreach ( $yum as $k => $v ) {
5827
				if ( strlen( $v ) ) {
5828
					$state[ $k ] = $v;
5829
				}
5830
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5831
			}
5832
		}
5833
5834
		if ( $restate ) {
5835
			foreach ( $state as $k => $v ) {
5836
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5837
			}
5838
			return;
5839
		}
5840
5841
		// Get a state variable.
5842
		if ( isset( $key ) && ! isset( $value ) ) {
5843
			if ( array_key_exists( $key, $state ) ) {
5844
				return $state[ $key ];
5845
			}
5846
			return null;
5847
		}
5848
5849
		// Set a state variable.
5850
		if ( isset( $key ) && isset( $value ) ) {
5851
			if ( is_array( $value ) && isset( $value[0] ) ) {
5852
				$value = $value[0];
5853
			}
5854
			$state[ $key ] = $value;
5855
			if ( ! headers_sent() ) {
5856
				if ( self::should_set_cookie( $key ) ) {
5857
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5858
				}
5859
			}
5860
		}
5861
	}
5862
5863
	public static function restate() {
5864
		self::state( null, null, true );
5865
	}
5866
5867
	/**
5868
	 * Determines whether the jetpackState[$key] value should be added to the
5869
	 * cookie.
5870
	 *
5871
	 * @param string $key The state key.
5872
	 *
5873
	 * @return boolean Whether the value should be added to the cookie.
5874
	 */
5875
	public static function should_set_cookie( $key ) {
5876
		global $current_screen;
5877
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5878
5879
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5880
			return false;
5881
		}
5882
5883
		return true;
5884
	}
5885
5886
	public static function check_privacy( $file ) {
5887
		static $is_site_publicly_accessible = null;
5888
5889
		if ( is_null( $is_site_publicly_accessible ) ) {
5890
			$is_site_publicly_accessible = false;
5891
5892
			$rpc = new Jetpack_IXR_Client();
5893
5894
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5895
			if ( $success ) {
5896
				$response = $rpc->getResponse();
5897
				if ( $response ) {
5898
					$is_site_publicly_accessible = true;
5899
				}
5900
			}
5901
5902
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5903
		}
5904
5905
		if ( $is_site_publicly_accessible ) {
5906
			return;
5907
		}
5908
5909
		$module_slug = self::get_module_slug( $file );
5910
5911
		$privacy_checks = self::state( 'privacy_checks' );
5912
		if ( ! $privacy_checks ) {
5913
			$privacy_checks = $module_slug;
5914
		} else {
5915
			$privacy_checks .= ",$module_slug";
5916
		}
5917
5918
		self::state( 'privacy_checks', $privacy_checks );
5919
	}
5920
5921
	/**
5922
	 * Helper method for multicall XMLRPC.
5923
	 *
5924
	 * @param ...$args Args for the async_call.
5925
	 */
5926
	public static function xmlrpc_async_call( ...$args ) {
5927
		global $blog_id;
5928
		static $clients = array();
5929
5930
		$client_blog_id = is_multisite() ? $blog_id : 0;
5931
5932
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5933
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5934
			if ( function_exists( 'ignore_user_abort' ) ) {
5935
				ignore_user_abort( true );
5936
			}
5937
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5938
		}
5939
5940
		if ( ! empty( $args[0] ) ) {
5941
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5942
		} elseif ( is_multisite() ) {
5943
			foreach ( $clients as $client_blog_id => $client ) {
5944
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5945
					continue;
5946
				}
5947
5948
				$switch_success = switch_to_blog( $client_blog_id, true );
5949
				if ( ! $switch_success ) {
5950
					continue;
5951
				}
5952
5953
				flush();
5954
				$client->query();
5955
5956
				restore_current_blog();
5957
			}
5958
		} else {
5959
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5960
				flush();
5961
				$clients[0]->query();
5962
			}
5963
		}
5964
	}
5965
5966
	public static function staticize_subdomain( $url ) {
5967
5968
		// Extract hostname from URL
5969
		$host = wp_parse_url( $url, PHP_URL_HOST );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_HOST.

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...
5970
5971
		// Explode hostname on '.'
5972
		$exploded_host = explode( '.', $host );
5973
5974
		// Retrieve the name and TLD
5975
		if ( count( $exploded_host ) > 1 ) {
5976
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5977
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5978
			// Rebuild domain excluding subdomains
5979
			$domain = $name . '.' . $tld;
5980
		} else {
5981
			$domain = $host;
5982
		}
5983
		// Array of Automattic domains
5984
		$domain_whitelist = array( 'wordpress.com', 'wp.com' );
5985
5986
		// Return $url if not an Automattic domain
5987
		if ( ! in_array( $domain, $domain_whitelist ) ) {
5988
			return $url;
5989
		}
5990
5991
		if ( is_ssl() ) {
5992
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5993
		}
5994
5995
		srand( crc32( basename( $url ) ) );
5996
		$static_counter = rand( 0, 2 );
5997
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5998
5999
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
6000
	}
6001
6002
	/* JSON API Authorization */
6003
6004
	/**
6005
	 * Handles the login action for Authorizing the JSON API
6006
	 */
6007
	function login_form_json_api_authorization() {
6008
		$this->verify_json_api_authorization_request();
6009
6010
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
6011
6012
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
6013
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
6014
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
6015
	}
6016
6017
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
6018
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
6019
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6020
			return $url;
6021
		}
6022
6023
		$parsed_url = wp_parse_url( $url );
6024
		$url        = strtok( $url, '?' );
6025
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
6026
		if ( ! empty( $parsed_url['query'] ) ) {
6027
			$url .= "&{$parsed_url['query']}";
6028
		}
6029
6030
		return $url;
6031
	}
6032
6033
	// Make sure the POSTed request is handled by the same action
6034
	function preserve_action_in_login_form_for_json_api_authorization() {
6035
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6036
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6037
	}
6038
6039
	// If someone logs in to approve API access, store the Access Code in usermeta
6040
	function store_json_api_authorization_token( $user_login, $user ) {
6041
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6042
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6043
		$token = wp_generate_password( 32, false );
6044
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6045
	}
6046
6047
	// Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
6048
	function allow_wpcom_public_api_domain( $domains ) {
6049
		$domains[] = 'public-api.wordpress.com';
6050
		return $domains;
6051
	}
6052
6053
	static function is_redirect_encoded( $redirect_url ) {
6054
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6055
	}
6056
6057
	// Add all wordpress.com environments to the safe redirect whitelist
6058
	function allow_wpcom_environments( $domains ) {
6059
		$domains[] = 'wordpress.com';
6060
		$domains[] = 'wpcalypso.wordpress.com';
6061
		$domains[] = 'horizon.wordpress.com';
6062
		$domains[] = 'calypso.localhost';
6063
		return $domains;
6064
	}
6065
6066
	// Add the Access Code details to the public-api.wordpress.com redirect
6067
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6068
		return add_query_arg(
6069
			urlencode_deep(
6070
				array(
6071
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6072
					'jetpack-user-id' => (int) $user->ID,
6073
					'jetpack-state'   => $this->json_api_authorization_request['state'],
6074
				)
6075
			),
6076
			$redirect_to
6077
		);
6078
	}
6079
6080
6081
	/**
6082
	 * Verifies the request by checking the signature
6083
	 *
6084
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6085
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6086
	 *
6087
	 * @param null|array $environment
6088
	 */
6089
	function verify_json_api_authorization_request( $environment = null ) {
6090
		$environment = is_null( $environment )
6091
			? $_REQUEST
6092
			: $environment;
6093
6094
		list( $envToken, $envVersion, $envUserId ) = explode( ':', $environment['token'] );
0 ignored issues
show
Unused Code introduced by
The assignment to $envVersion is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
6095
		$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...
6096
		if ( ! $token || empty( $token->secret ) ) {
6097
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6098
		}
6099
6100
		$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' );
6101
6102
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
6103
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6104
			/**
6105
			 * Jetpack authorisation request Error.
6106
			 *
6107
			 * @since 7.5.0
6108
			 */
6109
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6110
			$die_error = sprintf(
6111
				/* translators: %s is a URL */
6112
				__( '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' ),
6113
				Redirect::get_url( 'jetpack-support-double-encoding' )
6114
			);
6115
		}
6116
6117
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6118
6119
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6120
			$signature = $jetpack_signature->sign_request(
6121
				$environment['token'],
6122
				$environment['timestamp'],
6123
				$environment['nonce'],
6124
				'',
6125
				'GET',
6126
				$environment['jetpack_json_api_original_query'],
6127
				null,
6128
				true
6129
			);
6130
		} else {
6131
			$signature = $jetpack_signature->sign_current_request(
6132
				array(
6133
					'body'   => null,
6134
					'method' => 'GET',
6135
				)
6136
			);
6137
		}
6138
6139
		if ( ! $signature ) {
6140
			wp_die( $die_error );
6141
		} elseif ( is_wp_error( $signature ) ) {
6142
			wp_die( $die_error );
6143
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6144
			if ( is_ssl() ) {
6145
				// 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
6146
				$signature = $jetpack_signature->sign_current_request(
6147
					array(
6148
						'scheme' => 'http',
6149
						'body'   => null,
6150
						'method' => 'GET',
6151
					)
6152
				);
6153
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6154
					wp_die( $die_error );
6155
				}
6156
			} else {
6157
				wp_die( $die_error );
6158
			}
6159
		}
6160
6161
		$timestamp = (int) $environment['timestamp'];
6162
		$nonce     = stripslashes( (string) $environment['nonce'] );
6163
6164
		if ( ! $this->connection_manager ) {
6165
			$this->connection_manager = new Connection_Manager();
6166
		}
6167
6168
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
6169
			// De-nonce the nonce, at least for 5 minutes.
6170
			// 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)
6171
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6172
			if ( $old_nonce_time < time() - 300 ) {
6173
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6174
			}
6175
		}
6176
6177
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6178
		$data_filters = array(
6179
			'state'        => 'opaque',
6180
			'client_id'    => 'int',
6181
			'client_title' => 'string',
6182
			'client_image' => 'url',
6183
		);
6184
6185
		foreach ( $data_filters as $key => $sanitation ) {
6186
			if ( ! isset( $data->$key ) ) {
6187
				wp_die( $die_error );
6188
			}
6189
6190
			switch ( $sanitation ) {
6191
				case 'int':
6192
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6193
					break;
6194
				case 'opaque':
6195
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6196
					break;
6197
				case 'string':
6198
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6199
					break;
6200
				case 'url':
6201
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6202
					break;
6203
			}
6204
		}
6205
6206
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6207
			wp_die( $die_error );
6208
		}
6209
	}
6210
6211
	function login_message_json_api_authorization( $message ) {
6212
		return '<p class="message">' . sprintf(
6213
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6214
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6215
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6216
	}
6217
6218
	/**
6219
	 * Get $content_width, but with a <s>twist</s> filter.
6220
	 */
6221
	public static function get_content_width() {
6222
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6223
			? $GLOBALS['content_width']
6224
			: false;
6225
		/**
6226
		 * Filter the Content Width value.
6227
		 *
6228
		 * @since 2.2.3
6229
		 *
6230
		 * @param string $content_width Content Width value.
6231
		 */
6232
		return apply_filters( 'jetpack_content_width', $content_width );
6233
	}
6234
6235
	/**
6236
	 * Pings the WordPress.com Mirror Site for the specified options.
6237
	 *
6238
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6239
	 *
6240
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6241
	 */
6242
	public function get_cloud_site_options( $option_names ) {
6243
		$option_names = array_filter( (array) $option_names, 'is_string' );
6244
6245
		$xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER ) );
6246
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6247
		if ( $xml->isError() ) {
6248
			return array(
6249
				'error_code' => $xml->getErrorCode(),
6250
				'error_msg'  => $xml->getErrorMessage(),
6251
			);
6252
		}
6253
		$cloud_site_options = $xml->getResponse();
6254
6255
		return $cloud_site_options;
6256
	}
6257
6258
	/**
6259
	 * Checks if the site is currently in an identity crisis.
6260
	 *
6261
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6262
	 */
6263
	public static function check_identity_crisis() {
6264
		if ( ! self::is_active() || ( new Status() )->is_development_mode() || ! self::validate_sync_error_idc_option() ) {
6265
			return false;
6266
		}
6267
6268
		return Jetpack_Options::get_option( 'sync_error_idc' );
6269
	}
6270
6271
	/**
6272
	 * Checks whether the home and siteurl specifically are whitelisted
6273
	 * Written so that we don't have re-check $key and $value params every time
6274
	 * we want to check if this site is whitelisted, for example in footer.php
6275
	 *
6276
	 * @since  3.8.0
6277
	 * @return bool True = already whitelisted False = not whitelisted
6278
	 */
6279
	public static function is_staging_site() {
6280
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6281
		return ( new Status() )->is_staging_site();
6282
	}
6283
6284
	/**
6285
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6286
	 *
6287
	 * @since 4.4.0
6288
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6289
	 *
6290
	 * @return bool
6291
	 */
6292
	public static function validate_sync_error_idc_option() {
6293
		$is_valid = false;
6294
6295
		$idc_allowed = get_transient( 'jetpack_idc_allowed' );
6296
		if ( false === $idc_allowed ) {
6297
			$response = wp_remote_get( 'https://jetpack.com/is-idc-allowed/' );
6298
			if ( 200 === (int) wp_remote_retrieve_response_code( $response ) ) {
6299
				$json               = json_decode( wp_remote_retrieve_body( $response ) );
6300
				$idc_allowed        = isset( $json, $json->result ) && $json->result ? '1' : '0';
6301
				$transient_duration = HOUR_IN_SECONDS;
6302
			} else {
6303
				// If the request failed for some reason, then assume IDC is allowed and set shorter transient.
6304
				$idc_allowed        = '1';
6305
				$transient_duration = 5 * MINUTE_IN_SECONDS;
6306
			}
6307
6308
			set_transient( 'jetpack_idc_allowed', $idc_allowed, $transient_duration );
6309
		}
6310
6311
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6312
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6313
		if ( $idc_allowed && $sync_error && self::sync_idc_optin() ) {
6314
			$local_options = self::get_sync_error_idc_option();
6315
			// Ensure all values are set.
6316
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6317
				if ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6318
					$is_valid = true;
6319
				}
6320
			}
6321
		}
6322
6323
		/**
6324
		 * Filters whether the sync_error_idc option is valid.
6325
		 *
6326
		 * @since 4.4.0
6327
		 *
6328
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6329
		 */
6330
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6331
6332
		if ( ! $idc_allowed || ( ! $is_valid && $sync_error ) ) {
6333
			// Since the option exists, and did not validate, delete it
6334
			Jetpack_Options::delete_option( 'sync_error_idc' );
6335
		}
6336
6337
		return $is_valid;
6338
	}
6339
6340
	/**
6341
	 * Normalizes a url by doing three things:
6342
	 *  - Strips protocol
6343
	 *  - Strips www
6344
	 *  - Adds a trailing slash
6345
	 *
6346
	 * @since 4.4.0
6347
	 * @param string $url
6348
	 * @return WP_Error|string
6349
	 */
6350
	public static function normalize_url_protocol_agnostic( $url ) {
6351
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6352
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6353
			return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
0 ignored issues
show
Unused Code introduced by
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...
6354
		}
6355
6356
		// Strip www and protocols
6357
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6358
		return $url;
6359
	}
6360
6361
	/**
6362
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6363
	 *
6364
	 * @since 4.4.0
6365
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6366
	 *
6367
	 * @param array $response
6368
	 * @return array Array of the local urls, wpcom urls, and error code
6369
	 */
6370
	public static function get_sync_error_idc_option( $response = array() ) {
6371
		// Since the local options will hit the database directly, store the values
6372
		// in a transient to allow for autoloading and caching on subsequent views.
6373
		$local_options = get_transient( 'jetpack_idc_local' );
6374
		if ( false === $local_options ) {
6375
			$local_options = array(
6376
				'home'    => Functions::home_url(),
6377
				'siteurl' => Functions::site_url(),
6378
			);
6379
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6380
		}
6381
6382
		$options = array_merge( $local_options, $response );
6383
6384
		$returned_values = array();
6385
		foreach ( $options as $key => $option ) {
6386
			if ( 'error_code' === $key ) {
6387
				$returned_values[ $key ] = $option;
6388
				continue;
6389
			}
6390
6391
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6392
				continue;
6393
			}
6394
6395
			$returned_values[ $key ] = $normalized_url;
6396
		}
6397
6398
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6399
6400
		return $returned_values;
6401
	}
6402
6403
	/**
6404
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6405
	 * If set to true, the site will be put into staging mode.
6406
	 *
6407
	 * @since 4.3.2
6408
	 * @return bool
6409
	 */
6410
	public static function sync_idc_optin() {
6411
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6412
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6413
		} else {
6414
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6415
		}
6416
6417
		/**
6418
		 * Allows sites to opt in to IDC mitigation which blocks the site from syncing to WordPress.com when the home
6419
		 * URL or site URL do not match what WordPress.com expects. The default value is either false, or the value of
6420
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6421
		 *
6422
		 * @since 4.3.2
6423
		 *
6424
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6425
		 */
6426
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6427
	}
6428
6429
	/**
6430
	 * Maybe Use a .min.css stylesheet, maybe not.
6431
	 *
6432
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6433
	 */
6434
	public static function maybe_min_asset( $url, $path, $plugin ) {
6435
		// Short out on things trying to find actual paths.
6436
		if ( ! $path || empty( $plugin ) ) {
6437
			return $url;
6438
		}
6439
6440
		$path = ltrim( $path, '/' );
6441
6442
		// Strip out the abspath.
6443
		$base = dirname( plugin_basename( $plugin ) );
6444
6445
		// Short out on non-Jetpack assets.
6446
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6447
			return $url;
6448
		}
6449
6450
		// File name parsing.
6451
		$file              = "{$base}/{$path}";
6452
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6453
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6454
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6455
		$extension         = array_shift( $file_name_parts_r );
6456
6457
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6458
			// Already pointing at the minified version.
6459
			if ( 'min' === $file_name_parts_r[0] ) {
6460
				return $url;
6461
			}
6462
6463
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6464
			if ( file_exists( $min_full_path ) ) {
6465
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6466
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6467
				if ( 'css' === $extension ) {
6468
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6469
					self::$min_assets[ $key ] = $path;
6470
				}
6471
			}
6472
		}
6473
6474
		return $url;
6475
	}
6476
6477
	/**
6478
	 * If the asset is minified, let's flag .min as the suffix.
6479
	 *
6480
	 * Attached to `style_loader_src` filter.
6481
	 *
6482
	 * @param string $tag The tag that would link to the external asset.
0 ignored issues
show
Bug introduced by
There is no parameter named $tag. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6483
	 * @param string $handle The registered handle of the script in question.
6484
	 * @param string $href The url of the asset in question.
0 ignored issues
show
Bug introduced by
There is no parameter named $href. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
6485
	 */
6486
	public static function set_suffix_on_min( $src, $handle ) {
6487
		if ( false === strpos( $src, '.min.css' ) ) {
6488
			return $src;
6489
		}
6490
6491
		if ( ! empty( self::$min_assets ) ) {
6492
			foreach ( self::$min_assets as $file => $path ) {
6493
				if ( false !== strpos( $src, $file ) ) {
6494
					wp_style_add_data( $handle, 'suffix', '.min' );
6495
					return $src;
6496
				}
6497
			}
6498
		}
6499
6500
		return $src;
6501
	}
6502
6503
	/**
6504
	 * Maybe inlines a stylesheet.
6505
	 *
6506
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6507
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6508
	 *
6509
	 * Attached to `style_loader_tag` filter.
6510
	 *
6511
	 * @param string $tag The tag that would link to the external asset.
6512
	 * @param string $handle The registered handle of the script in question.
6513
	 *
6514
	 * @return string
6515
	 */
6516
	public static function maybe_inline_style( $tag, $handle ) {
6517
		global $wp_styles;
6518
		$item = $wp_styles->registered[ $handle ];
6519
6520
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6521
			return $tag;
6522
		}
6523
6524
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6525
			$href = $matches[1];
6526
			// Strip off query string
6527
			if ( $pos = strpos( $href, '?' ) ) {
6528
				$href = substr( $href, 0, $pos );
6529
			}
6530
			// Strip off fragment
6531
			if ( $pos = strpos( $href, '#' ) ) {
6532
				$href = substr( $href, 0, $pos );
6533
			}
6534
		} else {
6535
			return $tag;
6536
		}
6537
6538
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6539
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6540
			return $tag;
6541
		}
6542
6543
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6544
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6545
			// And this isn't the pass that actually deals with the RTL version...
6546
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6547
				// Short out, as the RTL version will deal with it in a moment.
6548
				return $tag;
6549
			}
6550
		}
6551
6552
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6553
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6554
		if ( $css ) {
6555
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6556
			if ( empty( $item->extra['after'] ) ) {
6557
				wp_add_inline_style( $handle, $css );
6558
			} else {
6559
				array_unshift( $item->extra['after'], $css );
6560
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6561
			}
6562
		}
6563
6564
		return $tag;
6565
	}
6566
6567
	/**
6568
	 * Loads a view file from the views
6569
	 *
6570
	 * Data passed in with the $data parameter will be available in the
6571
	 * template file as $data['value']
6572
	 *
6573
	 * @param string $template - Template file to load
6574
	 * @param array  $data - Any data to pass along to the template
6575
	 * @return boolean - If template file was found
6576
	 **/
6577
	public function load_view( $template, $data = array() ) {
6578
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6579
6580
		if ( file_exists( $views_dir . $template ) ) {
6581
			require_once $views_dir . $template;
6582
			return true;
6583
		}
6584
6585
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6586
		return false;
6587
	}
6588
6589
	/**
6590
	 * Throws warnings for deprecated hooks to be removed from Jetpack
6591
	 */
6592
	public function deprecated_hooks() {
6593
		global $wp_filter;
6594
6595
		/*
6596
		 * Format:
6597
		 * deprecated_filter_name => replacement_name
6598
		 *
6599
		 * If there is no replacement, use null for replacement_name
6600
		 */
6601
		$deprecated_list = array(
6602
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6603
			'wpl_sharing_2014_1'                           => null,
6604
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6605
			'jetpack_identity_crisis_options_to_check'     => null,
6606
			'update_option_jetpack_single_user_site'       => null,
6607
			'audio_player_default_colors'                  => null,
6608
			'add_option_jetpack_featured_images_enabled'   => null,
6609
			'add_option_jetpack_update_details'            => null,
6610
			'add_option_jetpack_updates'                   => null,
6611
			'add_option_jetpack_network_name'              => null,
6612
			'add_option_jetpack_network_allow_new_registrations' => null,
6613
			'add_option_jetpack_network_add_new_users'     => null,
6614
			'add_option_jetpack_network_site_upload_space' => null,
6615
			'add_option_jetpack_network_upload_file_types' => null,
6616
			'add_option_jetpack_network_enable_administration_menus' => null,
6617
			'add_option_jetpack_is_multi_site'             => null,
6618
			'add_option_jetpack_is_main_network'           => null,
6619
			'add_option_jetpack_main_network_site'         => null,
6620
			'jetpack_sync_all_registered_options'          => null,
6621
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6622
			'jetpack_is_post_mailable'                     => null,
6623
			'jetpack_seo_site_host'                        => null,
6624
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6625
			'jetpack_holiday_snow_option_name'             => null,
6626
			'jetpack_holiday_chance_of_snow'               => null,
6627
			'jetpack_holiday_snow_js_url'                  => null,
6628
			'jetpack_is_holiday_snow_season'               => null,
6629
			'jetpack_holiday_snow_option_updated'          => null,
6630
			'jetpack_holiday_snowing'                      => null,
6631
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6632
			'jetpack_cache_plans'                          => null,
6633
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6634
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6635
			'jetpack_enable_site_verification'             => null,
6636
			'can_display_jetpack_manage_notice'            => null,
6637
			// Removed in Jetpack 7.3.0
6638
			'atd_load_scripts'                             => null,
6639
			'atd_http_post_timeout'                        => null,
6640
			'atd_http_post_error'                          => null,
6641
			'atd_service_domain'                           => null,
6642
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6643
			// Removed in Jetpack 7.9.0
6644
			'jetpack_pwa_manifest'                         => null,
6645
			'jetpack_pwa_background_color'                 => null,
6646
			// Removed in Jetpack 8.3.0.
6647
			'jetpack_check_mobile'                         => null,
6648
			'jetpack_mobile_stylesheet'                    => null,
6649
			'jetpack_mobile_template'                      => null,
6650
			'mobile_reject_mobile'                         => null,
6651
			'mobile_force_mobile'                          => null,
6652
			'mobile_app_promo_download'                    => null,
6653
			'mobile_setup'                                 => null,
6654
			'jetpack_mobile_footer_before'                 => null,
6655
			'wp_mobile_theme_footer'                       => null,
6656
			'minileven_credits'                            => null,
6657
			'jetpack_mobile_header_before'                 => null,
6658
			'jetpack_mobile_header_after'                  => null,
6659
			'jetpack_mobile_theme_menu'                    => null,
6660
			'minileven_show_featured_images'               => null,
6661
			'minileven_attachment_size'                    => null,
6662
		);
6663
6664
		// This is a silly loop depth. Better way?
6665
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6666
			if ( has_action( $hook ) ) {
6667
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6668
					foreach ( $values as $hooked ) {
6669
						if ( is_callable( $hooked['function'] ) ) {
6670
							$function_name = $hooked['function'];
6671
						} else {
6672
							$function_name = 'an anonymous function';
6673
						}
6674
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6675
					}
6676
				}
6677
			}
6678
		}
6679
	}
6680
6681
	/**
6682
	 * Converts any url in a stylesheet, to the correct absolute url.
6683
	 *
6684
	 * Considerations:
6685
	 *  - Normal, relative URLs     `feh.png`
6686
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6687
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6688
	 *  - Absolute URLs             `http://domain.com/feh.png`
6689
	 *  - Domain root relative URLs `/feh.png`
6690
	 *
6691
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6692
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6693
	 *
6694
	 * @return mixed|string
6695
	 */
6696
	public static function absolutize_css_urls( $css, $css_file_url ) {
6697
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6698
		$css_dir = dirname( $css_file_url );
6699
		$p       = wp_parse_url( $css_dir );
6700
		$domain  = sprintf(
6701
			'%1$s//%2$s%3$s%4$s',
6702
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6703
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6704
			$p['host'],
6705
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6706
		);
6707
6708
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6709
			$find = $replace = array();
6710
			foreach ( $matches as $match ) {
6711
				$url = trim( $match['path'], "'\" \t" );
6712
6713
				// If this is a data url, we don't want to mess with it.
6714
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6715
					continue;
6716
				}
6717
6718
				// If this is an absolute or protocol-agnostic url,
6719
				// we don't want to mess with it.
6720
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6721
					continue;
6722
				}
6723
6724
				switch ( substr( $url, 0, 1 ) ) {
6725
					case '/':
6726
						$absolute = $domain . $url;
6727
						break;
6728
					default:
6729
						$absolute = $css_dir . '/' . $url;
6730
				}
6731
6732
				$find[]    = $match[0];
6733
				$replace[] = sprintf( 'url("%s")', $absolute );
6734
			}
6735
			$css = str_replace( $find, $replace, $css );
6736
		}
6737
6738
		return $css;
6739
	}
6740
6741
	/**
6742
	 * This methods removes all of the registered css files on the front end
6743
	 * from Jetpack in favor of using a single file. In effect "imploding"
6744
	 * all the files into one file.
6745
	 *
6746
	 * Pros:
6747
	 * - Uses only ONE css asset connection instead of 15
6748
	 * - Saves a minimum of 56k
6749
	 * - Reduces server load
6750
	 * - Reduces time to first painted byte
6751
	 *
6752
	 * Cons:
6753
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6754
	 *      should not cause any issues with themes.
6755
	 * - Plugins/themes dequeuing styles no longer do anything. See
6756
	 *      jetpack_implode_frontend_css filter for a workaround
6757
	 *
6758
	 * For some situations developers may wish to disable css imploding and
6759
	 * instead operate in legacy mode where each file loads seperately and
6760
	 * can be edited individually or dequeued. This can be accomplished with
6761
	 * the following line:
6762
	 *
6763
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6764
	 *
6765
	 * @since 3.2
6766
	 **/
6767
	public function implode_frontend_css( $travis_test = false ) {
6768
		$do_implode = true;
6769
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6770
			$do_implode = false;
6771
		}
6772
6773
		// Do not implode CSS when the page loads via the AMP plugin.
6774
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6775
			$do_implode = false;
6776
		}
6777
6778
		/**
6779
		 * Allow CSS to be concatenated into a single jetpack.css file.
6780
		 *
6781
		 * @since 3.2.0
6782
		 *
6783
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6784
		 */
6785
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6786
6787
		// Do not use the imploded file when default behavior was altered through the filter
6788
		if ( ! $do_implode ) {
6789
			return;
6790
		}
6791
6792
		// We do not want to use the imploded file in dev mode, or if not connected
6793
		if ( ( new Status() )->is_development_mode() || ! self::is_active() ) {
6794
			if ( ! $travis_test ) {
6795
				return;
6796
			}
6797
		}
6798
6799
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6800
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6801
			return;
6802
		}
6803
6804
		/*
6805
		 * Now we assume Jetpack is connected and able to serve the single
6806
		 * file.
6807
		 *
6808
		 * In the future there will be a check here to serve the file locally
6809
		 * or potentially from the Jetpack CDN
6810
		 *
6811
		 * For now:
6812
		 * - Enqueue a single imploded css file
6813
		 * - Zero out the style_loader_tag for the bundled ones
6814
		 * - Be happy, drink scotch
6815
		 */
6816
6817
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6818
6819
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6820
6821
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6822
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6823
	}
6824
6825
	function concat_remove_style_loader_tag( $tag, $handle ) {
6826
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6827
			$tag = '';
6828
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6829
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6830
			}
6831
		}
6832
6833
		return $tag;
6834
	}
6835
6836
	/**
6837
	 * @deprecated
6838
	 * @see Automattic\Jetpack\Assets\add_aync_script
6839
	 */
6840
	public function script_add_async( $tag, $handle, $src ) {
6841
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6842
	}
6843
6844
	/*
6845
	 * Check the heartbeat data
6846
	 *
6847
	 * Organizes the heartbeat data by severity.  For example, if the site
6848
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6849
	 *
6850
	 * Data will be added to "caution" array, if it either:
6851
	 *  - Out of date Jetpack version
6852
	 *  - Out of date WP version
6853
	 *  - Out of date PHP version
6854
	 *
6855
	 * $return array $filtered_data
6856
	 */
6857
	public static function jetpack_check_heartbeat_data() {
6858
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6859
6860
		$good    = array();
6861
		$caution = array();
6862
		$bad     = array();
6863
6864
		foreach ( $raw_data as $stat => $value ) {
6865
6866
			// Check jetpack version
6867
			if ( 'version' == $stat ) {
6868
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6869
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6870
					continue;
6871
				}
6872
			}
6873
6874
			// Check WP version
6875
			if ( 'wp-version' == $stat ) {
6876
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6877
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6878
					continue;
6879
				}
6880
			}
6881
6882
			// Check PHP version
6883
			if ( 'php-version' == $stat ) {
6884
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6885
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6886
					continue;
6887
				}
6888
			}
6889
6890
			// Check ID crisis
6891
			if ( 'identitycrisis' == $stat ) {
6892
				if ( 'yes' == $value ) {
6893
					$bad[ $stat ] = $value;
6894
					continue;
6895
				}
6896
			}
6897
6898
			// The rest are good :)
6899
			$good[ $stat ] = $value;
6900
		}
6901
6902
		$filtered_data = array(
6903
			'good'    => $good,
6904
			'caution' => $caution,
6905
			'bad'     => $bad,
6906
		);
6907
6908
		return $filtered_data;
6909
	}
6910
6911
6912
	/*
6913
	 * This method is used to organize all options that can be reset
6914
	 * without disconnecting Jetpack.
6915
	 *
6916
	 * It is used in class.jetpack-cli.php to reset options
6917
	 *
6918
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6919
	 *
6920
	 * @return array of options to delete.
6921
	 */
6922
	public static function get_jetpack_options_for_reset() {
6923
		return Jetpack_Options::get_options_for_reset();
6924
	}
6925
6926
	/*
6927
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6928
	 * so we can bring them directly to their site in calypso.
6929
	 *
6930
	 * @param string | url
6931
	 * @return string | url without the guff
6932
	 */
6933 View Code Duplication
	public static function build_raw_urls( $url ) {
6934
		$strip_http = '/.*?:\/\//i';
6935
		$url        = preg_replace( $strip_http, '', $url );
6936
		$url        = str_replace( '/', '::', $url );
6937
		return $url;
6938
	}
6939
6940
	/**
6941
	 * Stores and prints out domains to prefetch for page speed optimization.
6942
	 *
6943
	 * @param mixed $new_urls
6944
	 */
6945
	public static function dns_prefetch( $new_urls = null ) {
6946
		static $prefetch_urls = array();
6947
		if ( empty( $new_urls ) && ! empty( $prefetch_urls ) ) {
6948
			echo "\r\n";
6949
			foreach ( $prefetch_urls as $this_prefetch_url ) {
6950
				printf( "<link rel='dns-prefetch' href='%s'/>\r\n", esc_attr( $this_prefetch_url ) );
6951
			}
6952
		} elseif ( ! empty( $new_urls ) ) {
6953
			if ( ! has_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) ) ) {
6954
				add_action( 'wp_head', array( __CLASS__, __FUNCTION__ ) );
6955
			}
6956
			foreach ( (array) $new_urls as $this_new_url ) {
6957
				$prefetch_urls[] = strtolower( untrailingslashit( preg_replace( '#^https?://#i', '//', $this_new_url ) ) );
6958
			}
6959
			$prefetch_urls = array_unique( $prefetch_urls );
6960
		}
6961
	}
6962
6963
	public function wp_dashboard_setup() {
6964
		if ( self::is_active() ) {
6965
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6966
		}
6967
6968
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6969
			$jetpack_logo = new Jetpack_Logo();
6970
			$widget_title = sprintf(
6971
				wp_kses(
6972
					/* translators: Placeholder is a Jetpack logo. */
6973
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6974
					array( 'span' => array() )
6975
				),
6976
				$jetpack_logo->get_jp_emblem( true )
6977
			);
6978
6979
			wp_add_dashboard_widget(
6980
				'jetpack_summary_widget',
6981
				$widget_title,
6982
				array( __CLASS__, 'dashboard_widget' )
6983
			);
6984
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6985
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6986
6987
			// If we're inactive and not in development mode, sort our box to the top.
6988
			if ( ! self::is_active() && ! ( new Status() )->is_development_mode() ) {
6989
				global $wp_meta_boxes;
6990
6991
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6992
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6993
6994
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6995
			}
6996
		}
6997
	}
6998
6999
	/**
7000
	 * @param mixed $result Value for the user's option
0 ignored issues
show
Bug introduced by
There is no parameter named $result. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
7001
	 * @return mixed
7002
	 */
7003
	function get_user_option_meta_box_order_dashboard( $sorted ) {
7004
		if ( ! is_array( $sorted ) ) {
7005
			return $sorted;
7006
		}
7007
7008
		foreach ( $sorted as $box_context => $ids ) {
7009
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7010
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7011
				continue;
7012
			}
7013
7014
			$ids_array = explode( ',', $ids );
7015
			$key       = array_search( 'dashboard_stats', $ids_array );
7016
7017
			if ( false !== $key ) {
7018
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7019
				$ids_array[ $key ]      = 'jetpack_summary_widget';
7020
				$sorted[ $box_context ] = implode( ',', $ids_array );
7021
				// We've found it, stop searching, and just return.
7022
				break;
7023
			}
7024
		}
7025
7026
		return $sorted;
7027
	}
7028
7029
	public static function dashboard_widget() {
7030
		/**
7031
		 * Fires when the dashboard is loaded.
7032
		 *
7033
		 * @since 3.4.0
7034
		 */
7035
		do_action( 'jetpack_dashboard_widget' );
7036
	}
7037
7038
	public static function dashboard_widget_footer() {
7039
		?>
7040
		<footer>
7041
7042
		<div class="protect">
7043
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7044
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7045
				<p class="blocked-count">
7046
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7047
				</p>
7048
				<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>
7049
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_development_mode() ) : ?>
7050
				<a href="
7051
				<?php
7052
				echo esc_url(
7053
					wp_nonce_url(
7054
						self::admin_url(
7055
							array(
7056
								'action' => 'activate',
7057
								'module' => 'protect',
7058
							)
7059
						),
7060
						'jetpack_activate-protect'
7061
					)
7062
				);
7063
				?>
7064
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7065
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7066
				</a>
7067
			<?php else : ?>
7068
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7069
			<?php endif; ?>
7070
		</div>
7071
7072
		<div class="akismet">
7073
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7074
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7075
				<p class="blocked-count">
7076
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7077
				</p>
7078
				<p><?php echo esc_html_x( 'Blocked spam comments.', '{#} Spam comments blocked by Akismet -- number is on a prior line, text is a caption.', 'jetpack' ); ?></p>
7079
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7080
				<a href="
7081
				<?php
7082
				echo esc_url(
7083
					wp_nonce_url(
7084
						add_query_arg(
7085
							array(
7086
								'action' => 'activate',
7087
								'plugin' => 'akismet/akismet.php',
7088
							),
7089
							admin_url( 'plugins.php' )
7090
						),
7091
						'activate-plugin_akismet/akismet.php'
7092
					)
7093
				);
7094
				?>
7095
							" class="button button-jetpack">
7096
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7097
				</a>
7098
			<?php else : ?>
7099
				<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( 'Anti-spam can help to keep your blog safe from spam!', 'jetpack' ); ?></a></p>
7100
			<?php endif; ?>
7101
		</div>
7102
7103
		</footer>
7104
		<?php
7105
	}
7106
7107
	/*
7108
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7109
	 */
7110
	function jetpack_icon_user_connected( $columns ) {
7111
		$columns['user_jetpack'] = '';
7112
		return $columns;
7113
	}
7114
7115
	/*
7116
	 * Show Jetpack icon if the user is linked.
7117
	 */
7118
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7119
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7120
			$jetpack_logo = new Jetpack_Logo();
7121
			$emblem_html  = sprintf(
7122
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7123
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7124
				$jetpack_logo->get_jp_emblem()
7125
			);
7126
			return $emblem_html;
7127
		}
7128
7129
		return $val;
7130
	}
7131
7132
	/*
7133
	 * Style the Jetpack user column
7134
	 */
7135
	function jetpack_user_col_style() {
7136
		global $current_screen;
7137
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7138
			?>
7139
			<style>
7140
				.fixed .column-user_jetpack {
7141
					width: 21px;
7142
				}
7143
				.jp-emblem-user-admin svg {
7144
					width: 20px;
7145
					height: 20px;
7146
				}
7147
				.jp-emblem-user-admin path {
7148
					fill: #00BE28;
7149
				}
7150
			</style>
7151
			<?php
7152
		}
7153
	}
7154
7155
	/**
7156
	 * Checks if Akismet is active and working.
7157
	 *
7158
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7159
	 * that implied usage of methods present since more recent version.
7160
	 * See https://github.com/Automattic/jetpack/pull/9585
7161
	 *
7162
	 * @since  5.1.0
7163
	 *
7164
	 * @return bool True = Akismet available. False = Aksimet not available.
7165
	 */
7166
	public static function is_akismet_active() {
7167
		static $status = null;
7168
7169
		if ( ! is_null( $status ) ) {
7170
			return $status;
7171
		}
7172
7173
		// Check if a modern version of Akismet is active.
7174
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7175
			$status = false;
7176
			return $status;
7177
		}
7178
7179
		// Make sure there is a key known to Akismet at all before verifying key.
7180
		$akismet_key = Akismet::get_api_key();
7181
		if ( ! $akismet_key ) {
7182
			$status = false;
7183
			return $status;
7184
		}
7185
7186
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7187
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7188
7189
		// 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.
7190
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7191
		// We cache the result of the Akismet key verification for ten minutes.
7192
		if ( ! $akismet_key_state || $recheck ) {
7193
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7194
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7195
		}
7196
7197
		$status = 'valid' === $akismet_key_state;
7198
7199
		return $status;
7200
	}
7201
7202
	/**
7203
	 * @deprecated
7204
	 *
7205
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7206
	 */
7207
	public static function is_function_in_backtrace() {
7208
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7209
	}
7210
7211
	/**
7212
	 * Given a minified path, and a non-minified path, will return
7213
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7214
	 *
7215
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7216
	 * root Jetpack directory.
7217
	 *
7218
	 * @since 5.6.0
7219
	 *
7220
	 * @param string $min_path
7221
	 * @param string $non_min_path
7222
	 * @return string The URL to the file
7223
	 */
7224
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7225
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7226
	}
7227
7228
	/**
7229
	 * Checks for whether Jetpack Backup is enabled.
7230
	 * Will return true if the state of Backup is anything except "unavailable".
7231
	 *
7232
	 * @return bool|int|mixed
7233
	 */
7234
	public static function is_rewind_enabled() {
7235
		if ( ! self::is_active() ) {
7236
			return false;
7237
		}
7238
7239
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7240
		if ( false === $rewind_enabled ) {
7241
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7242
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7243
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7244
				&& ! empty( $rewind_data['state'] )
7245
				&& 'active' === $rewind_data['state'] )
7246
				? 1
7247
				: 0;
7248
7249
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7250
		}
7251
		return $rewind_enabled;
7252
	}
7253
7254
	/**
7255
	 * Return Calypso environment value; used for developing Jetpack and pairing
7256
	 * it with different Calypso enrionments, such as localhost.
7257
	 *
7258
	 * @since 7.4.0
7259
	 *
7260
	 * @return string Calypso environment
7261
	 */
7262
	public static function get_calypso_env() {
7263
		if ( isset( $_GET['calypso_env'] ) ) {
7264
			return sanitize_key( $_GET['calypso_env'] );
7265
		}
7266
7267
		if ( getenv( 'CALYPSO_ENV' ) ) {
7268
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7269
		}
7270
7271
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7272
			return sanitize_key( CALYPSO_ENV );
7273
		}
7274
7275
		return '';
7276
	}
7277
7278
	/**
7279
	 * Returns the hostname with protocol for Calypso.
7280
	 * Used for developing Jetpack with Calypso.
7281
	 *
7282
	 * @since 8.4.0
7283
	 *
7284
	 * @return string Calypso host.
7285
	 */
7286
	public static function get_calypso_host() {
7287
		$calypso_env = self::get_calypso_env();
7288
		switch ( $calypso_env ) {
7289
			case 'development':
7290
				return 'http://calypso.localhost:3000/';
7291
			case 'wpcalypso':
7292
				return 'https://wpcalypso.wordpress.com/';
7293
			case 'horizon':
7294
				return 'https://horizon.wordpress.com/';
7295
			default:
7296
				return 'https://wordpress.com/';
7297
		}
7298
	}
7299
7300
	/**
7301
	 * Checks whether or not TOS has been agreed upon.
7302
	 * Will return true if a user has clicked to register, or is already connected.
7303
	 */
7304
	public static function jetpack_tos_agreed() {
7305
		_deprecated_function( 'Jetpack::jetpack_tos_agreed', 'Jetpack 7.9.0', '\Automattic\Jetpack\Terms_Of_Service->has_agreed' );
7306
7307
		$terms_of_service = new Terms_Of_Service();
7308
		return $terms_of_service->has_agreed();
7309
7310
	}
7311
7312
	/**
7313
	 * Handles activating default modules as well general cleanup for the new connection.
7314
	 *
7315
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7316
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7317
	 * @param boolean $send_state_messages          Whether to send state messages.
7318
	 * @return void
7319
	 */
7320
	public static function handle_post_authorization_actions(
7321
		$activate_sso = false,
7322
		$redirect_on_activation_error = false,
7323
		$send_state_messages = true
7324
	) {
7325
		$other_modules = $activate_sso
7326
			? array( 'sso' )
7327
			: array();
7328
7329
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7330
			self::delete_active_modules();
7331
7332
			self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
0 ignored issues
show
Documentation introduced by
999 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
7333
		} else {
7334
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7335
		}
7336
7337
		// Since this is a fresh connection, be sure to clear out IDC options
7338
		Jetpack_IDC::clear_all_idc_options();
7339
7340
		if ( $send_state_messages ) {
7341
			self::state( 'message', 'authorized' );
7342
		}
7343
	}
7344
7345
	/**
7346
	 * Returns a boolean for whether backups UI should be displayed or not.
7347
	 *
7348
	 * @return bool Should backups UI be displayed?
7349
	 */
7350
	public static function show_backups_ui() {
7351
		/**
7352
		 * Whether UI for backups should be displayed.
7353
		 *
7354
		 * @since 6.5.0
7355
		 *
7356
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7357
		 */
7358
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7359
	}
7360
7361
	/*
7362
	 * Deprecated manage functions
7363
	 */
7364
	function prepare_manage_jetpack_notice() {
7365
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7366
	}
7367
	function manage_activate_screen() {
7368
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7369
	}
7370
	function admin_jetpack_manage_notice() {
7371
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7372
	}
7373
	function opt_out_jetpack_manage_url() {
7374
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7375
	}
7376
	function opt_in_jetpack_manage_url() {
7377
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7378
	}
7379
	function opt_in_jetpack_manage_notice() {
7380
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7381
	}
7382
	function can_display_jetpack_manage_notice() {
7383
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7384
	}
7385
7386
	/**
7387
	 * Clean leftoveruser meta.
7388
	 *
7389
	 * Delete Jetpack-related user meta when it is no longer needed.
7390
	 *
7391
	 * @since 7.3.0
7392
	 *
7393
	 * @param int $user_id User ID being updated.
7394
	 */
7395
	public static function user_meta_cleanup( $user_id ) {
7396
		$meta_keys = array(
7397
			// AtD removed from Jetpack 7.3
7398
			'AtD_options',
7399
			'AtD_check_when',
7400
			'AtD_guess_lang',
7401
			'AtD_ignored_phrases',
7402
		);
7403
7404
		foreach ( $meta_keys as $meta_key ) {
7405
			if ( get_user_meta( $user_id, $meta_key ) ) {
7406
				delete_user_meta( $user_id, $meta_key );
7407
			}
7408
		}
7409
	}
7410
7411
	/**
7412
	 * Checks if a Jetpack site is both active and not in development.
7413
	 *
7414
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_development_mode`.
7415
	 *
7416
	 * @return bool True if Jetpack is active and not in development.
7417
	 */
7418
	public static function is_active_and_not_development_mode() {
7419
		if ( ! self::is_active() || ( new Status() )->is_development_mode() ) {
7420
			return false;
7421
		}
7422
		return true;
7423
	}
7424
7425
	/**
7426
	 * Returns the list of products that we have available for purchase.
7427
	 */
7428
	public static function get_products_for_purchase() {
7429
		$products = array();
7430
		if ( ! is_multisite() ) {
7431
			$products[] = array(
7432
				'key'               => 'backup',
7433
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7434
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7435
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7436
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7437
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7438
				'options'           => array(
7439
					array(
7440
						'type'        => 'daily',
7441
						'slug'        => 'jetpack-backup-daily',
7442
						'key'         => 'jetpack_backup_daily',
7443
						'name'        => __( 'Daily Backups', 'jetpack' ),
7444
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7445
					),
7446
					array(
7447
						'type'        => 'realtime',
7448
						'slug'        => 'jetpack-backup-realtime',
7449
						'key'         => 'jetpack_backup_realtime',
7450
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7451
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7452
					),
7453
				),
7454
				'default_option'    => 'realtime',
7455
				'show_promotion'    => true,
7456
				'discount_percent'  => 70,
7457
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7458
			);
7459
7460
			$products[] = array(
7461
				'key'               => 'scan',
7462
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7463
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7464
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7465
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7466
				'show_promotion'    => true,
7467
				'discount_percent'  => 30,
7468
				'options'           => array(
7469
					array(
7470
						'type'      => 'scan',
7471
						'slug'      => 'jetpack-scan',
7472
						'key'       => 'jetpack_scan',
7473
						'name'      => __( 'Daily Scan', 'jetpack' ),
7474
					),
7475
				),
7476
				'default_option'    => 'scan',
7477
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7478
			);
7479
		}
7480
7481
		$products[] = array(
7482
			'key'               => 'search',
7483
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7484
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7485
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7486
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7487
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7488
			'options'           => array(
7489
				array(
7490
					'type'      => 'search',
7491
					'slug'      => 'jetpack-search',
7492
					'key'       => 'jetpack_search',
7493
					'name'      => __( 'Search', 'jetpack' ),
7494
				),
7495
			),
7496
			'tears'             => array(),
7497
			'default_option'    => 'search',
7498
			'show_promotion'    => false,
7499
			'included_in_plans' => array( 'search-plan' ),
7500
		);
7501
7502
		return $products;
7503
	}
7504
}
7505