Completed
Push — add/changelog-890 ( bdfacc...f7db88 )
by Jeremy
18:36 queued 09:31
created

Jetpack::get_translated_modules()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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

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...
Documentation introduced by
new \Automattic\Jetpack\Status() is of type object<Automattic\Jetpack\Status>, but the function expects a object<Automattic\Jetpac...omattic\Jetpack\Status>.

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

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
5684
				if ( strlen( $v ) ) {
5685
					$state[ $k ] = $v;
5686
				}
5687
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5688
			}
5689
		}
5690
5691
		if ( $restate ) {
5692
			foreach ( $state as $k => $v ) {
5693
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5694
			}
5695
			return;
5696
		}
5697
5698
		// Get a state variable.
5699
		if ( isset( $key ) && ! isset( $value ) ) {
5700
			if ( array_key_exists( $key, $state ) ) {
5701
				return $state[ $key ];
5702
			}
5703
			return null;
5704
		}
5705
5706
		// Set a state variable.
5707
		if ( isset( $key ) && isset( $value ) ) {
5708
			if ( is_array( $value ) && isset( $value[0] ) ) {
5709
				$value = $value[0];
5710
			}
5711
			$state[ $key ] = $value;
5712
			if ( ! headers_sent() ) {
5713
				if ( self::should_set_cookie( $key ) ) {
5714
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5715
				}
5716
			}
5717
		}
5718
	}
5719
5720
	public static function restate() {
5721
		self::state( null, null, true );
5722
	}
5723
5724
	/**
5725
	 * Determines whether the jetpackState[$key] value should be added to the
5726
	 * cookie.
5727
	 *
5728
	 * @param string $key The state key.
5729
	 *
5730
	 * @return boolean Whether the value should be added to the cookie.
5731
	 */
5732
	public static function should_set_cookie( $key ) {
5733
		global $current_screen;
5734
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5735
5736
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5737
			return false;
5738
		}
5739
5740
		return true;
5741
	}
5742
5743
	public static function check_privacy( $file ) {
5744
		static $is_site_publicly_accessible = null;
5745
5746
		if ( is_null( $is_site_publicly_accessible ) ) {
5747
			$is_site_publicly_accessible = false;
5748
5749
			$rpc = new Jetpack_IXR_Client();
5750
5751
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5752
			if ( $success ) {
5753
				$response = $rpc->getResponse();
5754
				if ( $response ) {
5755
					$is_site_publicly_accessible = true;
5756
				}
5757
			}
5758
5759
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5760
		}
5761
5762
		if ( $is_site_publicly_accessible ) {
5763
			return;
5764
		}
5765
5766
		$module_slug = self::get_module_slug( $file );
5767
5768
		$privacy_checks = self::state( 'privacy_checks' );
5769
		if ( ! $privacy_checks ) {
5770
			$privacy_checks = $module_slug;
5771
		} else {
5772
			$privacy_checks .= ",$module_slug";
5773
		}
5774
5775
		self::state( 'privacy_checks', $privacy_checks );
5776
	}
5777
5778
	/**
5779
	 * Helper method for multicall XMLRPC.
5780
	 *
5781
	 * @deprecated since 8.9.0
5782
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5783
	 *
5784
	 * @param ...$args Args for the async_call.
5785
	 */
5786
	public static function xmlrpc_async_call( ...$args ) {
5787
5788
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5789
5790
		global $blog_id;
5791
		static $clients = array();
5792
5793
		$client_blog_id = is_multisite() ? $blog_id : 0;
5794
5795
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5796
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER ) );
5797
			if ( function_exists( 'ignore_user_abort' ) ) {
5798
				ignore_user_abort( true );
5799
			}
5800
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5801
		}
5802
5803
		if ( ! empty( $args[0] ) ) {
5804
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5805
		} elseif ( is_multisite() ) {
5806
			foreach ( $clients as $client_blog_id => $client ) {
5807
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5808
					continue;
5809
				}
5810
5811
				$switch_success = switch_to_blog( $client_blog_id, true );
5812
				if ( ! $switch_success ) {
5813
					continue;
5814
				}
5815
5816
				flush();
5817
				$client->query();
5818
5819
				restore_current_blog();
5820
			}
5821
		} else {
5822
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5823
				flush();
5824
				$clients[0]->query();
5825
			}
5826
		}
5827
	}
5828
5829
	public static function staticize_subdomain( $url ) {
5830
5831
		// Extract hostname from URL
5832
		$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...
5833
5834
		// Explode hostname on '.'
5835
		$exploded_host = explode( '.', $host );
5836
5837
		// Retrieve the name and TLD
5838
		if ( count( $exploded_host ) > 1 ) {
5839
			$name = $exploded_host[ count( $exploded_host ) - 2 ];
5840
			$tld  = $exploded_host[ count( $exploded_host ) - 1 ];
5841
			// Rebuild domain excluding subdomains
5842
			$domain = $name . '.' . $tld;
5843
		} else {
5844
			$domain = $host;
5845
		}
5846
		// Array of Automattic domains.
5847
		$domains_allowed = array( 'wordpress.com', 'wp.com' );
5848
5849
		// Return $url if not an Automattic domain.
5850
		if ( ! in_array( $domain, $domains_allowed, true ) ) {
5851
			return $url;
5852
		}
5853
5854
		if ( is_ssl() ) {
5855
			return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
5856
		}
5857
5858
		srand( crc32( basename( $url ) ) );
5859
		$static_counter = rand( 0, 2 );
5860
		srand(); // this resets everything that relies on this, like array_rand() and shuffle()
5861
5862
		return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
5863
	}
5864
5865
	/* JSON API Authorization */
5866
5867
	/**
5868
	 * Handles the login action for Authorizing the JSON API
5869
	 */
5870
	function login_form_json_api_authorization() {
5871
		$this->verify_json_api_authorization_request();
5872
5873
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5874
5875
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5876
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5877
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5878
	}
5879
5880
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5881
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5882
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5883
			return $url;
5884
		}
5885
5886
		$parsed_url = wp_parse_url( $url );
5887
		$url        = strtok( $url, '?' );
5888
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5889
		if ( ! empty( $parsed_url['query'] ) ) {
5890
			$url .= "&{$parsed_url['query']}";
5891
		}
5892
5893
		return $url;
5894
	}
5895
5896
	// Make sure the POSTed request is handled by the same action
5897
	function preserve_action_in_login_form_for_json_api_authorization() {
5898
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5899
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5900
	}
5901
5902
	// If someone logs in to approve API access, store the Access Code in usermeta
5903
	function store_json_api_authorization_token( $user_login, $user ) {
5904
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5905
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5906
		$token = wp_generate_password( 32, false );
5907
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5908
	}
5909
5910
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5911
	function allow_wpcom_public_api_domain( $domains ) {
5912
		$domains[] = 'public-api.wordpress.com';
5913
		return $domains;
5914
	}
5915
5916
	static function is_redirect_encoded( $redirect_url ) {
5917
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5918
	}
5919
5920
	// Add all wordpress.com environments to the safe redirect allowed list.
5921
	function allow_wpcom_environments( $domains ) {
5922
		$domains[] = 'wordpress.com';
5923
		$domains[] = 'wpcalypso.wordpress.com';
5924
		$domains[] = 'horizon.wordpress.com';
5925
		$domains[] = 'calypso.localhost';
5926
		return $domains;
5927
	}
5928
5929
	// Add the Access Code details to the public-api.wordpress.com redirect
5930
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5931
		return add_query_arg(
5932
			urlencode_deep(
5933
				array(
5934
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5935
					'jetpack-user-id' => (int) $user->ID,
5936
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5937
				)
5938
			),
5939
			$redirect_to
5940
		);
5941
	}
5942
5943
5944
	/**
5945
	 * Verifies the request by checking the signature
5946
	 *
5947
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5948
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5949
	 *
5950
	 * @param null|array $environment
5951
	 */
5952
	function verify_json_api_authorization_request( $environment = null ) {
5953
		$environment = is_null( $environment )
5954
			? $_REQUEST
5955
			: $environment;
5956
5957
		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...
5958
		$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...
5959
		if ( ! $token || empty( $token->secret ) ) {
5960
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5961
		}
5962
5963
		$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' );
5964
5965
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5966
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5967
			/**
5968
			 * Jetpack authorisation request Error.
5969
			 *
5970
			 * @since 7.5.0
5971
			 */
5972
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5973
			$die_error = sprintf(
5974
				/* translators: %s is a URL */
5975
				__( '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' ),
5976
				Redirect::get_url( 'jetpack-support-double-encoding' )
5977
			);
5978
		}
5979
5980
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5981
5982
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5983
			$signature = $jetpack_signature->sign_request(
5984
				$environment['token'],
5985
				$environment['timestamp'],
5986
				$environment['nonce'],
5987
				'',
5988
				'GET',
5989
				$environment['jetpack_json_api_original_query'],
5990
				null,
5991
				true
5992
			);
5993
		} else {
5994
			$signature = $jetpack_signature->sign_current_request(
5995
				array(
5996
					'body'   => null,
5997
					'method' => 'GET',
5998
				)
5999
			);
6000
		}
6001
6002
		if ( ! $signature ) {
6003
			wp_die( $die_error );
6004
		} elseif ( is_wp_error( $signature ) ) {
6005
			wp_die( $die_error );
6006
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6007
			if ( is_ssl() ) {
6008
				// 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
6009
				$signature = $jetpack_signature->sign_current_request(
6010
					array(
6011
						'scheme' => 'http',
6012
						'body'   => null,
6013
						'method' => 'GET',
6014
					)
6015
				);
6016
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6017
					wp_die( $die_error );
6018
				}
6019
			} else {
6020
				wp_die( $die_error );
6021
			}
6022
		}
6023
6024
		$timestamp = (int) $environment['timestamp'];
6025
		$nonce     = stripslashes( (string) $environment['nonce'] );
6026
6027
		if ( ! $this->connection_manager ) {
6028
			$this->connection_manager = new Connection_Manager();
6029
		}
6030
6031
		if ( ! Nonce_Handler::add( $timestamp, $nonce ) ) {
6032
			// De-nonce the nonce, at least for 5 minutes.
6033
			// 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)
6034
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6035
			if ( $old_nonce_time < time() - 300 ) {
6036
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
6037
			}
6038
		}
6039
6040
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6041
		$data_filters = array(
6042
			'state'        => 'opaque',
6043
			'client_id'    => 'int',
6044
			'client_title' => 'string',
6045
			'client_image' => 'url',
6046
		);
6047
6048
		foreach ( $data_filters as $key => $sanitation ) {
6049
			if ( ! isset( $data->$key ) ) {
6050
				wp_die( $die_error );
6051
			}
6052
6053
			switch ( $sanitation ) {
6054
				case 'int':
6055
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6056
					break;
6057
				case 'opaque':
6058
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6059
					break;
6060
				case 'string':
6061
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6062
					break;
6063
				case 'url':
6064
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6065
					break;
6066
			}
6067
		}
6068
6069
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6070
			wp_die( $die_error );
6071
		}
6072
	}
6073
6074
	function login_message_json_api_authorization( $message ) {
6075
		return '<p class="message">' . sprintf(
6076
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6077
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6078
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6079
	}
6080
6081
	/**
6082
	 * Get $content_width, but with a <s>twist</s> filter.
6083
	 */
6084
	public static function get_content_width() {
6085
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6086
			? $GLOBALS['content_width']
6087
			: false;
6088
		/**
6089
		 * Filter the Content Width value.
6090
		 *
6091
		 * @since 2.2.3
6092
		 *
6093
		 * @param string $content_width Content Width value.
6094
		 */
6095
		return apply_filters( 'jetpack_content_width', $content_width );
6096
	}
6097
6098
	/**
6099
	 * Pings the WordPress.com Mirror Site for the specified options.
6100
	 *
6101
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6102
	 *
6103
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6104
	 */
6105
	public function get_cloud_site_options( $option_names ) {
6106
		$option_names = array_filter( (array) $option_names, 'is_string' );
6107
6108
		$xml = new Jetpack_IXR_Client();
6109
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6110
		if ( $xml->isError() ) {
6111
			return array(
6112
				'error_code' => $xml->getErrorCode(),
6113
				'error_msg'  => $xml->getErrorMessage(),
6114
			);
6115
		}
6116
		$cloud_site_options = $xml->getResponse();
6117
6118
		return $cloud_site_options;
6119
	}
6120
6121
	/**
6122
	 * Checks if the site is currently in an identity crisis.
6123
	 *
6124
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6125
	 */
6126
	public static function check_identity_crisis() {
6127
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6128
			return false;
6129
		}
6130
6131
		return Jetpack_Options::get_option( 'sync_error_idc' );
6132
	}
6133
6134
	/**
6135
	 * Checks whether the home and siteurl specifically are allowed.
6136
	 * Written so that we don't have re-check $key and $value params every time
6137
	 * we want to check if this site is allowed, for example in footer.php
6138
	 *
6139
	 * @since  3.8.0
6140
	 * @return bool True = already allowed False = not on the allowed list.
6141
	 */
6142
	public static function is_staging_site() {
6143
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6144
		return ( new Status() )->is_staging_site();
6145
	}
6146
6147
	/**
6148
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6149
	 *
6150
	 * @since 4.4.0
6151
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6152
	 *
6153
	 * @return bool
6154
	 */
6155
	public static function validate_sync_error_idc_option() {
6156
		$is_valid = false;
6157
6158
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6159
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6160
		if ( $sync_error && self::sync_idc_optin() ) {
6161
			$local_options = self::get_sync_error_idc_option();
6162
			// Ensure all values are set.
6163
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6164
6165
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6166
				if (
6167
						isset( $sync_error['wpcom_home'] ) &&
6168
						isset( $sync_error['wpcom_siteurl'] ) &&
6169
						$sync_error['wpcom_home'] === $local_options['home'] &&
6170
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6171
				) {
6172
					$is_valid = false;
6173
					// Enable migrate_for_idc so that sync actions are accepted.
6174
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6175
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6176
					$is_valid = true;
6177
				}
6178
			}
6179
		}
6180
6181
		/**
6182
		 * Filters whether the sync_error_idc option is valid.
6183
		 *
6184
		 * @since 4.4.0
6185
		 *
6186
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6187
		 */
6188
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6189
6190
		if ( ! $is_valid && $sync_error ) {
6191
			// Since the option exists, and did not validate, delete it
6192
			Jetpack_Options::delete_option( 'sync_error_idc' );
6193
		}
6194
6195
		return $is_valid;
6196
	}
6197
6198
	/**
6199
	 * Normalizes a url by doing three things:
6200
	 *  - Strips protocol
6201
	 *  - Strips www
6202
	 *  - Adds a trailing slash
6203
	 *
6204
	 * @since 4.4.0
6205
	 * @param string $url
6206
	 * @return WP_Error|string
6207
	 */
6208
	public static function normalize_url_protocol_agnostic( $url ) {
6209
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6210 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6211
			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...
6212
		}
6213
6214
		// Strip www and protocols
6215
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6216
		return $url;
6217
	}
6218
6219
	/**
6220
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6221
	 *
6222
	 * @since 4.4.0
6223
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6224
	 *
6225
	 * @param array $response
6226
	 * @return array Array of the local urls, wpcom urls, and error code
6227
	 */
6228
	public static function get_sync_error_idc_option( $response = array() ) {
6229
		// Since the local options will hit the database directly, store the values
6230
		// in a transient to allow for autoloading and caching on subsequent views.
6231
		$local_options = get_transient( 'jetpack_idc_local' );
6232
		if ( false === $local_options ) {
6233
			$local_options = array(
6234
				'home'    => Functions::home_url(),
6235
				'siteurl' => Functions::site_url(),
6236
			);
6237
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6238
		}
6239
6240
		$options = array_merge( $local_options, $response );
6241
6242
		$returned_values = array();
6243
		foreach ( $options as $key => $option ) {
6244
			if ( 'error_code' === $key ) {
6245
				$returned_values[ $key ] = $option;
6246
				continue;
6247
			}
6248
6249
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6250
				continue;
6251
			}
6252
6253
			$returned_values[ $key ] = $normalized_url;
6254
		}
6255
6256
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6257
6258
		return $returned_values;
6259
	}
6260
6261
	/**
6262
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6263
	 * If set to true, the site will be put into staging mode.
6264
	 *
6265
	 * @since 4.3.2
6266
	 * @return bool
6267
	 */
6268
	public static function sync_idc_optin() {
6269
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6270
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6271
		} else {
6272
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6273
		}
6274
6275
		/**
6276
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6277
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6278
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6279
		 *
6280
		 * @since 4.3.2
6281
		 *
6282
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6283
		 */
6284
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6285
	}
6286
6287
	/**
6288
	 * Maybe Use a .min.css stylesheet, maybe not.
6289
	 *
6290
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6291
	 */
6292
	public static function maybe_min_asset( $url, $path, $plugin ) {
6293
		// Short out on things trying to find actual paths.
6294
		if ( ! $path || empty( $plugin ) ) {
6295
			return $url;
6296
		}
6297
6298
		$path = ltrim( $path, '/' );
6299
6300
		// Strip out the abspath.
6301
		$base = dirname( plugin_basename( $plugin ) );
6302
6303
		// Short out on non-Jetpack assets.
6304
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6305
			return $url;
6306
		}
6307
6308
		// File name parsing.
6309
		$file              = "{$base}/{$path}";
6310
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6311
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6312
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6313
		$extension         = array_shift( $file_name_parts_r );
6314
6315
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6316
			// Already pointing at the minified version.
6317
			if ( 'min' === $file_name_parts_r[0] ) {
6318
				return $url;
6319
			}
6320
6321
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6322
			if ( file_exists( $min_full_path ) ) {
6323
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6324
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6325
				if ( 'css' === $extension ) {
6326
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6327
					self::$min_assets[ $key ] = $path;
6328
				}
6329
			}
6330
		}
6331
6332
		return $url;
6333
	}
6334
6335
	/**
6336
	 * If the asset is minified, let's flag .min as the suffix.
6337
	 *
6338
	 * Attached to `style_loader_src` filter.
6339
	 *
6340
	 * @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...
6341
	 * @param string $handle The registered handle of the script in question.
6342
	 * @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...
6343
	 */
6344
	public static function set_suffix_on_min( $src, $handle ) {
6345
		if ( false === strpos( $src, '.min.css' ) ) {
6346
			return $src;
6347
		}
6348
6349
		if ( ! empty( self::$min_assets ) ) {
6350
			foreach ( self::$min_assets as $file => $path ) {
6351
				if ( false !== strpos( $src, $file ) ) {
6352
					wp_style_add_data( $handle, 'suffix', '.min' );
6353
					return $src;
6354
				}
6355
			}
6356
		}
6357
6358
		return $src;
6359
	}
6360
6361
	/**
6362
	 * Maybe inlines a stylesheet.
6363
	 *
6364
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6365
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6366
	 *
6367
	 * Attached to `style_loader_tag` filter.
6368
	 *
6369
	 * @param string $tag The tag that would link to the external asset.
6370
	 * @param string $handle The registered handle of the script in question.
6371
	 *
6372
	 * @return string
6373
	 */
6374
	public static function maybe_inline_style( $tag, $handle ) {
6375
		global $wp_styles;
6376
		$item = $wp_styles->registered[ $handle ];
6377
6378
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6379
			return $tag;
6380
		}
6381
6382
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6383
			$href = $matches[1];
6384
			// Strip off query string
6385
			if ( $pos = strpos( $href, '?' ) ) {
6386
				$href = substr( $href, 0, $pos );
6387
			}
6388
			// Strip off fragment
6389
			if ( $pos = strpos( $href, '#' ) ) {
6390
				$href = substr( $href, 0, $pos );
6391
			}
6392
		} else {
6393
			return $tag;
6394
		}
6395
6396
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6397
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6398
			return $tag;
6399
		}
6400
6401
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6402
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6403
			// And this isn't the pass that actually deals with the RTL version...
6404
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6405
				// Short out, as the RTL version will deal with it in a moment.
6406
				return $tag;
6407
			}
6408
		}
6409
6410
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6411
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6412
		if ( $css ) {
6413
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6414
			if ( empty( $item->extra['after'] ) ) {
6415
				wp_add_inline_style( $handle, $css );
6416
			} else {
6417
				array_unshift( $item->extra['after'], $css );
6418
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6419
			}
6420
		}
6421
6422
		return $tag;
6423
	}
6424
6425
	/**
6426
	 * Loads a view file from the views
6427
	 *
6428
	 * Data passed in with the $data parameter will be available in the
6429
	 * template file as $data['value']
6430
	 *
6431
	 * @param string $template - Template file to load
6432
	 * @param array  $data - Any data to pass along to the template
6433
	 * @return boolean - If template file was found
6434
	 **/
6435
	public function load_view( $template, $data = array() ) {
6436
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6437
6438
		if ( file_exists( $views_dir . $template ) ) {
6439
			require_once $views_dir . $template;
6440
			return true;
6441
		}
6442
6443
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6444
		return false;
6445
	}
6446
6447
	/**
6448
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6449
	 *
6450
	 * @todo Convert these to use apply_filters_deprecated and do_action_deprecated and remove custom code.
6451
	 */
6452
	public function deprecated_hooks() {
6453
		global $wp_filter;
6454
6455
		/*
6456
		 * Format:
6457
		 * deprecated_filter_name => replacement_name
6458
		 *
6459
		 * If there is no replacement, use null for replacement_name
6460
		 */
6461
		$deprecated_list = array(
6462
			'jetpack_bail_on_shortcode'                    => 'jetpack_shortcodes_to_include',
6463
			'wpl_sharing_2014_1'                           => null,
6464
			'jetpack-tools-to-include'                     => 'jetpack_tools_to_include',
6465
			'jetpack_identity_crisis_options_to_check'     => null,
6466
			'update_option_jetpack_single_user_site'       => null,
6467
			'audio_player_default_colors'                  => null,
6468
			'add_option_jetpack_featured_images_enabled'   => null,
6469
			'add_option_jetpack_update_details'            => null,
6470
			'add_option_jetpack_updates'                   => null,
6471
			'add_option_jetpack_network_name'              => null,
6472
			'add_option_jetpack_network_allow_new_registrations' => null,
6473
			'add_option_jetpack_network_add_new_users'     => null,
6474
			'add_option_jetpack_network_site_upload_space' => null,
6475
			'add_option_jetpack_network_upload_file_types' => null,
6476
			'add_option_jetpack_network_enable_administration_menus' => null,
6477
			'add_option_jetpack_is_multi_site'             => null,
6478
			'add_option_jetpack_is_main_network'           => null,
6479
			'add_option_jetpack_main_network_site'         => null,
6480
			'jetpack_sync_all_registered_options'          => null,
6481
			'jetpack_has_identity_crisis'                  => 'jetpack_sync_error_idc_validation',
6482
			'jetpack_is_post_mailable'                     => null,
6483
			'jetpack_seo_site_host'                        => null,
6484
			'jetpack_installed_plugin'                     => 'jetpack_plugin_installed',
6485
			'jetpack_holiday_snow_option_name'             => null,
6486
			'jetpack_holiday_chance_of_snow'               => null,
6487
			'jetpack_holiday_snow_js_url'                  => null,
6488
			'jetpack_is_holiday_snow_season'               => null,
6489
			'jetpack_holiday_snow_option_updated'          => null,
6490
			'jetpack_holiday_snowing'                      => null,
6491
			'jetpack_sso_auth_cookie_expirtation'          => 'jetpack_sso_auth_cookie_expiration',
6492
			'jetpack_cache_plans'                          => null,
6493
			'jetpack_updated_theme'                        => 'jetpack_updated_themes',
6494
			'jetpack_lazy_images_skip_image_with_atttributes' => 'jetpack_lazy_images_skip_image_with_attributes',
6495
			'jetpack_enable_site_verification'             => null,
6496
			// Removed in Jetpack 7.3.0
6497
			'jetpack_widget_authors_exclude'               => 'jetpack_widget_authors_params',
6498
			// Removed in Jetpack 7.9.0
6499
			'jetpack_pwa_manifest'                         => null,
6500
			'jetpack_pwa_background_color'                 => null,
6501
			// Removed in Jetpack 8.3.0.
6502
			'jetpack_check_mobile'                         => null,
6503
			'jetpack_mobile_stylesheet'                    => null,
6504
			'jetpack_mobile_template'                      => null,
6505
			'mobile_reject_mobile'                         => null,
6506
			'mobile_force_mobile'                          => null,
6507
			'mobile_app_promo_download'                    => null,
6508
			'mobile_setup'                                 => null,
6509
			'jetpack_mobile_footer_before'                 => null,
6510
			'wp_mobile_theme_footer'                       => null,
6511
			'minileven_credits'                            => null,
6512
			'jetpack_mobile_header_before'                 => null,
6513
			'jetpack_mobile_header_after'                  => null,
6514
			'jetpack_mobile_theme_menu'                    => null,
6515
			'minileven_show_featured_images'               => null,
6516
			'minileven_attachment_size'                    => null,
6517
		);
6518
6519
		// This is a silly loop depth. Better way?
6520
		foreach ( $deprecated_list as $hook => $hook_alt ) {
6521
			if ( has_action( $hook ) ) {
6522
				foreach ( $wp_filter[ $hook ] as $func => $values ) {
6523
					foreach ( $values as $hooked ) {
6524
						if ( is_callable( $hooked['function'] ) ) {
6525
							$function_name = $hooked['function'];
6526
						} else {
6527
							$function_name = 'an anonymous function';
6528
						}
6529
						_deprecated_function( $hook . ' used for ' . $function_name, null, $hook_alt );
6530
					}
6531
				}
6532
			}
6533
		}
6534
6535
		$filter_deprecated_list = array(
6536
			'can_display_jetpack_manage_notice' => array(
6537
				'replacement' => null,
6538
				'version'     => 'jetpack-7.3.0',
6539
			),
6540
			'atd_http_post_timeout'             => array(
6541
				'replacement' => null,
6542
				'version'     => 'jetpack-7.3.0',
6543
			),
6544
			'atd_service_domain'                => array(
6545
				'replacement' => null,
6546
				'version'     => 'jetpack-7.3.0',
6547
			),
6548
			'atd_load_scripts'                  => array(
6549
				'replacement' => null,
6550
				'version'     => 'jetpack-7.3.0',
6551
			),
6552
		);
6553
6554
		foreach ( $filter_deprecated_list as $tag => $args ) {
6555
			if ( has_filter( $tag ) ) {
6556
				apply_filters_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6557
			}
6558
		}
6559
6560
		$action_deprecated_list = array(
6561
			'atd_http_post_error' => array(
6562
				'replacement' => null,
6563
				'version'     => 'jetpack-7.3.0',
6564
			),
6565
		);
6566
6567
		foreach ( $action_deprecated_list as $tag => $args ) {
6568
			if ( has_action( $tag ) ) {
6569
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6570
			}
6571
		}
6572
	}
6573
6574
	/**
6575
	 * Converts any url in a stylesheet, to the correct absolute url.
6576
	 *
6577
	 * Considerations:
6578
	 *  - Normal, relative URLs     `feh.png`
6579
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6580
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6581
	 *  - Absolute URLs             `http://domain.com/feh.png`
6582
	 *  - Domain root relative URLs `/feh.png`
6583
	 *
6584
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6585
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6586
	 *
6587
	 * @return mixed|string
6588
	 */
6589
	public static function absolutize_css_urls( $css, $css_file_url ) {
6590
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6591
		$css_dir = dirname( $css_file_url );
6592
		$p       = wp_parse_url( $css_dir );
6593
		$domain  = sprintf(
6594
			'%1$s//%2$s%3$s%4$s',
6595
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6596
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6597
			$p['host'],
6598
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6599
		);
6600
6601
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6602
			$find = $replace = array();
6603
			foreach ( $matches as $match ) {
6604
				$url = trim( $match['path'], "'\" \t" );
6605
6606
				// If this is a data url, we don't want to mess with it.
6607
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6608
					continue;
6609
				}
6610
6611
				// If this is an absolute or protocol-agnostic url,
6612
				// we don't want to mess with it.
6613
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6614
					continue;
6615
				}
6616
6617
				switch ( substr( $url, 0, 1 ) ) {
6618
					case '/':
6619
						$absolute = $domain . $url;
6620
						break;
6621
					default:
6622
						$absolute = $css_dir . '/' . $url;
6623
				}
6624
6625
				$find[]    = $match[0];
6626
				$replace[] = sprintf( 'url("%s")', $absolute );
6627
			}
6628
			$css = str_replace( $find, $replace, $css );
6629
		}
6630
6631
		return $css;
6632
	}
6633
6634
	/**
6635
	 * This methods removes all of the registered css files on the front end
6636
	 * from Jetpack in favor of using a single file. In effect "imploding"
6637
	 * all the files into one file.
6638
	 *
6639
	 * Pros:
6640
	 * - Uses only ONE css asset connection instead of 15
6641
	 * - Saves a minimum of 56k
6642
	 * - Reduces server load
6643
	 * - Reduces time to first painted byte
6644
	 *
6645
	 * Cons:
6646
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6647
	 *      should not cause any issues with themes.
6648
	 * - Plugins/themes dequeuing styles no longer do anything. See
6649
	 *      jetpack_implode_frontend_css filter for a workaround
6650
	 *
6651
	 * For some situations developers may wish to disable css imploding and
6652
	 * instead operate in legacy mode where each file loads seperately and
6653
	 * can be edited individually or dequeued. This can be accomplished with
6654
	 * the following line:
6655
	 *
6656
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6657
	 *
6658
	 * @since 3.2
6659
	 **/
6660
	public function implode_frontend_css( $travis_test = false ) {
6661
		$do_implode = true;
6662
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6663
			$do_implode = false;
6664
		}
6665
6666
		// Do not implode CSS when the page loads via the AMP plugin.
6667
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6668
			$do_implode = false;
6669
		}
6670
6671
		/**
6672
		 * Allow CSS to be concatenated into a single jetpack.css file.
6673
		 *
6674
		 * @since 3.2.0
6675
		 *
6676
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6677
		 */
6678
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6679
6680
		// Do not use the imploded file when default behavior was altered through the filter
6681
		if ( ! $do_implode ) {
6682
			return;
6683
		}
6684
6685
		// We do not want to use the imploded file in dev mode, or if not connected
6686
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6687
			if ( ! $travis_test ) {
6688
				return;
6689
			}
6690
		}
6691
6692
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6693
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6694
			return;
6695
		}
6696
6697
		/*
6698
		 * Now we assume Jetpack is connected and able to serve the single
6699
		 * file.
6700
		 *
6701
		 * In the future there will be a check here to serve the file locally
6702
		 * or potentially from the Jetpack CDN
6703
		 *
6704
		 * For now:
6705
		 * - Enqueue a single imploded css file
6706
		 * - Zero out the style_loader_tag for the bundled ones
6707
		 * - Be happy, drink scotch
6708
		 */
6709
6710
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6711
6712
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6713
6714
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6715
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6716
	}
6717
6718
	function concat_remove_style_loader_tag( $tag, $handle ) {
6719
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6720
			$tag = '';
6721
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6722
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6723
			}
6724
		}
6725
6726
		return $tag;
6727
	}
6728
6729
	/**
6730
	 * @deprecated
6731
	 * @see Automattic\Jetpack\Assets\add_aync_script
6732
	 */
6733
	public function script_add_async( $tag, $handle, $src ) {
6734
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6735
	}
6736
6737
	/*
6738
	 * Check the heartbeat data
6739
	 *
6740
	 * Organizes the heartbeat data by severity.  For example, if the site
6741
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6742
	 *
6743
	 * Data will be added to "caution" array, if it either:
6744
	 *  - Out of date Jetpack version
6745
	 *  - Out of date WP version
6746
	 *  - Out of date PHP version
6747
	 *
6748
	 * $return array $filtered_data
6749
	 */
6750
	public static function jetpack_check_heartbeat_data() {
6751
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6752
6753
		$good    = array();
6754
		$caution = array();
6755
		$bad     = array();
6756
6757
		foreach ( $raw_data as $stat => $value ) {
6758
6759
			// Check jetpack version
6760
			if ( 'version' == $stat ) {
6761
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6762
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6763
					continue;
6764
				}
6765
			}
6766
6767
			// Check WP version
6768
			if ( 'wp-version' == $stat ) {
6769
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6770
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6771
					continue;
6772
				}
6773
			}
6774
6775
			// Check PHP version
6776
			if ( 'php-version' == $stat ) {
6777
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6778
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6779
					continue;
6780
				}
6781
			}
6782
6783
			// Check ID crisis
6784
			if ( 'identitycrisis' == $stat ) {
6785
				if ( 'yes' == $value ) {
6786
					$bad[ $stat ] = $value;
6787
					continue;
6788
				}
6789
			}
6790
6791
			// The rest are good :)
6792
			$good[ $stat ] = $value;
6793
		}
6794
6795
		$filtered_data = array(
6796
			'good'    => $good,
6797
			'caution' => $caution,
6798
			'bad'     => $bad,
6799
		);
6800
6801
		return $filtered_data;
6802
	}
6803
6804
6805
	/*
6806
	 * This method is used to organize all options that can be reset
6807
	 * without disconnecting Jetpack.
6808
	 *
6809
	 * It is used in class.jetpack-cli.php to reset options
6810
	 *
6811
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6812
	 *
6813
	 * @return array of options to delete.
6814
	 */
6815
	public static function get_jetpack_options_for_reset() {
6816
		return Jetpack_Options::get_options_for_reset();
6817
	}
6818
6819
	/*
6820
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6821
	 * so we can bring them directly to their site in calypso.
6822
	 *
6823
	 * @param string | url
6824
	 * @return string | url without the guff
6825
	 */
6826 View Code Duplication
	public static function build_raw_urls( $url ) {
6827
		$strip_http = '/.*?:\/\//i';
6828
		$url        = preg_replace( $strip_http, '', $url );
6829
		$url        = str_replace( '/', '::', $url );
6830
		return $url;
6831
	}
6832
6833
	/**
6834
	 * Stores and prints out domains to prefetch for page speed optimization.
6835
	 *
6836
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6837
	 *
6838
	 * @param string|array $urls URLs to hint.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $urls not be string|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...
6839
	 */
6840
	public static function dns_prefetch( $urls = null ) {
6841
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6842
		if ( $urls ) {
6843
			Assets::add_resource_hint( $urls );
6844
		}
6845
	}
6846
6847
	public function wp_dashboard_setup() {
6848
		if ( self::is_active() ) {
6849
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6850
		}
6851
6852
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6853
			$jetpack_logo = new Jetpack_Logo();
6854
			$widget_title = sprintf(
6855
				wp_kses(
6856
					/* translators: Placeholder is a Jetpack logo. */
6857
					__( 'Stats <span>by %s</span>', 'jetpack' ),
6858
					array( 'span' => array() )
6859
				),
6860
				$jetpack_logo->get_jp_emblem( true )
6861
			);
6862
6863
			wp_add_dashboard_widget(
6864
				'jetpack_summary_widget',
6865
				$widget_title,
6866
				array( __CLASS__, 'dashboard_widget' )
6867
			);
6868
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6869
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6870
6871
			// If we're inactive and not in offline mode, sort our box to the top.
6872
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6873
				global $wp_meta_boxes;
6874
6875
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6876
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6877
6878
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6879
			}
6880
		}
6881
	}
6882
6883
	/**
6884
	 * @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...
6885
	 * @return mixed
6886
	 */
6887
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6888
		if ( ! is_array( $sorted ) ) {
6889
			return $sorted;
6890
		}
6891
6892
		foreach ( $sorted as $box_context => $ids ) {
6893
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6894
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6895
				continue;
6896
			}
6897
6898
			$ids_array = explode( ',', $ids );
6899
			$key       = array_search( 'dashboard_stats', $ids_array );
6900
6901
			if ( false !== $key ) {
6902
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6903
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6904
				$sorted[ $box_context ] = implode( ',', $ids_array );
6905
				// We've found it, stop searching, and just return.
6906
				break;
6907
			}
6908
		}
6909
6910
		return $sorted;
6911
	}
6912
6913
	public static function dashboard_widget() {
6914
		/**
6915
		 * Fires when the dashboard is loaded.
6916
		 *
6917
		 * @since 3.4.0
6918
		 */
6919
		do_action( 'jetpack_dashboard_widget' );
6920
	}
6921
6922
	public static function dashboard_widget_footer() {
6923
		?>
6924
		<footer>
6925
6926
		<div class="protect">
6927
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
6928
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
6929
				<p class="blocked-count">
6930
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
6931
				</p>
6932
				<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>
6933
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
6934
				<a href="
6935
				<?php
6936
				echo esc_url(
6937
					wp_nonce_url(
6938
						self::admin_url(
6939
							array(
6940
								'action' => 'activate',
6941
								'module' => 'protect',
6942
							)
6943
						),
6944
						'jetpack_activate-protect'
6945
					)
6946
				);
6947
				?>
6948
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
6949
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
6950
				</a>
6951
			<?php else : ?>
6952
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
6953
			<?php endif; ?>
6954
		</div>
6955
6956
		<div class="akismet">
6957
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
6958
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
6959
				<p class="blocked-count">
6960
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
6961
				</p>
6962
				<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>
6963
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
6964
				<a href="
6965
				<?php
6966
				echo esc_url(
6967
					wp_nonce_url(
6968
						add_query_arg(
6969
							array(
6970
								'action' => 'activate',
6971
								'plugin' => 'akismet/akismet.php',
6972
							),
6973
							admin_url( 'plugins.php' )
6974
						),
6975
						'activate-plugin_akismet/akismet.php'
6976
					)
6977
				);
6978
				?>
6979
							" class="button button-jetpack">
6980
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
6981
				</a>
6982
			<?php else : ?>
6983
				<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>
6984
			<?php endif; ?>
6985
		</div>
6986
6987
		</footer>
6988
		<?php
6989
	}
6990
6991
	/*
6992
	 * Adds a "blank" column in the user admin table to display indication of user connection.
6993
	 */
6994
	function jetpack_icon_user_connected( $columns ) {
6995
		$columns['user_jetpack'] = '';
6996
		return $columns;
6997
	}
6998
6999
	/*
7000
	 * Show Jetpack icon if the user is linked.
7001
	 */
7002
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7003
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7004
			$jetpack_logo = new Jetpack_Logo();
7005
			$emblem_html  = sprintf(
7006
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7007
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7008
				$jetpack_logo->get_jp_emblem()
7009
			);
7010
			return $emblem_html;
7011
		}
7012
7013
		return $val;
7014
	}
7015
7016
	/*
7017
	 * Style the Jetpack user column
7018
	 */
7019
	function jetpack_user_col_style() {
7020
		global $current_screen;
7021
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7022
			?>
7023
			<style>
7024
				.fixed .column-user_jetpack {
7025
					width: 21px;
7026
				}
7027
				.jp-emblem-user-admin svg {
7028
					width: 20px;
7029
					height: 20px;
7030
				}
7031
				.jp-emblem-user-admin path {
7032
					fill: #00BE28;
7033
				}
7034
			</style>
7035
			<?php
7036
		}
7037
	}
7038
7039
	/**
7040
	 * Checks if Akismet is active and working.
7041
	 *
7042
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7043
	 * that implied usage of methods present since more recent version.
7044
	 * See https://github.com/Automattic/jetpack/pull/9585
7045
	 *
7046
	 * @since  5.1.0
7047
	 *
7048
	 * @return bool True = Akismet available. False = Aksimet not available.
7049
	 */
7050
	public static function is_akismet_active() {
7051
		static $status = null;
7052
7053
		if ( ! is_null( $status ) ) {
7054
			return $status;
7055
		}
7056
7057
		// Check if a modern version of Akismet is active.
7058
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7059
			$status = false;
7060
			return $status;
7061
		}
7062
7063
		// Make sure there is a key known to Akismet at all before verifying key.
7064
		$akismet_key = Akismet::get_api_key();
7065
		if ( ! $akismet_key ) {
7066
			$status = false;
7067
			return $status;
7068
		}
7069
7070
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7071
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7072
7073
		// 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.
7074
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7075
		// We cache the result of the Akismet key verification for ten minutes.
7076
		if ( ! $akismet_key_state || $recheck ) {
7077
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7078
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7079
		}
7080
7081
		$status = 'valid' === $akismet_key_state;
7082
7083
		return $status;
7084
	}
7085
7086
	/**
7087
	 * @deprecated
7088
	 *
7089
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7090
	 */
7091
	public static function is_function_in_backtrace() {
7092
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7093
	}
7094
7095
	/**
7096
	 * Given a minified path, and a non-minified path, will return
7097
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7098
	 *
7099
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7100
	 * root Jetpack directory.
7101
	 *
7102
	 * @since 5.6.0
7103
	 *
7104
	 * @param string $min_path
7105
	 * @param string $non_min_path
7106
	 * @return string The URL to the file
7107
	 */
7108
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7109
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7110
	}
7111
7112
	/**
7113
	 * Checks for whether Jetpack Backup is enabled.
7114
	 * Will return true if the state of Backup is anything except "unavailable".
7115
	 *
7116
	 * @return bool|int|mixed
7117
	 */
7118
	public static function is_rewind_enabled() {
7119
		if ( ! self::is_active() ) {
7120
			return false;
7121
		}
7122
7123
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7124
		if ( false === $rewind_enabled ) {
7125
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7126
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7127
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7128
				&& ! empty( $rewind_data['state'] )
7129
				&& 'active' === $rewind_data['state'] )
7130
				? 1
7131
				: 0;
7132
7133
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7134
		}
7135
		return $rewind_enabled;
7136
	}
7137
7138
	/**
7139
	 * Return Calypso environment value; used for developing Jetpack and pairing
7140
	 * it with different Calypso enrionments, such as localhost.
7141
	 *
7142
	 * @since 7.4.0
7143
	 *
7144
	 * @return string Calypso environment
7145
	 */
7146
	public static function get_calypso_env() {
7147
		if ( isset( $_GET['calypso_env'] ) ) {
7148
			return sanitize_key( $_GET['calypso_env'] );
7149
		}
7150
7151
		if ( getenv( 'CALYPSO_ENV' ) ) {
7152
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7153
		}
7154
7155
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7156
			return sanitize_key( CALYPSO_ENV );
7157
		}
7158
7159
		return '';
7160
	}
7161
7162
	/**
7163
	 * Returns the hostname with protocol for Calypso.
7164
	 * Used for developing Jetpack with Calypso.
7165
	 *
7166
	 * @since 8.4.0
7167
	 *
7168
	 * @return string Calypso host.
7169
	 */
7170
	public static function get_calypso_host() {
7171
		$calypso_env = self::get_calypso_env();
7172
		switch ( $calypso_env ) {
7173
			case 'development':
7174
				return 'http://calypso.localhost:3000/';
7175
			case 'wpcalypso':
7176
				return 'https://wpcalypso.wordpress.com/';
7177
			case 'horizon':
7178
				return 'https://horizon.wordpress.com/';
7179
			default:
7180
				return 'https://wordpress.com/';
7181
		}
7182
	}
7183
7184
	/**
7185
	 * Handles activating default modules as well general cleanup for the new connection.
7186
	 *
7187
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7188
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7189
	 * @param boolean $send_state_messages          Whether to send state messages.
7190
	 * @return void
7191
	 */
7192
	public static function handle_post_authorization_actions(
7193
		$activate_sso = false,
7194
		$redirect_on_activation_error = false,
7195
		$send_state_messages = true
7196
	) {
7197
		$other_modules = $activate_sso
7198
			? array( 'sso' )
7199
			: array();
7200
7201
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7202
			self::delete_active_modules();
7203
7204
			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...
7205
		} else {
7206
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7207
		}
7208
7209
		// Since this is a fresh connection, be sure to clear out IDC options
7210
		Jetpack_IDC::clear_all_idc_options();
7211
7212
		if ( $send_state_messages ) {
7213
			self::state( 'message', 'authorized' );
7214
		}
7215
	}
7216
7217
	/**
7218
	 * Returns a boolean for whether backups UI should be displayed or not.
7219
	 *
7220
	 * @return bool Should backups UI be displayed?
7221
	 */
7222
	public static function show_backups_ui() {
7223
		/**
7224
		 * Whether UI for backups should be displayed.
7225
		 *
7226
		 * @since 6.5.0
7227
		 *
7228
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7229
		 */
7230
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7231
	}
7232
7233
	/*
7234
	 * Deprecated manage functions
7235
	 */
7236
	function prepare_manage_jetpack_notice() {
7237
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7238
	}
7239
	function manage_activate_screen() {
7240
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7241
	}
7242
	function admin_jetpack_manage_notice() {
7243
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7244
	}
7245
	function opt_out_jetpack_manage_url() {
7246
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7247
	}
7248
	function opt_in_jetpack_manage_url() {
7249
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7250
	}
7251
	function opt_in_jetpack_manage_notice() {
7252
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7253
	}
7254
	function can_display_jetpack_manage_notice() {
7255
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7256
	}
7257
7258
	/**
7259
	 * Clean leftoveruser meta.
7260
	 *
7261
	 * Delete Jetpack-related user meta when it is no longer needed.
7262
	 *
7263
	 * @since 7.3.0
7264
	 *
7265
	 * @param int $user_id User ID being updated.
7266
	 */
7267
	public static function user_meta_cleanup( $user_id ) {
7268
		$meta_keys = array(
7269
			// AtD removed from Jetpack 7.3
7270
			'AtD_options',
7271
			'AtD_check_when',
7272
			'AtD_guess_lang',
7273
			'AtD_ignored_phrases',
7274
		);
7275
7276
		foreach ( $meta_keys as $meta_key ) {
7277
			if ( get_user_meta( $user_id, $meta_key ) ) {
7278
				delete_user_meta( $user_id, $meta_key );
7279
			}
7280
		}
7281
	}
7282
7283
	/**
7284
	 * Checks if a Jetpack site is both active and not in offline mode.
7285
	 *
7286
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7287
	 *
7288
	 * @deprecated 8.8.0
7289
	 *
7290
	 * @return bool True if Jetpack is active and not in offline mode.
7291
	 */
7292
	public static function is_active_and_not_development_mode() {
7293
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7294
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7295
			return false;
7296
		}
7297
		return true;
7298
	}
7299
7300
	/**
7301
	 * Checks if a Jetpack site is both active and not in offline mode.
7302
	 *
7303
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7304
	 *
7305
	 * @since 8.8.0
7306
	 *
7307
	 * @return bool True if Jetpack is active and not in offline mode.
7308
	 */
7309
	public static function is_active_and_not_offline_mode() {
7310
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7311
			return false;
7312
		}
7313
		return true;
7314
	}
7315
7316
	/**
7317
	 * Returns the list of products that we have available for purchase.
7318
	 */
7319
	public static function get_products_for_purchase() {
7320
		$products = array();
7321
		if ( ! is_multisite() ) {
7322
			$products[] = array(
7323
				'key'               => 'backup',
7324
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7325
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7326
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7327
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7328
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7329
				'options'           => array(
7330
					array(
7331
						'type'        => 'daily',
7332
						'slug'        => 'jetpack-backup-daily',
7333
						'key'         => 'jetpack_backup_daily',
7334
						'name'        => __( 'Daily Backups', 'jetpack' ),
7335
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7336
					),
7337
					array(
7338
						'type'        => 'realtime',
7339
						'slug'        => 'jetpack-backup-realtime',
7340
						'key'         => 'jetpack_backup_realtime',
7341
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7342
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7343
					),
7344
				),
7345
				'default_option'    => 'realtime',
7346
				'show_promotion'    => true,
7347
				'discount_percent'  => 70,
7348
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7349
			);
7350
7351
			$products[] = array(
7352
				'key'               => 'scan',
7353
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7354
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7355
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7356
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7357
				'show_promotion'    => true,
7358
				'discount_percent'  => 30,
7359
				'options'           => array(
7360
					array(
7361
						'type'      => 'scan',
7362
						'slug'      => 'jetpack-scan',
7363
						'key'       => 'jetpack_scan',
7364
						'name'      => __( 'Daily Scan', 'jetpack' ),
7365
					),
7366
				),
7367
				'default_option'    => 'scan',
7368
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7369
			);
7370
		}
7371
7372
		$products[] = array(
7373
			'key'               => 'search',
7374
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7375
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7376
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7377
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7378
			'label_popup'  		=> __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.' ),
7379
			'options'           => array(
7380
				array(
7381
					'type'      => 'search',
7382
					'slug'      => 'jetpack-search',
7383
					'key'       => 'jetpack_search',
7384
					'name'      => __( 'Search', 'jetpack' ),
7385
				),
7386
			),
7387
			'tears'             => array(),
7388
			'default_option'    => 'search',
7389
			'show_promotion'    => false,
7390
			'included_in_plans' => array( 'search-plan' ),
7391
		);
7392
7393
		$products[] = array(
7394
			'key'               => 'anti-spam',
7395
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7396
			'short_description' => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7397
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7398
			'description'       => __( 'Automatically clear spam from comments and forms. Save time, get more responses, give your visitors a better experience – all without lifting a finger.', 'jetpack' ),
7399
			'options'           => array(
7400
				array(
7401
					'type'      => 'anti-spam',
7402
					'slug'      => 'jetpack-anti-spam',
7403
					'key'       => 'jetpack_anti_spam',
7404
					'name'      => __( 'Anti-Spam', 'jetpack' ),
7405
				),
7406
			),
7407
			'default_option'    => 'anti-spam',
7408
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7409
		);
7410
7411
		return $products;
7412
	}
7413
}
7414