Completed
Push — add/constants ( f4a5bb...bc62ab )
by
unknown
14:54 queued 04:54
created

Jetpack::get_option()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 3
rs 10
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\Plugin_Storage as Connection_Plugin_Storage;
8
use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
9
use Automattic\Jetpack\Connection\Utils as Connection_Utils;
10
use Automattic\Jetpack\Connection\Webhooks as Connection_Webhooks;
11
use Automattic\Jetpack\Constants;
12
use Automattic\Jetpack\Device_Detection\User_Agent_Info;
13
use Automattic\Jetpack\Licensing;
14
use Automattic\Jetpack\Partner;
15
use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
16
use Automattic\Jetpack\Redirect;
17
use Automattic\Jetpack\Roles;
18
use Automattic\Jetpack\Status;
19
use Automattic\Jetpack\Sync\Functions;
20
use Automattic\Jetpack\Sync\Health;
21
use Automattic\Jetpack\Sync\Sender;
22
use Automattic\Jetpack\Sync\Users;
23
use Automattic\Jetpack\Terms_Of_Service;
24
use Automattic\Jetpack\Tracking;
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
		}
512
	}
513
514
	/**
515
	 * Runs upgrade routines that need to have modules loaded.
516
	 */
517
	static function upgrade_on_load() {
518
519
		// Not attempting any upgrades if jetpack_modules_loaded did not fire.
520
		// This can happen in case Jetpack has been just upgraded and is
521
		// being initialized late during the page load. In this case we wait
522
		// until the next proper admin page load with Jetpack active.
523
		if ( ! did_action( 'jetpack_modules_loaded' ) ) {
524
			delete_transient( self::$plugin_upgrade_lock_key );
525
526
			return;
527
		}
528
529
		self::maybe_set_version_option();
530
531
		if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
532
			Jetpack_Widget_Conditions::migrate_post_type_rules();
533
		}
534
535
		if (
536
			class_exists( 'Jetpack_Sitemap_Manager' )
537
			&& version_compare( JETPACK__VERSION, '5.3', '>=' )
538
		) {
539
			do_action( 'jetpack_sitemaps_purge_data' );
540
		}
541
542
		// Delete old stats cache
543
		delete_option( 'jetpack_restapi_stats_cache' );
544
545
		delete_transient( self::$plugin_upgrade_lock_key );
546
	}
547
548
	/**
549
	 * Saves all the currently active modules to options.
550
	 * Also fires Action hooks for each newly activated and deactivated module.
551
	 *
552
	 * @param $modules Array Array of active modules to be saved in options.
553
	 *
554
	 * @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...
555
	 */
556
	static function update_active_modules( $modules ) {
557
		$current_modules      = Jetpack_Options::get_option( 'active_modules', array() );
558
		$active_modules       = self::get_active_modules();
559
		$new_active_modules   = array_diff( $modules, $current_modules );
560
		$new_inactive_modules = array_diff( $active_modules, $modules );
561
		$new_current_modules  = array_diff( array_merge( $current_modules, $new_active_modules ), $new_inactive_modules );
562
		$reindexed_modules    = array_values( $new_current_modules );
563
		$success              = Jetpack_Options::update_option( 'active_modules', array_unique( $reindexed_modules ) );
564
565
		foreach ( $new_active_modules as $module ) {
566
			/**
567
			 * Fires when a specific module is activated.
568
			 *
569
			 * @since 1.9.0
570
			 *
571
			 * @param string $module Module slug.
572
			 * @param boolean $success whether the module was activated. @since 4.2
573
			 */
574
			do_action( 'jetpack_activate_module', $module, $success );
575
			/**
576
			 * Fires when a module is activated.
577
			 * The dynamic part of the filter, $module, is the module slug.
578
			 *
579
			 * @since 1.9.0
580
			 *
581
			 * @param string $module Module slug.
582
			 */
583
			do_action( "jetpack_activate_module_$module", $module );
584
		}
585
586
		foreach ( $new_inactive_modules as $module ) {
587
			/**
588
			 * Fired after a module has been deactivated.
589
			 *
590
			 * @since 4.2.0
591
			 *
592
			 * @param string $module Module slug.
593
			 * @param boolean $success whether the module was deactivated.
594
			 */
595
			do_action( 'jetpack_deactivate_module', $module, $success );
596
			/**
597
			 * Fires when a module is deactivated.
598
			 * The dynamic part of the filter, $module, is the module slug.
599
			 *
600
			 * @since 1.9.0
601
			 *
602
			 * @param string $module Module slug.
603
			 */
604
			do_action( "jetpack_deactivate_module_$module", $module );
605
		}
606
607
		return $success;
608
	}
609
610
	static function delete_active_modules() {
611
		self::update_active_modules( array() );
612
	}
613
614
	/**
615
	 * Adds a hook to plugins_loaded at a priority that's currently the earliest
616
	 * available.
617
	 */
618
	public function add_configure_hook() {
619
		global $wp_filter;
620
621
		$current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
622
		if ( false !== $current_priority ) {
623
			remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
624
		}
625
626
		$taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
627
		sort( $taken_priorities );
628
629
		$first_priority = array_shift( $taken_priorities );
630
631
		if ( defined( 'PHP_INT_MAX' ) && $first_priority <= - PHP_INT_MAX ) {
632
			$new_priority = - PHP_INT_MAX;
633
		} else {
634
			$new_priority = $first_priority - 1;
635
		}
636
637
		add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
638
	}
639
640
	/**
641
	 * Constructor.  Initializes WordPress hooks
642
	 */
643
	private function __construct() {
644
		/*
645
		 * Check for and alert any deprecated hooks
646
		 */
647
		add_action( 'init', array( $this, 'deprecated_hooks' ) );
648
649
		// Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
650
		add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
651
		add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
652
		add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
653
		add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
654
655
		add_action( 'jetpack_verify_signature_error', array( $this, 'track_xmlrpc_error' ) );
656
657
		add_filter(
658
			'jetpack_signature_check_token',
659
			array( __CLASS__, 'verify_onboarding_token' ),
660
			10,
661
			3
662
		);
663
664
		/**
665
		 * Prepare Gutenberg Editor functionality
666
		 */
667
		require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
668
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'init' ) );
669
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_independent_blocks' ) );
670
		add_action( 'plugins_loaded', array( 'Jetpack_Gutenberg', 'load_extended_blocks' ), 9 );
671
		add_action( 'enqueue_block_editor_assets', array( 'Jetpack_Gutenberg', 'enqueue_block_editor_assets' ) );
672
673
		add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
674
675
		// Unlink user before deleting the user from WP.com.
676
		add_action( 'deleted_user', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
677
		add_action( 'remove_user_from_blog', array( 'Automattic\\Jetpack\\Connection\\Manager', 'disconnect_user' ), 10, 1 );
678
679
		add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
680
681
		add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
682
		add_action( 'login_init', array( $this, 'login_init' ) );
683
684
		// Set up the REST authentication hooks.
685
		Connection_Rest_Authentication::init();
686
687
		add_action( 'admin_init', array( $this, 'admin_init' ) );
688
		add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
689
690
		add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
691
692
		add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
693
		// Filter the dashboard meta box order to swap the new one in in place of the old one.
694
		add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
695
696
		// returns HTTPS support status
697
		add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
698
699
		add_action( 'wp_ajax_jetpack_connection_banner', array( $this, 'jetpack_connection_banner_callback' ) );
700
701
		add_action( 'wp_ajax_jetpack_wizard_banner', array( 'Jetpack_Wizard_Banner', 'ajax_callback' ) );
702
703
		add_action( 'wp_loaded', array( $this, 'register_assets' ) );
704
705
		/**
706
		 * These actions run checks to load additional files.
707
		 * They check for external files or plugins, so they need to run as late as possible.
708
		 */
709
		add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
710
		add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
711
		add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
712
		add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
713
714
		add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
715
		add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
716
		add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
717
718
		add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
719
720
		add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
721
		add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
722
723
		// A filter to control all just in time messages
724
		add_filter( 'jetpack_just_in_time_msgs', '__return_true', 9 );
725
726
		add_filter( 'jetpack_just_in_time_msg_cache', '__return_true', 9 );
727
728
		/*
729
		 * If enabled, point edit post, page, and comment links to Calypso instead of WP-Admin.
730
		 * We should make sure to only do this for front end links.
731
		 */
732
		if ( self::get_option( 'edit_links_calypso_redirect' ) && ! is_admin() ) {
733
			add_filter( 'get_edit_post_link', array( $this, 'point_edit_post_links_to_calypso' ), 1, 2 );
734
			add_filter( 'get_edit_comment_link', array( $this, 'point_edit_comment_links_to_calypso' ), 1 );
735
736
			/*
737
			 * We'll shortcircuit wp_notify_postauthor and wp_notify_moderator pluggable functions
738
			 * so they point moderation links on emails to Calypso.
739
			 */
740
			jetpack_require_lib( 'functions.wp-notify' );
741
			add_filter( 'comment_notification_recipients', 'jetpack_notify_postauthor', 1, 2 );
742
			add_filter( 'notify_moderator', 'jetpack_notify_moderator', 1, 2 );
743
		}
744
745
		add_action(
746
			'plugins_loaded',
747
			function () {
748
				if ( User_Agent_Info::is_mobile_app() ) {
749
					add_filter( 'get_edit_post_link', '__return_empty_string' );
750
				}
751
			}
752
		);
753
754
		// Update the site's Jetpack plan and products from API on heartbeats.
755
		add_action( 'jetpack_heartbeat', array( 'Jetpack_Plan', 'refresh_from_wpcom' ) );
756
757
		/**
758
		 * This is the hack to concatenate all css files into one.
759
		 * For description and reasoning see the implode_frontend_css method.
760
		 *
761
		 * Super late priority so we catch all the registered styles.
762
		 */
763
		if ( ! is_admin() ) {
764
			add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
765
			add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
766
		}
767
768
		/**
769
		 * These are sync actions that we need to keep track of for jitms
770
		 */
771
		add_filter( 'jetpack_sync_before_send_updated_option', array( $this, 'jetpack_track_last_sync_callback' ), 99 );
772
773
		// Actually push the stats on shutdown.
774
		if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
775
			add_action( 'shutdown', array( $this, 'push_stats' ) );
776
		}
777
778
		// Actions for Manager::authorize().
779
		add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
780
		add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
781
		add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
782
783
		add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
784
		add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
785
		add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
786
		add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
787
788
		// Filters for the Manager::get_token() urls and request body.
789
		add_filter( 'jetpack_token_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
790
		add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
791
792
		// Actions for successful reconnect.
793
		add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
794
795
		// Actions for licensing.
796
		Licensing::instance()->initialize();
797
798
		// Make resources use static domain when possible.
799
		add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
800
	}
801
802
	/**
803
	 * Before everything else starts getting initalized, we need to initialize Jetpack using the
804
	 * Config object.
805
	 */
806
	public function configure() {
807
		$config = new Config();
808
809
		foreach (
810
			array(
811
				'sync',
812
			)
813
			as $feature
814
		) {
815
			$config->ensure( $feature );
816
		}
817
818
		$config->ensure(
819
			'connection',
820
			array(
821
				'slug' => 'jetpack',
822
				'name' => 'Jetpack',
823
			)
824
		);
825
826
		if ( is_admin() ) {
827
			$config->ensure( 'jitm' );
828
		}
829
830
		if ( ! $this->connection_manager ) {
831
			$this->connection_manager = new Connection_Manager( 'jetpack' );
832
833
			/**
834
			 * Filter to activate Jetpack Connection UI.
835
			 * INTERNAL USE ONLY.
836
			 *
837
			 * @since 9.5.0
838
			 *
839
			 * @param bool false Whether to activate the Connection UI.
840
			 */
841
			if ( apply_filters( 'jetpack_connection_ui_active', false ) ) {
842
				Automattic\Jetpack\ConnectionUI\Admin::init();
843
			}
844
		}
845
846
		/*
847
		 * Load things that should only be in Network Admin.
848
		 *
849
		 * For now blow away everything else until a more full
850
		 * understanding of what is needed at the network level is
851
		 * available
852
		 */
853
		if ( is_multisite() ) {
854
			$network = Jetpack_Network::init();
855
			$network->set_connection( $this->connection_manager );
856
		}
857
858
		if ( $this->connection_manager->is_active() ) {
859
			add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
860
861
			Jetpack_Heartbeat::init();
862
			if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
863
				require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
864
				Jetpack_Search_Performance_Logger::init();
865
			}
866
		}
867
868
		// Initialize remote file upload request handlers.
869
		$this->add_remote_request_handlers();
870
871
		/*
872
		 * Enable enhanced handling of previewing sites in Calypso
873
		 */
874
		if ( self::is_active() ) {
875
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
876
			add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
877
			require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-keyring-service-helper.php';
878
			add_action( 'init', array( 'Jetpack_Keyring_Service_Helper', 'init' ), 9, 0 );
879
		}
880
881
		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...
882
			add_action( 'init', array( new Plugin_Tracking(), 'init' ) );
883
		} else {
884
			/**
885
			 * Initialize tracking right after the user agrees to the terms of service.
886
			 */
887
			add_action( 'jetpack_agreed_to_terms_of_service', array( new Plugin_Tracking(), 'init' ) );
888
		}
889
	}
890
891
	/**
892
	 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
893
	 * initialization code.
894
	 *
895
	 * @action plugins_loaded
896
	 */
897
	public function late_initialization() {
898
		add_action( 'plugins_loaded', array( 'Jetpack', 'load_modules' ), 100 );
899
900
		Partner::init();
901
902
		/**
903
		 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
904
		 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
905
		 *
906
		 * @since 8.1.0
907
		 *
908
		 * @param Jetpack $jetpack the main plugin class object.
909
		 */
910
		do_action( 'jetpack_loaded', $this );
911
912
		add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
913
	}
914
915
	/**
916
	 * Sets up the XMLRPC request handlers.
917
	 *
918
	 * @deprecated since 7.7.0
919
	 * @see Automattic\Jetpack\Connection\Manager::setup_xmlrpc_handlers()
920
	 *
921
	 * @param array                 $request_params Incoming request parameters.
922
	 * @param Boolean               $is_active      Whether the connection is currently active.
923
	 * @param Boolean               $is_signed      Whether the signature check has been successful.
924
	 * @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...
925
	 */
926 View Code Duplication
	public function setup_xmlrpc_handlers(
927
		$request_params,
928
		$is_active,
929
		$is_signed,
930
		Jetpack_XMLRPC_Server $xmlrpc_server = null
931
	) {
932
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::setup_xmlrpc_handlers' );
933
934
		if ( ! $this->connection_manager ) {
935
			$this->connection_manager = new Connection_Manager();
936
		}
937
938
		return $this->connection_manager->setup_xmlrpc_handlers(
939
			$request_params,
940
			$is_active,
941
			$is_signed,
942
			$xmlrpc_server
943
		);
944
	}
945
946
	/**
947
	 * Initialize REST API registration connector.
948
	 *
949
	 * @deprecated since 7.7.0
950
	 * @see Automattic\Jetpack\Connection\Manager::initialize_rest_api_registration_connector()
951
	 */
952 View Code Duplication
	public function initialize_rest_api_registration_connector() {
953
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::initialize_rest_api_registration_connector' );
954
955
		if ( ! $this->connection_manager ) {
956
			$this->connection_manager = new Connection_Manager();
957
		}
958
959
		$this->connection_manager->initialize_rest_api_registration_connector();
960
	}
961
962
	/**
963
	 * This is ported over from the manage module, which has been deprecated and baked in here.
964
	 *
965
	 * @param $domains
966
	 */
967
	function add_wpcom_to_allowed_redirect_hosts( $domains ) {
968
		add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
969
	}
970
971
	/**
972
	 * Return $domains, with 'wordpress.com' appended.
973
	 * This is ported over from the manage module, which has been deprecated and baked in here.
974
	 *
975
	 * @param $domains
976
	 * @return array
977
	 */
978
	function allow_wpcom_domain( $domains ) {
979
		if ( empty( $domains ) ) {
980
			$domains = array();
981
		}
982
		$domains[] = 'wordpress.com';
983
		return array_unique( $domains );
984
	}
985
986
	function point_edit_post_links_to_calypso( $default_url, $post_id ) {
987
		$post = get_post( $post_id );
988
989
		if ( empty( $post ) ) {
990
			return $default_url;
991
		}
992
993
		$post_type = $post->post_type;
994
995
		// Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
996
		// https://en.support.wordpress.com/custom-post-types/
997
		$allowed_post_types = array(
998
			'post',
999
			'page',
1000
			'jetpack-portfolio',
1001
			'jetpack-testimonial',
1002
		);
1003
1004
		if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1005
			return $default_url;
1006
		}
1007
1008
		return Redirect::get_url(
1009
			'calypso-edit-' . $post_type,
1010
			array(
1011
				'path' => $post_id,
1012
			)
1013
		);
1014
	}
1015
1016
	function point_edit_comment_links_to_calypso( $url ) {
1017
		// Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1018
		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...
1019
1020
		return Redirect::get_url(
1021
			'calypso-edit-comment',
1022
			array(
1023
				'path' => $query_args['amp;c'],
1024
			)
1025
		);
1026
1027
	}
1028
1029
	function jetpack_track_last_sync_callback( $params ) {
1030
		/**
1031
		 * Filter to turn off jitm caching
1032
		 *
1033
		 * @since 5.4.0
1034
		 *
1035
		 * @param bool false Whether to cache just in time messages
1036
		 */
1037
		if ( ! apply_filters( 'jetpack_just_in_time_msg_cache', false ) ) {
1038
			return $params;
1039
		}
1040
1041
		if ( is_array( $params ) && isset( $params[0] ) ) {
1042
			$option = $params[0];
1043
			if ( 'active_plugins' === $option ) {
1044
				// use the cache if we can, but not terribly important if it gets evicted
1045
				set_transient( 'jetpack_last_plugin_sync', time(), HOUR_IN_SECONDS );
1046
			}
1047
		}
1048
1049
		return $params;
1050
	}
1051
1052
	function jetpack_connection_banner_callback() {
1053
		check_ajax_referer( 'jp-connection-banner-nonce', 'nonce' );
1054
1055
		// Disable the banner dismiss functionality if the pre-connection prompt helpers filter is set.
1056
		if (
1057
			isset( $_REQUEST['dismissBanner'] ) &&
1058
			! Jetpack_Connection_Banner::force_display()
1059
		) {
1060
			Jetpack_Options::update_option( 'dismissed_connection_banner', 1 );
1061
			wp_send_json_success();
1062
		}
1063
1064
		wp_die();
1065
	}
1066
1067
	/**
1068
	 * Removes all XML-RPC methods that are not `jetpack.*`.
1069
	 * Only used in our alternate XML-RPC endpoint, where we want to
1070
	 * ensure that Core and other plugins' methods are not exposed.
1071
	 *
1072
	 * @deprecated since 7.7.0
1073
	 * @see Automattic\Jetpack\Connection\Manager::remove_non_jetpack_xmlrpc_methods()
1074
	 *
1075
	 * @param array $methods A list of registered WordPress XMLRPC methods.
1076
	 * @return array Filtered $methods
1077
	 */
1078 View Code Duplication
	public function remove_non_jetpack_xmlrpc_methods( $methods ) {
1079
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::remove_non_jetpack_xmlrpc_methods' );
1080
1081
		if ( ! $this->connection_manager ) {
1082
			$this->connection_manager = new Connection_Manager();
1083
		}
1084
1085
		return $this->connection_manager->remove_non_jetpack_xmlrpc_methods( $methods );
1086
	}
1087
1088
	/**
1089
	 * Since a lot of hosts use a hammer approach to "protecting" WordPress sites,
1090
	 * and just blanket block all requests to /xmlrpc.php, or apply other overly-sensitive
1091
	 * security/firewall policies, we provide our own alternate XML RPC API endpoint
1092
	 * which is accessible via a different URI. Most of the below is copied directly
1093
	 * from /xmlrpc.php so that we're replicating it as closely as possible.
1094
	 *
1095
	 * @deprecated since 7.7.0
1096
	 * @see Automattic\Jetpack\Connection\Manager::alternate_xmlrpc()
1097
	 */
1098 View Code Duplication
	public function alternate_xmlrpc() {
1099
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::alternate_xmlrpc' );
1100
1101
		if ( ! $this->connection_manager ) {
1102
			$this->connection_manager = new Connection_Manager();
1103
		}
1104
1105
		$this->connection_manager->alternate_xmlrpc();
1106
	}
1107
1108
	/**
1109
	 * The callback for the JITM ajax requests.
1110
	 *
1111
	 * @deprecated since 7.9.0
1112
	 */
1113
	function jetpack_jitm_ajax_callback() {
1114
		_deprecated_function( __METHOD__, 'jetpack-7.9' );
1115
	}
1116
1117
	/**
1118
	 * If there are any stats that need to be pushed, but haven't been, push them now.
1119
	 */
1120
	function push_stats() {
1121
		if ( ! empty( $this->stats ) ) {
1122
			$this->do_stats( 'server_side' );
1123
		}
1124
	}
1125
1126
	/**
1127
	 * Sets the Jetpack custom capabilities.
1128
	 *
1129
	 * @param string[] $caps    Array of the user's capabilities.
1130
	 * @param string   $cap     Capability name.
1131
	 * @param int      $user_id The user ID.
1132
	 * @param array    $args    Adds the context to the cap. Typically the object ID.
1133
	 */
1134
	public function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
1135
		$is_offline_mode = ( new Status() )->is_offline_mode();
1136
		switch ( $cap ) {
1137
			case 'jetpack_manage_modules':
1138
			case 'jetpack_activate_modules':
1139
			case 'jetpack_deactivate_modules':
1140
				$caps = array( 'manage_options' );
1141
				break;
1142
			case 'jetpack_configure_modules':
1143
				$caps = array( 'manage_options' );
1144
				break;
1145
			case 'jetpack_manage_autoupdates':
1146
				$caps = array(
1147
					'manage_options',
1148
					'update_plugins',
1149
				);
1150
				break;
1151
			case 'jetpack_network_admin_page':
1152
			case 'jetpack_network_settings_page':
1153
				$caps = array( 'manage_network_plugins' );
1154
				break;
1155
			case 'jetpack_network_sites_page':
1156
				$caps = array( 'manage_sites' );
1157
				break;
1158
			case 'jetpack_admin_page':
1159
				if ( $is_offline_mode ) {
1160
					$caps = array( 'manage_options' );
1161
					break;
1162
				} else {
1163
					$caps = array( 'read' );
1164
				}
1165
				break;
1166
		}
1167
		return $caps;
1168
	}
1169
1170
	/**
1171
	 * Require a Jetpack authentication.
1172
	 *
1173
	 * @deprecated since 7.7.0
1174
	 * @see Automattic\Jetpack\Connection\Manager::require_jetpack_authentication()
1175
	 */
1176 View Code Duplication
	public function require_jetpack_authentication() {
1177
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::require_jetpack_authentication' );
1178
1179
		if ( ! $this->connection_manager ) {
1180
			$this->connection_manager = new Connection_Manager();
1181
		}
1182
1183
		$this->connection_manager->require_jetpack_authentication();
1184
	}
1185
1186
	/**
1187
	 * Register assets for use in various modules and the Jetpack admin page.
1188
	 *
1189
	 * @uses wp_script_is, wp_register_script, plugins_url
1190
	 * @action wp_loaded
1191
	 * @return null
1192
	 */
1193
	public function register_assets() {
1194 View Code Duplication
		if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1195
			wp_register_script(
1196
				'jetpack-gallery-settings',
1197
				Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1198
				array( 'media-views' ),
1199
				'20121225'
1200
			);
1201
		}
1202
1203
		if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1204
			wp_register_script(
1205
				'jetpack-twitter-timeline',
1206
				Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1207
				array( 'jquery' ),
1208
				'4.0.0',
1209
				true
1210
			);
1211
		}
1212
1213
		if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1214
			wp_register_script(
1215
				'jetpack-facebook-embed',
1216
				Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1217
				array(),
1218
				null,
1219
				true
1220
			);
1221
1222
			/** This filter is documented in modules/sharedaddy/sharing-sources.php */
1223
			$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1224
			if ( ! is_numeric( $fb_app_id ) ) {
1225
				$fb_app_id = '';
1226
			}
1227
			wp_localize_script(
1228
				'jetpack-facebook-embed',
1229
				'jpfbembed',
1230
				array(
1231
					'appid'  => $fb_app_id,
1232
					'locale' => $this->get_locale(),
1233
				)
1234
			);
1235
		}
1236
1237
		/**
1238
		 * As jetpack_register_genericons is by default fired off a hook,
1239
		 * the hook may have already fired by this point.
1240
		 * So, let's just trigger it manually.
1241
		 */
1242
		require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1243
		jetpack_register_genericons();
1244
1245
		/**
1246
		 * Register the social logos
1247
		 */
1248
		require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1249
		jetpack_register_social_logos();
1250
1251 View Code Duplication
		if ( ! wp_style_is( 'jetpack-icons', 'registered' ) ) {
1252
			wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
1253
		}
1254
	}
1255
1256
	/**
1257
	 * Guess locale from language code.
1258
	 *
1259
	 * @param string $lang Language code.
1260
	 * @return string|bool
1261
	 */
1262 View Code Duplication
	function guess_locale_from_lang( $lang ) {
1263
		if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1264
			return 'en_US';
1265
		}
1266
1267
		if ( ! class_exists( 'GP_Locales' ) ) {
1268
			if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1269
				return false;
1270
			}
1271
1272
			require JETPACK__GLOTPRESS_LOCALES_PATH;
1273
		}
1274
1275
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1276
			// WP.com: get_locale() returns 'it'
1277
			$locale = GP_Locales::by_slug( $lang );
1278
		} else {
1279
			// Jetpack: get_locale() returns 'it_IT';
1280
			$locale = GP_Locales::by_field( 'facebook_locale', $lang );
1281
		}
1282
1283
		if ( ! $locale ) {
1284
			return false;
1285
		}
1286
1287
		if ( empty( $locale->facebook_locale ) ) {
1288
			if ( empty( $locale->wp_locale ) ) {
1289
				return false;
1290
			} else {
1291
				// Facebook SDK is smart enough to fall back to en_US if a
1292
				// locale isn't supported. Since supported Facebook locales
1293
				// can fall out of sync, we'll attempt to use the known
1294
				// wp_locale value and rely on said fallback.
1295
				return $locale->wp_locale;
1296
			}
1297
		}
1298
1299
		return $locale->facebook_locale;
1300
	}
1301
1302
	/**
1303
	 * Get the locale.
1304
	 *
1305
	 * @return string|bool
1306
	 */
1307
	function get_locale() {
1308
		$locale = $this->guess_locale_from_lang( get_locale() );
1309
1310
		if ( ! $locale ) {
1311
			$locale = 'en_US';
1312
		}
1313
1314
		return $locale;
1315
	}
1316
1317
	/**
1318
	 * Return the network_site_url so that .com knows what network this site is a part of.
1319
	 *
1320
	 * @param  bool $option
1321
	 * @return string
1322
	 */
1323
	public function jetpack_main_network_site_option( $option ) {
1324
		return network_site_url();
1325
	}
1326
	/**
1327
	 * Network Name.
1328
	 */
1329
	static function network_name( $option = null ) {
1330
		global $current_site;
1331
		return $current_site->site_name;
1332
	}
1333
	/**
1334
	 * Does the network allow new user and site registrations.
1335
	 *
1336
	 * @return string
1337
	 */
1338
	static function network_allow_new_registrations( $option = null ) {
1339
		return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration' ) : 'none' );
1340
	}
1341
	/**
1342
	 * Does the network allow admins to add new users.
1343
	 *
1344
	 * @return boolian
1345
	 */
1346
	static function network_add_new_users( $option = null ) {
1347
		return (bool) get_site_option( 'add_new_users' );
1348
	}
1349
	/**
1350
	 * File upload psace left per site in MB.
1351
	 *  -1 means NO LIMIT.
1352
	 *
1353
	 * @return number
1354
	 */
1355
	static function network_site_upload_space( $option = null ) {
1356
		// value in MB
1357
		return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1358
	}
1359
1360
	/**
1361
	 * Network allowed file types.
1362
	 *
1363
	 * @return string
1364
	 */
1365
	static function network_upload_file_types( $option = null ) {
1366
		return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1367
	}
1368
1369
	/**
1370
	 * Maximum file upload size set by the network.
1371
	 *
1372
	 * @return number
1373
	 */
1374
	static function network_max_upload_file_size( $option = null ) {
1375
		// value in KB
1376
		return get_site_option( 'fileupload_maxk', 300 );
1377
	}
1378
1379
	/**
1380
	 * Lets us know if a site allows admins to manage the network.
1381
	 *
1382
	 * @return array
1383
	 */
1384
	static function network_enable_administration_menus( $option = null ) {
1385
		return get_site_option( 'menu_items' );
1386
	}
1387
1388
	/**
1389
	 * If a user has been promoted to or demoted from admin, we need to clear the
1390
	 * jetpack_other_linked_admins transient.
1391
	 *
1392
	 * @since 4.3.2
1393
	 * @since 4.4.0  $old_roles is null by default and if it's not passed, the transient is cleared.
1394
	 *
1395
	 * @param int    $user_id   The user ID whose role changed.
1396
	 * @param string $role      The new role.
1397
	 * @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...
1398
	 */
1399
	function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1400
		if ( 'administrator' == $role
1401
			|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
1402
			|| is_null( $old_roles )
1403
		) {
1404
			delete_transient( 'jetpack_other_linked_admins' );
1405
		}
1406
	}
1407
1408
	/**
1409
	 * Checks to see if there are any other users available to become primary
1410
	 * Users must both:
1411
	 * - Be linked to wpcom
1412
	 * - Be an admin
1413
	 *
1414
	 * @return mixed False if no other users are linked, Int if there are.
1415
	 */
1416
	static function get_other_linked_admins() {
1417
		$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1418
1419
		if ( false === $other_linked_users ) {
1420
			$admins = get_users( array( 'role' => 'administrator' ) );
1421
			if ( count( $admins ) > 1 ) {
1422
				$available = array();
1423
				foreach ( $admins as $admin ) {
1424
					if ( self::is_user_connected( $admin->ID ) ) {
1425
						$available[] = $admin->ID;
1426
					}
1427
				}
1428
1429
				$count_connected_admins = count( $available );
1430
				if ( count( $available ) > 1 ) {
1431
					$other_linked_users = $count_connected_admins;
1432
				} else {
1433
					$other_linked_users = 0;
1434
				}
1435
			} else {
1436
				$other_linked_users = 0;
1437
			}
1438
1439
			set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1440
		}
1441
1442
		return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1443
	}
1444
1445
	/**
1446
	 * Return whether we are dealing with a multi network setup or not.
1447
	 * The reason we are type casting this is because we want to avoid the situation where
1448
	 * the result is false since when is_main_network_option return false it cases
1449
	 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1450
	 * database which could be set to anything as opposed to what this function returns.
1451
	 *
1452
	 * @param  bool $option
1453
	 *
1454
	 * @return boolean
1455
	 */
1456
	public function is_main_network_option( $option ) {
1457
		// return '1' or ''
1458
		return (string) (bool) self::is_multi_network();
1459
	}
1460
1461
	/**
1462
	 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1463
	 *
1464
	 * @param  string $option
1465
	 * @return boolean
1466
	 */
1467
	public function is_multisite( $option ) {
1468
		return (string) (bool) is_multisite();
1469
	}
1470
1471
	/**
1472
	 * Implemented since there is no core is multi network function
1473
	 * Right now there is no way to tell if we which network is the dominant network on the system
1474
	 *
1475
	 * @since  3.3
1476
	 * @return boolean
1477
	 */
1478 View Code Duplication
	public static function is_multi_network() {
1479
		global  $wpdb;
1480
1481
		// if we don't have a multi site setup no need to do any more
1482
		if ( ! is_multisite() ) {
1483
			return false;
1484
		}
1485
1486
		$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1487
		if ( $num_sites > 1 ) {
1488
			return true;
1489
		} else {
1490
			return false;
1491
		}
1492
	}
1493
1494
	/**
1495
	 * Trigger an update to the main_network_site when we update the siteurl of a site.
1496
	 *
1497
	 * @return null
1498
	 */
1499
	function update_jetpack_main_network_site_option() {
1500
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1501
	}
1502
	/**
1503
	 * Triggered after a user updates the network settings via Network Settings Admin Page
1504
	 */
1505
	function update_jetpack_network_settings() {
1506
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1507
		// Only sync this info for the main network site.
1508
	}
1509
1510
	/**
1511
	 * Get back if the current site is single user site.
1512
	 *
1513
	 * @return bool
1514
	 */
1515 View Code Duplication
	public static function is_single_user_site() {
1516
		global $wpdb;
1517
1518
		if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
1519
			$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1520
			set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1521
		}
1522
		return 1 === (int) $some_users;
1523
	}
1524
1525
	/**
1526
	 * Returns true if the site has file write access false otherwise.
1527
	 *
1528
	 * @return string ( '1' | '0' )
1529
	 **/
1530
	public static function file_system_write_access() {
1531
		if ( ! function_exists( 'get_filesystem_method' ) ) {
1532
			require_once ABSPATH . 'wp-admin/includes/file.php';
1533
		}
1534
1535
		require_once ABSPATH . 'wp-admin/includes/template.php';
1536
1537
		$filesystem_method = get_filesystem_method();
1538
		if ( $filesystem_method === 'direct' ) {
1539
			return 1;
1540
		}
1541
1542
		ob_start();
1543
		$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1544
		ob_end_clean();
1545
		if ( $filesystem_credentials_are_stored ) {
1546
			return 1;
1547
		}
1548
		return 0;
1549
	}
1550
1551
	/**
1552
	 * Finds out if a site is using a version control system.
1553
	 *
1554
	 * @return string ( '1' | '0' )
1555
	 **/
1556
	public static function is_version_controlled() {
1557
		_deprecated_function( __METHOD__, 'jetpack-4.2', 'Functions::is_version_controlled' );
1558
		return (string) (int) Functions::is_version_controlled();
1559
	}
1560
1561
	/**
1562
	 * Determines whether the current theme supports featured images or not.
1563
	 *
1564
	 * @return string ( '1' | '0' )
1565
	 */
1566
	public static function featured_images_enabled() {
1567
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1568
		return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
1569
	}
1570
1571
	/**
1572
	 * Wrapper for core's get_avatar_url().  This one is deprecated.
1573
	 *
1574
	 * @deprecated 4.7 use get_avatar_url instead.
1575
	 * @param int|string|object $id_or_email A user ID,  email address, or comment object
1576
	 * @param int               $size Size of the avatar image
1577
	 * @param string            $default URL to a default image to use if no avatar is available
1578
	 * @param bool              $force_display Whether to force it to return an avatar even if show_avatars is disabled
1579
	 *
1580
	 * @return array
1581
	 */
1582
	public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
1583
		_deprecated_function( __METHOD__, 'jetpack-4.7', 'get_avatar_url' );
1584
		return get_avatar_url(
1585
			$id_or_email,
1586
			array(
1587
				'size'          => $size,
1588
				'default'       => $default,
1589
				'force_default' => $force_display,
1590
			)
1591
		);
1592
	}
1593
// phpcs:disable WordPress.WP.CapitalPDangit.Misspelled
1594
	/**
1595
	 * jetpack_updates is saved in the following schema:
1596
	 *
1597
	 * array (
1598
	 *      'plugins'                       => (int) Number of plugin updates available.
1599
	 *      'themes'                        => (int) Number of theme updates available.
1600
	 *      'wordpress'                     => (int) Number of WordPress core updates available.
1601
	 *      'translations'                  => (int) Number of translation updates available.
1602
	 *      'total'                         => (int) Total of all available updates.
1603
	 *      'wp_update_version'             => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1604
	 * )
1605
	 *
1606
	 * @return array
1607
	 */
1608
	public static function get_updates() {
1609
		$update_data = wp_get_update_data();
1610
1611
		// Stores the individual update counts as well as the total count.
1612
		if ( isset( $update_data['counts'] ) ) {
1613
			$updates = $update_data['counts'];
1614
		}
1615
1616
		// If we need to update WordPress core, let's find the latest version number.
1617 View Code Duplication
		if ( ! empty( $updates['wordpress'] ) ) {
1618
			$cur = get_preferred_from_update_core();
1619
			if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1620
				$updates['wp_update_version'] = $cur->current;
1621
			}
1622
		}
1623
		return isset( $updates ) ? $updates : array();
1624
	}
1625
	// phpcs:enable
1626
1627
	public static function get_update_details() {
1628
		$update_details = array(
1629
			'update_core'    => get_site_transient( 'update_core' ),
1630
			'update_plugins' => get_site_transient( 'update_plugins' ),
1631
			'update_themes'  => get_site_transient( 'update_themes' ),
1632
		);
1633
		return $update_details;
1634
	}
1635
1636
	public static function refresh_update_data() {
1637
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1638
1639
	}
1640
1641
	public static function refresh_theme_data() {
1642
		_deprecated_function( __METHOD__, 'jetpack-4.2' );
1643
	}
1644
1645
	/**
1646
	 * Is Jetpack active?
1647
	 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1648
	 *
1649
	 * @return bool
1650
	 */
1651
	public static function is_active() {
1652
		return self::connection()->is_active();
1653
	}
1654
1655
	/**
1656
	 * Make an API call to WordPress.com for plan status
1657
	 *
1658
	 * @deprecated 7.2.0 Use Jetpack_Plan::refresh_from_wpcom.
1659
	 *
1660
	 * @return bool True if plan is updated, false if no update
1661
	 */
1662
	public static function refresh_active_plan_from_wpcom() {
1663
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::refresh_from_wpcom' );
1664
		return Jetpack_Plan::refresh_from_wpcom();
1665
	}
1666
1667
	/**
1668
	 * Get the plan that this Jetpack site is currently using
1669
	 *
1670
	 * @deprecated 7.2.0 Use Jetpack_Plan::get.
1671
	 * @return array Active Jetpack plan details.
1672
	 */
1673
	public static function get_active_plan() {
1674
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::get' );
1675
		return Jetpack_Plan::get();
1676
	}
1677
1678
	/**
1679
	 * Determine whether the active plan supports a particular feature
1680
	 *
1681
	 * @deprecated 7.2.0 Use Jetpack_Plan::supports.
1682
	 * @return bool True if plan supports feature, false if not.
1683
	 */
1684
	public static function active_plan_supports( $feature ) {
1685
		_deprecated_function( __METHOD__, 'jetpack-7.2.0', 'Jetpack_Plan::supports' );
1686
		return Jetpack_Plan::supports( $feature );
1687
	}
1688
1689
	/**
1690
	 * Deprecated: Is Jetpack in development (offline) mode?
1691
	 *
1692
	 * This static method is being left here intentionally without the use of _deprecated_function(), as other plugins
1693
	 * and themes still use it, and we do not want to flood them with notices.
1694
	 *
1695
	 * Please use Automattic\Jetpack\Status()->is_offline_mode() instead.
1696
	 *
1697
	 * @deprecated since 8.0.
1698
	 */
1699
	public static function is_development_mode() {
1700
		return ( new Status() )->is_offline_mode();
1701
	}
1702
1703
	/**
1704
	 * Whether the site is currently onboarding or not.
1705
	 * A site is considered as being onboarded if it currently has an onboarding token.
1706
	 *
1707
	 * @since 5.8
1708
	 *
1709
	 * @access public
1710
	 * @static
1711
	 *
1712
	 * @return bool True if the site is currently onboarding, false otherwise
1713
	 */
1714
	public static function is_onboarding() {
1715
		return Jetpack_Options::get_option( 'onboarding' ) !== false;
1716
	}
1717
1718
	/**
1719
	 * Determines reason for Jetpack offline mode.
1720
	 */
1721
	public static function development_mode_trigger_text() {
1722
		$status = new Status();
1723
1724
		if ( ! $status->is_offline_mode() ) {
1725
			return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1726
		}
1727
1728
		if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1729
			$notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1730
		} elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1731
			$notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1732
		} elseif ( $status->is_local_site() ) {
1733
			$notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1734
			/** This filter is documented in packages/status/src/class-status.php */
1735
		} elseif ( has_filter( 'jetpack_development_mode' ) && apply_filters( 'jetpack_development_mode', false ) ) { // This is a deprecated filter name.
1736
			$notice = __( 'The jetpack_development_mode filter is set to true.', 'jetpack' );
1737
		} else {
1738
			$notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1739
		}
1740
1741
		return $notice;
1742
1743
	}
1744
	/**
1745
	 * Get Jetpack offline mode notice text and notice class.
1746
	 *
1747
	 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1748
	 */
1749
	public static function show_development_mode_notice() {
1750 View Code Duplication
		if ( ( new Status() )->is_offline_mode() ) {
1751
			$notice = sprintf(
1752
				/* translators: %s is a URL */
1753
				__( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1754
				Redirect::get_url( 'jetpack-support-development-mode' )
1755
			);
1756
1757
			$notice .= ' ' . self::development_mode_trigger_text();
1758
1759
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1760
		}
1761
1762
		// Throw up a notice if using a development version and as for feedback.
1763
		if ( self::is_development_version() ) {
1764
			/* translators: %s is a URL */
1765
			$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' ) );
1766
1767
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1768
		}
1769
		// Throw up a notice if using staging mode
1770 View Code Duplication
		if ( ( new Status() )->is_staging_site() ) {
1771
			/* translators: %s is a URL */
1772
			$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), Redirect::get_url( 'jetpack-support-staging-sites' ) );
1773
1774
			echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
1775
		}
1776
	}
1777
1778
	/**
1779
	 * Whether Jetpack's version maps to a public release, or a development version.
1780
	 */
1781
	public static function is_development_version() {
1782
		/**
1783
		 * Allows filtering whether this is a development version of Jetpack.
1784
		 *
1785
		 * This filter is especially useful for tests.
1786
		 *
1787
		 * @since 4.3.0
1788
		 *
1789
		 * @param bool $development_version Is this a develoment version of Jetpack?
1790
		 */
1791
		return (bool) apply_filters(
1792
			'jetpack_development_version',
1793
			! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1794
		);
1795
	}
1796
1797
	/**
1798
	 * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
1799
	 */
1800
	public static function is_user_connected( $user_id = false ) {
1801
		_deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Manager\\is_user_connected' );
1802
		return self::connection()->is_user_connected( $user_id );
0 ignored issues
show
Documentation introduced by
$user_id is of type boolean, but the function expects a false|integer.

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

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

Consider the follow example

<?php

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

    return false;
}

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

Loading history...
3384
				if ( is_wp_error( $result ) ) {
3385
					return $result;
3386
				}
3387
			}
3388
		}
3389
3390
		$result = self::register();
3391
3392
		// If there was an error with registration and the site was not registered, record this so we can show a message.
3393
		if ( ! $result || is_wp_error( $result ) ) {
3394
			return $result;
3395
		} else {
3396
			return true;
3397
		}
3398
	}
3399
3400
	/**
3401
	 * Tracking an internal event log. Try not to put too much chaff in here.
3402
	 *
3403
	 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3404
	 */
3405
	public static function log( $code, $data = null ) {
3406
		// only grab the latest 200 entries
3407
		$log = array_slice( Jetpack_Options::get_option( 'log', array() ), -199, 199 );
3408
3409
		// Append our event to the log
3410
		$log_entry = array(
3411
			'time'    => time(),
3412
			'user_id' => get_current_user_id(),
3413
			'blog_id' => Jetpack_Options::get_option( 'id' ),
3414
			'code'    => $code,
3415
		);
3416
		// Don't bother storing it unless we've got some.
3417
		if ( ! is_null( $data ) ) {
3418
			$log_entry['data'] = $data;
3419
		}
3420
		$log[] = $log_entry;
3421
3422
		// Try add_option first, to make sure it's not autoloaded.
3423
		// @todo: Add an add_option method to Jetpack_Options
3424
		if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
3425
			Jetpack_Options::update_option( 'log', $log );
3426
		}
3427
3428
		/**
3429
		 * Fires when Jetpack logs an internal event.
3430
		 *
3431
		 * @since 3.0.0
3432
		 *
3433
		 * @param array $log_entry {
3434
		 *  Array of details about the log entry.
3435
		 *
3436
		 *  @param string time Time of the event.
3437
		 *  @param int user_id ID of the user who trigerred the event.
3438
		 *  @param int blog_id Jetpack Blog ID.
3439
		 *  @param string code Unique name for the event.
3440
		 *  @param string data Data about the event.
3441
		 * }
3442
		 */
3443
		do_action( 'jetpack_log_entry', $log_entry );
3444
	}
3445
3446
	/**
3447
	 * Get the internal event log.
3448
	 *
3449
	 * @param $event (string) - only return the specific log events
3450
	 * @param $num   (int)    - get specific number of latest results, limited to 200
3451
	 *
3452
	 * @return array of log events || WP_Error for invalid params
3453
	 */
3454
	public static function get_log( $event = false, $num = false ) {
3455
		if ( $event && ! is_string( $event ) ) {
3456
			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...
3457
		}
3458
3459
		if ( $num && ! is_numeric( $num ) ) {
3460
			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...
3461
		}
3462
3463
		$entire_log = Jetpack_Options::get_option( 'log', array() );
3464
3465
		// If nothing set - act as it did before, otherwise let's start customizing the output
3466
		if ( ! $num && ! $event ) {
3467
			return $entire_log;
3468
		} else {
3469
			$entire_log = array_reverse( $entire_log );
3470
		}
3471
3472
		$custom_log_output = array();
3473
3474
		if ( $event ) {
3475
			foreach ( $entire_log as $log_event ) {
3476
				if ( $event == $log_event['code'] ) {
3477
					$custom_log_output[] = $log_event;
3478
				}
3479
			}
3480
		} else {
3481
			$custom_log_output = $entire_log;
3482
		}
3483
3484
		if ( $num ) {
3485
			$custom_log_output = array_slice( $custom_log_output, 0, $num );
3486
		}
3487
3488
		return $custom_log_output;
3489
	}
3490
3491
	/**
3492
	 * Log modification of important settings.
3493
	 */
3494
	public static function log_settings_change( $option, $old_value, $value ) {
3495
		switch ( $option ) {
3496
			case 'jetpack_sync_non_public_post_stati':
3497
				self::log( $option, $value );
3498
				break;
3499
		}
3500
	}
3501
3502
	/**
3503
	 * Return stat data for WPCOM sync
3504
	 */
3505
	public static function get_stat_data( $encode = true, $extended = true ) {
3506
		$data = Jetpack_Heartbeat::generate_stats_array();
3507
3508
		if ( $extended ) {
3509
			$additional_data = self::get_additional_stat_data();
3510
			$data            = array_merge( $data, $additional_data );
3511
		}
3512
3513
		if ( $encode ) {
3514
			return json_encode( $data );
3515
		}
3516
3517
		return $data;
3518
	}
3519
3520
	/**
3521
	 * Get additional stat data to sync to WPCOM
3522
	 */
3523
	public static function get_additional_stat_data( $prefix = '' ) {
3524
		$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...
3525
		$return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3526
		$return[ "{$prefix}users" ]         = (int) self::get_site_user_count();
3527
		$return[ "{$prefix}site-count" ]    = 0;
3528
3529
		if ( function_exists( 'get_blog_count' ) ) {
3530
			$return[ "{$prefix}site-count" ] = get_blog_count();
3531
		}
3532
		return $return;
3533
	}
3534
3535
	private static function get_site_user_count() {
3536
		global $wpdb;
3537
3538
		if ( function_exists( 'wp_is_large_network' ) ) {
3539
			if ( wp_is_large_network( 'users' ) ) {
3540
				return -1; // Not a real value but should tell us that we are dealing with a large network.
3541
			}
3542
		}
3543
		if ( false === ( $user_count = get_transient( 'jetpack_site_user_count' ) ) ) {
3544
			// It wasn't there, so regenerate the data and save the transient
3545
			$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3546
			set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3547
		}
3548
		return $user_count;
3549
	}
3550
3551
	/* Admin Pages */
3552
3553
	function admin_init() {
3554
		// If the plugin is not connected, display a connect message.
3555
		if (
3556
			// the plugin was auto-activated and needs its candy
3557
			Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3558
		||
3559
			// the plugin is active, but was never activated.  Probably came from a site-wide network activation
3560
			! Jetpack_Options::get_option( 'activated' )
3561
		) {
3562
			self::plugin_initialize();
3563
		}
3564
3565
		$is_offline_mode = ( new Status() )->is_offline_mode();
3566
		if ( ! self::is_active() && ! $is_offline_mode ) {
3567
			Jetpack_Connection_Banner::init();
3568
		} elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
3569
			// Upgrade: 1.1 -> 1.1.1
3570
			// Check and see if host can verify the Jetpack servers' SSL certificate
3571
			$args = array();
3572
			Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3573
		}
3574
3575
		Jetpack_Wizard_Banner::init();
3576
3577
		if ( current_user_can( 'manage_options' ) && ! self::permit_ssl() ) {
3578
			add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3579
		}
3580
3581
		add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3582
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
3583
		add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3584
		add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3585
3586
		if ( self::is_active() || $is_offline_mode ) {
3587
			// Artificially throw errors in certain specific cases during plugin activation.
3588
			add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3589
		}
3590
3591
		// Add custom column in wp-admin/users.php to show whether user is linked.
3592
		add_filter( 'manage_users_columns', array( $this, 'jetpack_icon_user_connected' ) );
3593
		add_action( 'manage_users_custom_column', array( $this, 'jetpack_show_user_connected_icon' ), 10, 3 );
3594
		add_action( 'admin_print_styles', array( $this, 'jetpack_user_col_style' ) );
3595
	}
3596
3597
	function admin_body_class( $admin_body_class = '' ) {
3598
		$classes = explode( ' ', trim( $admin_body_class ) );
3599
3600
		$classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
3601
3602
		$admin_body_class = implode( ' ', array_unique( $classes ) );
3603
		return " $admin_body_class ";
3604
	}
3605
3606
	static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3607
		return $admin_body_class . ' jetpack-pagestyles ';
3608
	}
3609
3610
	/**
3611
	 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3612
	 * This function artificially throws errors for such cases (per a specific list).
3613
	 *
3614
	 * @param string $plugin The activated plugin.
3615
	 */
3616
	function throw_error_on_activate_plugin( $plugin ) {
3617
		$active_modules = self::get_active_modules();
3618
3619
		// The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3620
		if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
3621
			$throw = false;
3622
3623
			// Try and make sure it really was the stats plugin
3624
			if ( ! class_exists( 'ReflectionFunction' ) ) {
3625
				if ( 'stats.php' == basename( $plugin ) ) {
3626
					$throw = true;
3627
				}
3628
			} else {
3629
				$reflection = new ReflectionFunction( 'stats_get_api_key' );
3630
				if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
3631
					$throw = true;
3632
				}
3633
			}
3634
3635
			if ( $throw ) {
3636
				trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
3637
			}
3638
		}
3639
	}
3640
3641
	function intercept_plugin_error_scrape_init() {
3642
		add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3643
	}
3644
3645
	function intercept_plugin_error_scrape( $action, $result ) {
3646
		if ( ! $result ) {
3647
			return;
3648
		}
3649
3650
		foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
3651
			if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
3652
				self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3653
			}
3654
		}
3655
	}
3656
3657
	/**
3658
	 * Register the remote file upload request handlers, if needed.
3659
	 *
3660
	 * @access public
3661
	 */
3662
	public function add_remote_request_handlers() {
3663
		// Remote file uploads are allowed only via AJAX requests.
3664
		if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3665
			return;
3666
		}
3667
3668
		// Remote file uploads are allowed only for a set of specific AJAX actions.
3669
		$remote_request_actions = array(
3670
			'jetpack_upload_file',
3671
			'jetpack_update_file',
3672
		);
3673
3674
		// phpcs:ignore WordPress.Security.NonceVerification
3675
		if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3676
			return;
3677
		}
3678
3679
		// Require Jetpack authentication for the remote file upload AJAX requests.
3680
		if ( ! $this->connection_manager ) {
3681
			$this->connection_manager = new Connection_Manager();
3682
		}
3683
3684
		$this->connection_manager->require_jetpack_authentication();
3685
3686
		// Register the remote file upload AJAX handlers.
3687
		foreach ( $remote_request_actions as $action ) {
3688
			add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3689
		}
3690
	}
3691
3692
	/**
3693
	 * Handler for Jetpack remote file uploads.
3694
	 *
3695
	 * @access public
3696
	 */
3697
	public function remote_request_handlers() {
3698
		$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...
3699
3700
		switch ( current_filter() ) {
3701
			case 'wp_ajax_nopriv_jetpack_upload_file':
3702
				$response = $this->upload_handler();
3703
				break;
3704
3705
			case 'wp_ajax_nopriv_jetpack_update_file':
3706
				$response = $this->upload_handler( true );
3707
				break;
3708
			default:
3709
				$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...
3710
				break;
3711
		}
3712
3713
		if ( ! $response ) {
3714
			$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...
3715
		}
3716
3717
		if ( is_wp_error( $response ) ) {
3718
			$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...
3719
			$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...
3720
			$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...
3721
3722
			if ( ! is_int( $status_code ) ) {
3723
				$status_code = 400;
3724
			}
3725
3726
			status_header( $status_code );
3727
			die( json_encode( (object) compact( 'error', 'error_description' ) ) );
3728
		}
3729
3730
		status_header( 200 );
3731
		if ( true === $response ) {
3732
			exit;
3733
		}
3734
3735
		die( json_encode( (object) $response ) );
3736
	}
3737
3738
	/**
3739
	 * Uploads a file gotten from the global $_FILES.
3740
	 * If `$update_media_item` is true and `post_id` is defined
3741
	 * the attachment file of the media item (gotten through of the post_id)
3742
	 * will be updated instead of add a new one.
3743
	 *
3744
	 * @param  boolean $update_media_item - update media attachment
3745
	 * @return array - An array describing the uploadind files process
3746
	 */
3747
	function upload_handler( $update_media_item = false ) {
3748
		if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
3749
			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...
3750
		}
3751
3752
		$user = wp_authenticate( '', '' );
3753
		if ( ! $user || is_wp_error( $user ) ) {
3754
			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...
3755
		}
3756
3757
		wp_set_current_user( $user->ID );
3758
3759
		if ( ! current_user_can( 'upload_files' ) ) {
3760
			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...
3761
		}
3762
3763
		if ( empty( $_FILES ) ) {
3764
			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...
3765
		}
3766
3767
		foreach ( array_keys( $_FILES ) as $files_key ) {
3768
			if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) {
3769
				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...
3770
			}
3771
		}
3772
3773
		$media_keys = array_keys( $_FILES['media'] );
3774
3775
		$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...
3776
		if ( ! $token || is_wp_error( $token ) ) {
3777
			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...
3778
		}
3779
3780
		$uploaded_files = array();
3781
		$global_post    = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
3782
		unset( $GLOBALS['post'] );
3783
		foreach ( $_FILES['media']['name'] as $index => $name ) {
3784
			$file = array();
3785
			foreach ( $media_keys as $media_key ) {
3786
				$file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ];
3787
			}
3788
3789
			list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][ $index ] );
3790
3791
			$hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3792
			if ( $hmac_provided !== $hmac_file ) {
3793
				$uploaded_files[ $index ] = (object) array(
3794
					'error'             => 'invalid_hmac',
3795
					'error_description' => 'The corresponding HMAC for this file does not match',
3796
				);
3797
				continue;
3798
			}
3799
3800
			$_FILES['.jetpack.upload.'] = $file;
3801
			$post_id                    = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0;
3802
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
3803
				$post_id = 0;
3804
			}
3805
3806
			if ( $update_media_item ) {
3807
				if ( ! isset( $post_id ) || $post_id === 0 ) {
3808
					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...
3809
				}
3810
3811
				$media_array = $_FILES['media'];
3812
3813
				$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...
3814
				$file_array['type']     = $media_array['type'][0];
3815
				$file_array['tmp_name'] = $media_array['tmp_name'][0];
3816
				$file_array['error']    = $media_array['error'][0];
3817
				$file_array['size']     = $media_array['size'][0];
3818
3819
				$edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3820
3821
				if ( is_wp_error( $edited_media_item ) ) {
3822
					return $edited_media_item;
3823
				}
3824
3825
				$response = (object) array(
3826
					'id'   => (string) $post_id,
3827
					'file' => (string) $edited_media_item->post_title,
3828
					'url'  => (string) wp_get_attachment_url( $post_id ),
3829
					'type' => (string) $edited_media_item->post_mime_type,
3830
					'meta' => (array) wp_get_attachment_metadata( $post_id ),
3831
				);
3832
3833
				return (array) array( $response );
3834
			}
3835
3836
			$attachment_id = media_handle_upload(
3837
				'.jetpack.upload.',
3838
				$post_id,
3839
				array(),
3840
				array(
3841
					'action' => 'jetpack_upload_file',
3842
				)
3843
			);
3844
3845
			if ( ! $attachment_id ) {
3846
				$uploaded_files[ $index ] = (object) array(
3847
					'error'             => 'unknown',
3848
					'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3849
				);
3850
			} elseif ( is_wp_error( $attachment_id ) ) {
3851
				$uploaded_files[ $index ] = (object) array(
3852
					'error'             => 'attachment_' . $attachment_id->get_error_code(),
3853
					'error_description' => $attachment_id->get_error_message(),
3854
				);
3855
			} else {
3856
				$attachment               = get_post( $attachment_id );
3857
				$uploaded_files[ $index ] = (object) array(
3858
					'id'   => (string) $attachment_id,
3859
					'file' => $attachment->post_title,
3860
					'url'  => wp_get_attachment_url( $attachment_id ),
3861
					'type' => $attachment->post_mime_type,
3862
					'meta' => wp_get_attachment_metadata( $attachment_id ),
3863
				);
3864
				// Zip files uploads are not supported unless they are done for installation purposed
3865
				// lets delete them in case something goes wrong in this whole process
3866
				if ( 'application/zip' === $attachment->post_mime_type ) {
3867
					// Schedule a cleanup for 2 hours from now in case of failed install.
3868
					wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $attachment_id ) );
3869
				}
3870
			}
3871
		}
3872
		if ( ! is_null( $global_post ) ) {
3873
			$GLOBALS['post'] = $global_post;
3874
		}
3875
3876
		return $uploaded_files;
3877
	}
3878
3879
	/**
3880
	 * Add help to the Jetpack page
3881
	 *
3882
	 * @since Jetpack (1.2.3)
3883
	 * @return false if not the Jetpack page
3884
	 */
3885
	function admin_help() {
3886
		$current_screen = get_current_screen();
3887
3888
		// Overview
3889
		$current_screen->add_help_tab(
3890
			array(
3891
				'id'      => 'home',
3892
				'title'   => __( 'Home', 'jetpack' ),
3893
				'content' =>
3894
					'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3895
					'<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
3896
					'<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>',
3897
			)
3898
		);
3899
3900
		// Screen Content
3901
		if ( current_user_can( 'manage_options' ) ) {
3902
			$current_screen->add_help_tab(
3903
				array(
3904
					'id'      => 'settings',
3905
					'title'   => __( 'Settings', 'jetpack' ),
3906
					'content' =>
3907
						'<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
3908
						'<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
3909
						'<ol>' .
3910
							'<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
3911
							'<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>' .
3912
						'</ol>' .
3913
						'<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>',
3914
				)
3915
			);
3916
		}
3917
3918
		// Help Sidebar
3919
		$support_url = Redirect::get_url( 'jetpack-support' );
3920
		$faq_url     = Redirect::get_url( 'jetpack-faq' );
3921
		$current_screen->set_help_sidebar(
3922
			'<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
3923
			'<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
3924
			'<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
3925
			'<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
3926
		);
3927
	}
3928
3929
	function admin_menu_css() {
3930
		wp_enqueue_style( 'jetpack-icons' );
3931
	}
3932
3933
	function admin_menu_order() {
3934
		return true;
3935
	}
3936
3937
	function jetpack_menu_order( $menu_order ) {
3938
		$jp_menu_order = array();
3939
3940
		foreach ( $menu_order as $index => $item ) {
3941
			if ( $item != 'jetpack' ) {
3942
				$jp_menu_order[] = $item;
3943
			}
3944
3945
			if ( $index == 0 ) {
3946
				$jp_menu_order[] = 'jetpack';
3947
			}
3948
		}
3949
3950
		return $jp_menu_order;
3951
	}
3952
3953
	function admin_banner_styles() {
3954
		$min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
3955
3956 View Code Duplication
		if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
3957
			wp_register_style(
3958
				'jetpack-dops-style',
3959
				plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
3960
				array(),
3961
				JETPACK__VERSION
3962
			);
3963
		}
3964
3965
		wp_enqueue_style(
3966
			'jetpack',
3967
			plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
3968
			array( 'jetpack-dops-style' ),
3969
			JETPACK__VERSION . '-20121016'
3970
		);
3971
		wp_style_add_data( 'jetpack', 'rtl', 'replace' );
3972
		wp_style_add_data( 'jetpack', 'suffix', $min );
3973
	}
3974
3975
	function plugin_action_links( $actions ) {
3976
3977
		$jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), 'Jetpack' ) );
3978
3979
		if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_active() || ( new Status() )->is_offline_mode() ) ) {
3980
			return array_merge(
3981
				$jetpack_home,
3982
				array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
3983
				array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
3984
				$actions
3985
			);
3986
		}
3987
3988
		return array_merge( $jetpack_home, $actions );
3989
	}
3990
3991
	/**
3992
	 * Adds the deactivation warning modal if there are other active plugins using the connection
3993
	 *
3994
	 * @param string $hook The current admin page.
3995
	 *
3996
	 * @return void
3997
	 */
3998
	public function deactivate_dialog( $hook ) {
3999
		if (
4000
			'plugins.php' === $hook
4001
			&& self::is_active()
4002
		) {
4003
4004
			$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4005
4006
			if ( count( $active_plugins_using_connection ) > 1 ) {
4007
4008
				add_thickbox();
4009
4010
				wp_register_script(
4011
					'jp-tracks',
4012
					'//stats.wp.com/w.js',
4013
					array(),
4014
					gmdate( 'YW' ),
4015
					true
4016
				);
4017
4018
				wp_register_script(
4019
					'jp-tracks-functions',
4020
					plugins_url( '_inc/lib/tracks/tracks-callables.js', JETPACK__PLUGIN_FILE ),
4021
					array( 'jp-tracks' ),
4022
					JETPACK__VERSION,
4023
					false
4024
				);
4025
4026
				wp_enqueue_script(
4027
					'jetpack-deactivate-dialog-js',
4028
					Assets::get_file_url_for_environment(
4029
						'_inc/build/jetpack-deactivate-dialog.min.js',
4030
						'_inc/jetpack-deactivate-dialog.js'
4031
					),
4032
					array( 'jquery', 'jp-tracks-functions' ),
4033
					JETPACK__VERSION,
4034
					true
4035
				);
4036
4037
				wp_localize_script(
4038
					'jetpack-deactivate-dialog-js',
4039
					'deactivate_dialog',
4040
					array(
4041
						'title'            => __( 'Deactivate Jetpack', 'jetpack' ),
4042
						'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4043
						'tracksUserData'   => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4044
					)
4045
				);
4046
4047
				add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4048
4049
				wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4050
			}
4051
		}
4052
	}
4053
4054
	/**
4055
	 * Outputs the content of the deactivation modal
4056
	 *
4057
	 * @return void
4058
	 */
4059
	public function deactivate_dialog_content() {
4060
		$active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4061
		unset( $active_plugins_using_connection['jetpack'] );
4062
		$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 4060 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...
4063
	}
4064
4065
	/**
4066
	 * Filters the login URL to include the registration flow in case the user isn't logged in.
4067
	 *
4068
	 * @param string $login_url The wp-login URL.
4069
	 * @param string $redirect  URL to redirect users after logging in.
4070
	 * @since Jetpack 8.4
4071
	 * @return string
4072
	 */
4073
	public function login_url( $login_url, $redirect ) {
4074
		parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4075
		if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4076
			$login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4077
		}
4078
		return $login_url;
4079
	}
4080
4081
	/**
4082
	 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4083
	 *
4084
	 * @since Jetpack 8.4
4085
	 */
4086
	public function login_init() {
4087
		// phpcs:ignore WordPress.Security.NonceVerification
4088
		if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4089
			add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4090
			wp_safe_redirect(
4091
				add_query_arg(
4092
					array(
4093
						'forceInstall' => 1,
4094
						'url'          => rawurlencode( get_site_url() ),
4095
					),
4096
					// @todo provide way to go to specific calypso env.
4097
					self::get_calypso_host() . 'jetpack/connect'
4098
				)
4099
			);
4100
			exit;
4101
		}
4102
	}
4103
4104
	/*
4105
	 * Registration flow:
4106
	 * 1 - ::admin_page_load() action=register
4107
	 * 2 - ::try_registration()
4108
	 * 3 - ::register()
4109
	 *     - Creates jetpack_register option containing two secrets and a timestamp
4110
	 *     - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4111
	 *       siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4112
	 *     - That request to jetpack.wordpress.com does not immediately respond.  It first makes a request BACK to this site's
4113
	 *       xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4114
	 *     - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4115
	 *     - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4116
	 *       jetpack_id, jetpack_secret, jetpack_public
4117
	 *     - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4118
	 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4119
	 * 5 - user logs in with WP.com account
4120
	 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4121
	 *		- Manager::authorize()
4122
	 *		- Manager::get_token()
4123
	 *		- GET https://jetpack.wordpress.com/jetpack.token/1/ with
4124
	 *        client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4125
	 *			- which responds with access_token, token_type, scope
4126
	 *		- Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4127
	 *		- Jetpack::activate_default_modules()
4128
	 *     		- Deactivates deprecated plugins
4129
	 *     		- Activates all default modules
4130
	 *		- Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4131
	 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4132
	 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4133
	 *     Done!
4134
	 */
4135
4136
	/**
4137
	 * Handles the page load events for the Jetpack admin page
4138
	 */
4139
	function admin_page_load() {
4140
		$error = false;
4141
4142
		// Make sure we have the right body class to hook stylings for subpages off of.
4143
		add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4144
4145
		if ( ! empty( $_GET['jetpack_restate'] ) ) {
4146
			// Should only be used in intermediate redirects to preserve state across redirects
4147
			self::restate();
4148
		}
4149
4150
		if ( isset( $_GET['connect_url_redirect'] ) ) {
4151
			// @todo: Add validation against a known allowed list.
4152
			$from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4153
			// User clicked in the iframe to link their accounts
4154
			if ( ! self::is_user_connected() ) {
4155
				$redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4156
4157
				add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4158
				$connect_url = $this->build_connect_url( true, $redirect, $from );
4159
				remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4160
4161
				if ( isset( $_GET['notes_iframe'] ) ) {
4162
					$connect_url .= '&notes_iframe';
4163
				}
4164
				wp_redirect( $connect_url );
4165
				exit;
4166
			} else {
4167
				if ( ! isset( $_GET['calypso_env'] ) ) {
4168
					self::state( 'message', 'already_authorized' );
4169
					wp_safe_redirect( self::admin_url() );
4170
					exit;
4171
				} else {
4172
					$connect_url  = $this->build_connect_url( true, false, $from );
4173
					$connect_url .= '&already_authorized=true';
4174
					wp_redirect( $connect_url );
4175
					exit;
4176
				}
4177
			}
4178
		}
4179
4180
		if ( isset( $_GET['action'] ) ) {
4181
			switch ( $_GET['action'] ) {
4182
				case 'authorize':
4183
					_doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4184
					( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4185
					exit;
4186
				case 'register':
4187
					if ( ! current_user_can( 'jetpack_connect' ) ) {
4188
						$error = 'cheatin';
4189
						break;
4190
					}
4191
					check_admin_referer( 'jetpack-register' );
4192
					self::log( 'register' );
4193
					self::maybe_set_version_option();
4194
					$registered = self::try_registration();
4195
					if ( is_wp_error( $registered ) ) {
4196
						$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...
4197
						self::state( 'error', $error );
4198
						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...
4199
4200
						/**
4201
						 * Jetpack registration Error.
4202
						 *
4203
						 * @since 7.5.0
4204
						 *
4205
						 * @param string|int $error The error code.
4206
						 * @param \WP_Error $registered The error object.
4207
						 */
4208
						do_action( 'jetpack_connection_register_fail', $error, $registered );
4209
						break;
4210
					}
4211
4212
					$from     = isset( $_GET['from'] ) ? $_GET['from'] : false;
4213
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4214
4215
					/**
4216
					 * Jetpack registration Success.
4217
					 *
4218
					 * @since 7.5.0
4219
					 *
4220
					 * @param string $from 'from' GET parameter;
4221
					 */
4222
					do_action( 'jetpack_connection_register_success', $from );
4223
4224
					$url = $this->build_connect_url( true, $redirect, $from );
4225
4226
					if ( ! empty( $_GET['onboarding'] ) ) {
4227
						$url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4228
					}
4229
4230
					if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4231
						$url = add_query_arg( 'auth_approved', 'true', $url );
4232
					}
4233
4234
					wp_redirect( $url );
4235
					exit;
4236
				case 'activate':
4237
					if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4238
						$error = 'cheatin';
4239
						break;
4240
					}
4241
4242
					$module = stripslashes( $_GET['module'] );
4243
					check_admin_referer( "jetpack_activate-$module" );
4244
					self::log( 'activate', $module );
4245
					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...
4246
						self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4247
					}
4248
					// The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4249
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4250
					exit;
4251
				case 'activate_default_modules':
4252
					check_admin_referer( 'activate_default_modules' );
4253
					self::log( 'activate_default_modules' );
4254
					self::restate();
4255
					$min_version   = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4256
					$max_version   = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4257
					$other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4258
					self::activate_default_modules( $min_version, $max_version, $other_modules );
4259
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4260
					exit;
4261
				case 'disconnect':
4262
					if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4263
						$error = 'cheatin';
4264
						break;
4265
					}
4266
4267
					check_admin_referer( 'jetpack-disconnect' );
4268
					self::log( 'disconnect' );
4269
					self::disconnect();
4270
					wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4271
					exit;
4272
				case 'reconnect':
4273
					if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4274
						$error = 'cheatin';
4275
						break;
4276
					}
4277
4278
					check_admin_referer( 'jetpack-reconnect' );
4279
					self::log( 'reconnect' );
4280
					$this->disconnect();
4281
					wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4282
					exit;
4283 View Code Duplication
				case 'deactivate':
4284
					if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4285
						$error = 'cheatin';
4286
						break;
4287
					}
4288
4289
					$modules = stripslashes( $_GET['module'] );
4290
					check_admin_referer( "jetpack_deactivate-$modules" );
4291
					foreach ( explode( ',', $modules ) as $module ) {
4292
						self::log( 'deactivate', $module );
4293
						self::deactivate_module( $module );
4294
						self::state( 'message', 'module_deactivated' );
4295
					}
4296
					self::state( 'module', $modules );
4297
					wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4298
					exit;
4299
				case 'unlink':
4300
					$redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4301
					check_admin_referer( 'jetpack-unlink' );
4302
					self::log( 'unlink' );
4303
					Connection_Manager::disconnect_user();
4304
					self::state( 'message', 'unlinked' );
4305
					if ( 'sub-unlink' == $redirect ) {
4306
						wp_safe_redirect( admin_url() );
4307
					} else {
4308
						wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4309
					}
4310
					exit;
4311
				case 'onboard':
4312
					if ( ! current_user_can( 'manage_options' ) ) {
4313
						wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4314
					} else {
4315
						self::create_onboarding_token();
4316
						$url = $this->build_connect_url( true );
4317
4318
						if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4319
							$url = add_query_arg( 'onboarding', $token, $url );
4320
						}
4321
4322
						$calypso_env = $this->get_calypso_env();
4323
						if ( ! empty( $calypso_env ) ) {
4324
							$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4325
						}
4326
4327
						wp_redirect( $url );
4328
						exit;
4329
					}
4330
					exit;
4331
				default:
4332
					/**
4333
					 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4334
					 *
4335
					 * @since 2.6.0
4336
					 *
4337
					 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4338
					 */
4339
					do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4340
			}
4341
		}
4342
4343
		if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4344
			self::activate_new_modules( true );
4345
		}
4346
4347
		$message_code = self::state( 'message' );
4348
		if ( self::state( 'optin-manage' ) ) {
4349
			$activated_manage = $message_code;
4350
			$message_code     = 'jetpack-manage';
4351
		}
4352
4353
		switch ( $message_code ) {
4354
			case 'jetpack-manage':
4355
				$sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4356
				// translators: %s is the URL to the "Sites" panel on wordpress.com.
4357
				$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>';
4358
				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...
4359
					$this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4360
				}
4361
				break;
4362
4363
		}
4364
4365
		$deactivated_plugins = self::state( 'deactivated_plugins' );
4366
4367
		if ( ! empty( $deactivated_plugins ) ) {
4368
			$deactivated_plugins = explode( ',', $deactivated_plugins );
4369
			$deactivated_titles  = array();
4370
			foreach ( $deactivated_plugins as $deactivated_plugin ) {
4371
				if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4372
					continue;
4373
				}
4374
4375
				$deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4376
			}
4377
4378
			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...
4379
				if ( $this->message ) {
4380
					$this->message .= "<br /><br />\n";
4381
				}
4382
4383
				$this->message .= wp_sprintf(
4384
					_n(
4385
						'Jetpack contains the most recent version of the old %l plugin.',
4386
						'Jetpack contains the most recent versions of the old %l plugins.',
4387
						count( $deactivated_titles ),
4388
						'jetpack'
4389
					),
4390
					$deactivated_titles
4391
				);
4392
4393
				$this->message .= "<br />\n";
4394
4395
				$this->message .= _n(
4396
					'The old version has been deactivated and can be removed from your site.',
4397
					'The old versions have been deactivated and can be removed from your site.',
4398
					count( $deactivated_titles ),
4399
					'jetpack'
4400
				);
4401
			}
4402
		}
4403
4404
		$this->privacy_checks = self::state( 'privacy_checks' );
4405
4406
		if ( $this->message || $this->error || $this->privacy_checks ) {
4407
			add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4408
		}
4409
4410
		add_filter( 'jetpack_short_module_description', 'wptexturize' );
4411
	}
4412
4413
	function admin_notices() {
4414
4415
		if ( $this->error ) {
4416
			?>
4417
<div id="message" class="jetpack-message jetpack-err">
4418
	<div class="squeezer">
4419
		<h2>
4420
			<?php
4421
			echo wp_kses(
4422
				$this->error,
4423
				array(
4424
					'a'      => array( 'href' => array() ),
4425
					'small'  => true,
4426
					'code'   => true,
4427
					'strong' => true,
4428
					'br'     => true,
4429
					'b'      => true,
4430
				)
4431
			);
4432
			?>
4433
			</h2>
4434
			<?php	if ( $desc = self::state( 'error_description' ) ) : ?>
4435
		<p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4436
<?php	endif; ?>
4437
	</div>
4438
</div>
4439
			<?php
4440
		}
4441
4442
		if ( $this->message ) {
4443
			?>
4444
<div id="message" class="jetpack-message">
4445
	<div class="squeezer">
4446
		<h2>
4447
			<?php
4448
			echo wp_kses(
4449
				$this->message,
4450
				array(
4451
					'strong' => array(),
4452
					'a'      => array( 'href' => true ),
4453
					'br'     => true,
4454
				)
4455
			);
4456
			?>
4457
			</h2>
4458
	</div>
4459
</div>
4460
			<?php
4461
		}
4462
4463
		if ( $this->privacy_checks ) :
4464
			$module_names = $module_slugs = array();
4465
4466
			$privacy_checks = explode( ',', $this->privacy_checks );
4467
			$privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4468
			foreach ( $privacy_checks as $module_slug ) {
4469
				$module = self::get_module( $module_slug );
4470
				if ( ! $module ) {
4471
					continue;
4472
				}
4473
4474
				$module_slugs[] = $module_slug;
4475
				$module_names[] = "<strong>{$module['name']}</strong>";
4476
			}
4477
4478
			$module_slugs = join( ',', $module_slugs );
4479
			?>
4480
<div id="message" class="jetpack-message jetpack-err">
4481
	<div class="squeezer">
4482
		<h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4483
		<p>
4484
			<?php
4485
			echo wp_kses(
4486
				wptexturize(
4487
					wp_sprintf(
4488
						_nx(
4489
							"Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4490
							"Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4491
							count( $privacy_checks ),
4492
							'%l = list of Jetpack module/feature names',
4493
							'jetpack'
4494
						),
4495
						$module_names
4496
					)
4497
				),
4498
				array( 'strong' => true )
4499
			);
4500
4501
			echo "\n<br />\n";
4502
4503
			echo wp_kses(
4504
				sprintf(
4505
					_nx(
4506
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4507
						'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4508
						count( $privacy_checks ),
4509
						'%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4510
						'jetpack'
4511
					),
4512
					wp_nonce_url(
4513
						self::admin_url(
4514
							array(
4515
								'page'   => 'jetpack',
4516
								'action' => 'deactivate',
4517
								'module' => urlencode( $module_slugs ),
4518
							)
4519
						),
4520
						"jetpack_deactivate-$module_slugs"
4521
					),
4522
					esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4523
				),
4524
				array(
4525
					'a' => array(
4526
						'href'  => true,
4527
						'title' => true,
4528
					),
4529
				)
4530
			);
4531
			?>
4532
		</p>
4533
	</div>
4534
</div>
4535
			<?php
4536
endif;
4537
	}
4538
4539
	/**
4540
	 * We can't always respond to a signed XML-RPC request with a
4541
	 * helpful error message. In some circumstances, doing so could
4542
	 * leak information.
4543
	 *
4544
	 * Instead, track that the error occurred via a Jetpack_Option,
4545
	 * and send that data back in the heartbeat.
4546
	 * All this does is increment a number, but it's enough to find
4547
	 * trends.
4548
	 *
4549
	 * @param WP_Error $xmlrpc_error The error produced during
4550
	 *                               signature validation.
4551
	 */
4552
	function track_xmlrpc_error( $xmlrpc_error ) {
4553
		$code = is_wp_error( $xmlrpc_error )
4554
			? $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...
4555
			: 'should-not-happen';
4556
4557
		$xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4558
		if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4559
			// No need to update the option if we already have
4560
			// this code stored.
4561
			return;
4562
		}
4563
		$xmlrpc_errors[ $code ] = true;
4564
4565
		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...
4566
	}
4567
4568
	/**
4569
	 * Initialize the jetpack stats instance only when needed
4570
	 *
4571
	 * @return void
4572
	 */
4573
	private function initialize_stats() {
4574
		if ( is_null( $this->a8c_mc_stats_instance ) ) {
4575
			$this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4576
		}
4577
	}
4578
4579
	/**
4580
	 * Record a stat for later output.  This will only currently output in the admin_footer.
4581
	 */
4582
	function stat( $group, $detail ) {
4583
		$this->initialize_stats();
4584
		$this->a8c_mc_stats_instance->add( $group, $detail );
4585
4586
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4587
		$this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4588
	}
4589
4590
	/**
4591
	 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4592
	 */
4593
	function do_stats( $method = '' ) {
4594
		$this->initialize_stats();
4595
		if ( 'server_side' === $method ) {
4596
			$this->a8c_mc_stats_instance->do_server_side_stats();
4597
		} else {
4598
			$this->a8c_mc_stats_instance->do_stats();
4599
		}
4600
4601
		// Keep a local copy for backward compatibility (there are some direct checks on this).
4602
		$this->stats = array();
4603
	}
4604
4605
	/**
4606
	 * Runs stats code for a one-off, server-side.
4607
	 *
4608
	 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4609
	 *
4610
	 * @return bool If it worked.
4611
	 */
4612
	static function do_server_side_stat( $args ) {
4613
		$url                   = self::build_stats_url( $args );
4614
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4615
		return $a8c_mc_stats_instance->do_server_side_stat( $url );
4616
	}
4617
4618
	/**
4619
	 * Builds the stats url.
4620
	 *
4621
	 * @param $args array|string The arguments to append to the URL.
4622
	 *
4623
	 * @return string The URL to be pinged.
4624
	 */
4625
	static function build_stats_url( $args ) {
4626
4627
		$a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4628
		return $a8c_mc_stats_instance->build_stats_url( $args );
4629
4630
	}
4631
4632
	/**
4633
	 * Get the role of the current user.
4634
	 *
4635
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_current_user_to_role() instead.
4636
	 *
4637
	 * @access public
4638
	 * @static
4639
	 *
4640
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
4641
	 */
4642
	public static function translate_current_user_to_role() {
4643
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4644
4645
		$roles = new Roles();
4646
		return $roles->translate_current_user_to_role();
4647
	}
4648
4649
	/**
4650
	 * Get the role of a particular user.
4651
	 *
4652
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_user_to_role() instead.
4653
	 *
4654
	 * @access public
4655
	 * @static
4656
	 *
4657
	 * @param \WP_User $user User object.
4658
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
4659
	 */
4660
	public static function translate_user_to_role( $user ) {
4661
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4662
4663
		$roles = new Roles();
4664
		return $roles->translate_user_to_role( $user );
4665
	}
4666
4667
	/**
4668
	 * Get the minimum capability for a role.
4669
	 *
4670
	 * @deprecated 7.6 Use Automattic\Jetpack\Roles::translate_role_to_cap() instead.
4671
	 *
4672
	 * @access public
4673
	 * @static
4674
	 *
4675
	 * @param string $role Role name.
4676
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
4677
	 */
4678
	public static function translate_role_to_cap( $role ) {
4679
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
4680
4681
		$roles = new Roles();
4682
		return $roles->translate_role_to_cap( $role );
4683
	}
4684
4685
	/**
4686
	 * Sign a user role with the master access token.
4687
	 * If not specified, will default to the current user.
4688
	 *
4689
	 * @deprecated since 7.7
4690
	 * @see Automattic\Jetpack\Connection\Manager::sign_role()
4691
	 *
4692
	 * @access public
4693
	 * @static
4694
	 *
4695
	 * @param string $role    User role.
4696
	 * @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...
4697
	 * @return string Signed user role.
4698
	 */
4699
	public static function sign_role( $role, $user_id = null ) {
4700
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::sign_role' );
4701
		return self::connection()->sign_role( $role, $user_id );
4702
	}
4703
4704
	/**
4705
	 * Builds a URL to the Jetpack connection auth page
4706
	 *
4707
	 * @since 3.9.5
4708
	 *
4709
	 * @param bool        $raw If true, URL will not be escaped.
4710
	 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4711
	 *                              If string, will be a custom redirect.
4712
	 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4713
	 * @param bool        $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4714
	 *
4715
	 * @return string Connect URL
4716
	 */
4717
	function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4718
		$site_id    = Jetpack_Options::get_option( 'id' );
4719
		$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...
4720
4721
		if ( $register || ! $blog_token || ! $site_id ) {
4722
			$url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4723
4724
			if ( ! empty( $redirect ) ) {
4725
				$url = add_query_arg(
4726
					'redirect',
4727
					urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4728
					$url
4729
				);
4730
			}
4731
4732
			if ( is_network_admin() ) {
4733
				$url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4734
			}
4735
4736
			$calypso_env = self::get_calypso_env();
4737
4738
			if ( ! empty( $calypso_env ) ) {
4739
				$url = add_query_arg( 'calypso_env', $calypso_env, $url );
4740
			}
4741
		} else {
4742
4743
			// Let's check the existing blog token to see if we need to re-register. We only check once per minute
4744
			// because otherwise this logic can get us in to a loop.
4745
			$last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4746
			if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4747
				Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4748
4749
				$response = Client::wpcom_json_api_request_as_blog(
4750
					sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4751
					'1.1'
4752
				);
4753
4754
				if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4755
4756
					// Generating a register URL instead to refresh the existing token
4757
					return $this->build_connect_url( $raw, $redirect, $from, true );
4758
				}
4759
			}
4760
4761
			$url = $this->build_authorize_url( $redirect );
0 ignored issues
show
Bug introduced by
It seems like $redirect defined by parameter $redirect on line 4717 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...
4762
		}
4763
4764
		if ( $from ) {
4765
			$url = add_query_arg( 'from', $from, $url );
4766
		}
4767
4768
		$url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4769
		/**
4770
		 * Filter the URL used when connecting a user to a WordPress.com account.
4771
		 *
4772
		 * @since 8.1.0
4773
		 *
4774
		 * @param string $url Connection URL.
4775
		 * @param bool   $raw If true, URL will not be escaped.
4776
		 */
4777
		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...
4778
	}
4779
4780
	public static function build_authorize_url( $redirect = false, $iframe = false ) {
4781
4782
		add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4783
		add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4784
4785
		if ( $iframe ) {
4786
			add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4787
		}
4788
4789
		$c8n = self::connection();
4790
		$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...
4791
4792
		remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4793
		remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4794
4795
		if ( $iframe ) {
4796
			remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4797
		}
4798
4799
		/**
4800
		 * Filter the URL used when authorizing a user to a WordPress.com account.
4801
		 *
4802
		 * @since 8.9.0
4803
		 *
4804
		 * @param string $url Connection URL.
4805
		 */
4806
		return apply_filters( 'jetpack_build_authorize_url', $url );
4807
	}
4808
4809
	/**
4810
	 * Filters the connection URL parameter array.
4811
	 *
4812
	 * @param array $args default URL parameters used by the package.
4813
	 * @return array the modified URL arguments array.
4814
	 */
4815
	public static function filter_connect_request_body( $args ) {
4816
		if (
4817
			Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4818
			&& include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4819
		) {
4820
			$gp_locale      = GP_Locales::by_field( 'wp_locale', get_locale() );
4821
			$args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4822
				? $gp_locale->slug
4823
				: '';
4824
		}
4825
4826
		$tracking        = new Tracking();
4827
		$tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4828
4829
		$args = array_merge(
4830
			$args,
4831
			array(
4832
				'_ui' => $tracks_identity['_ui'],
4833
				'_ut' => $tracks_identity['_ut'],
4834
			)
4835
		);
4836
4837
		$calypso_env = self::get_calypso_env();
4838
4839
		if ( ! empty( $calypso_env ) ) {
4840
			$args['calypso_env'] = $calypso_env;
4841
		}
4842
4843
		return $args;
4844
	}
4845
4846
	/**
4847
	 * Filters the URL that will process the connection data. It can be different from the URL
4848
	 * that we send the user to after everything is done.
4849
	 *
4850
	 * @param String $processing_url the default redirect URL used by the package.
4851
	 * @return String the modified URL.
4852
	 *
4853
	 * @deprecated since Jetpack 9.5.0
4854
	 */
4855
	public static function filter_connect_processing_url( $processing_url ) {
4856
		_deprecated_function( __METHOD__, 'jetpack-9.5' );
4857
4858
		$processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
4859
		return $processing_url;
4860
	}
4861
4862
	/**
4863
	 * Filters the redirection URL that is used for connect requests. The redirect
4864
	 * URL should return the user back to the Jetpack console.
4865
	 *
4866
	 * @param String $redirect the default redirect URL used by the package.
4867
	 * @return String the modified URL.
4868
	 */
4869
	public static function filter_connect_redirect_url( $redirect ) {
4870
		$jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
4871
		$redirect           = $redirect
4872
			? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
4873
			: $jetpack_admin_page;
4874
4875
		if ( isset( $_REQUEST['is_multisite'] ) ) {
4876
			$redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
4877
		}
4878
4879
		return $redirect;
4880
	}
4881
4882
	/**
4883
	 * This action fires at the beginning of the Manager::authorize method.
4884
	 */
4885
	public static function authorize_starting() {
4886
		$jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4887
		// Checking if site has been active/connected previously before recording unique connection.
4888
		if ( ! $jetpack_unique_connection ) {
4889
			// jetpack_unique_connection option has never been set.
4890
			$jetpack_unique_connection = array(
4891
				'connected'    => 0,
4892
				'disconnected' => 0,
4893
				'version'      => '3.6.1',
4894
			);
4895
4896
			update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4897
4898
			// Track unique connection.
4899
			$jetpack = self::init();
4900
4901
			$jetpack->stat( 'connections', 'unique-connection' );
4902
			$jetpack->do_stats( 'server_side' );
4903
		}
4904
4905
		// Increment number of times connected.
4906
		$jetpack_unique_connection['connected'] += 1;
4907
		Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4908
	}
4909
4910
	/**
4911
	 * This action fires at the end of the Manager::authorize method when a secondary user is
4912
	 * linked.
4913
	 */
4914
	public static function authorize_ending_linked() {
4915
		// Don't activate anything since we are just connecting a user.
4916
		self::state( 'message', 'linked' );
4917
	}
4918
4919
	/**
4920
	 * This action fires at the end of the Manager::authorize method when the master user is
4921
	 * authorized.
4922
	 *
4923
	 * @param array $data The request data.
4924
	 */
4925
	public static function authorize_ending_authorized( $data ) {
4926
		// If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
4927
		self::invalidate_onboarding_token();
4928
4929
		// If redirect_uri is SSO, ensure SSO module is enabled.
4930
		parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4931
4932
		/** This filter is documented in class.jetpack-cli.php */
4933
		$jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4934
4935
		$activate_sso = (
4936
			isset( $redirect_options['action'] ) &&
4937
			'jetpack-sso' === $redirect_options['action'] &&
4938
			$jetpack_start_enable_sso
4939
		);
4940
4941
		$do_redirect_on_error = ( 'client' === $data['auth_type'] );
4942
4943
		self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4944
	}
4945
4946
	/**
4947
	 * This action fires at the end of the REST_Connector connection_reconnect method when the
4948
	 * reconnect process is completed.
4949
	 * Note that this currently only happens when we don't need the user to re-authorize
4950
	 * their WP.com account, eg in cases where we are restoring a connection with
4951
	 * unhealthy blog token.
4952
	 */
4953
	public static function reconnection_completed() {
4954
		self::state( 'message', 'reconnection_completed' );
4955
	}
4956
4957
	/**
4958
	 * Get our assumed site creation date.
4959
	 * Calculated based on the earlier date of either:
4960
	 * - Earliest admin user registration date.
4961
	 * - Earliest date of post of any post type.
4962
	 *
4963
	 * @since 7.2.0
4964
	 * @deprecated since 7.8.0
4965
	 *
4966
	 * @return string Assumed site creation date and time.
4967
	 */
4968
	public static function get_assumed_site_creation_date() {
4969
		_deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
4970
		return self::connection()->get_assumed_site_creation_date();
4971
	}
4972
4973 View Code Duplication
	public static function apply_activation_source_to_args( &$args ) {
4974
		list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4975
4976
		if ( $activation_source_name ) {
4977
			$args['_as'] = urlencode( $activation_source_name );
4978
		}
4979
4980
		if ( $activation_source_keyword ) {
4981
			$args['_ak'] = urlencode( $activation_source_keyword );
4982
		}
4983
	}
4984
4985
	function build_reconnect_url( $raw = false ) {
4986
		$url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4987
		return $raw ? $url : esc_url( $url );
4988
	}
4989
4990
	public static function admin_url( $args = null ) {
4991
		$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...
4992
		$url  = add_query_arg( $args, admin_url( 'admin.php' ) );
4993
		return $url;
4994
	}
4995
4996
	public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4997
		$actionurl = str_replace( '&amp;', '&', $actionurl );
4998
		return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4999
	}
5000
5001
	function dismiss_jetpack_notice() {
5002
5003
		if ( ! isset( $_GET['jetpack-notice'] ) ) {
5004
			return;
5005
		}
5006
5007
		switch ( $_GET['jetpack-notice'] ) {
5008
			case 'dismiss':
5009
				if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5010
5011
					require_once ABSPATH . 'wp-admin/includes/plugin.php';
5012
					deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5013
					wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5014
				}
5015
				break;
5016
		}
5017
	}
5018
5019
	public static function sort_modules( $a, $b ) {
5020
		if ( $a['sort'] == $b['sort'] ) {
5021
			return 0;
5022
		}
5023
5024
		return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5025
	}
5026
5027
	function ajax_recheck_ssl() {
5028
		check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5029
		$result = self::permit_ssl( true );
5030
		wp_send_json(
5031
			array(
5032
				'enabled' => $result,
5033
				'message' => get_transient( 'jetpack_https_test_message' ),
5034
			)
5035
		);
5036
	}
5037
5038
	/* Client API */
5039
5040
	/**
5041
	 * Returns the requested Jetpack API URL
5042
	 *
5043
	 * @deprecated since 7.7
5044
	 * @return string
5045
	 */
5046
	public static function api_url( $relative_url ) {
5047
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5048
		$connection = self::connection();
5049
		return $connection->api_url( $relative_url );
5050
	}
5051
5052
	/**
5053
	 * @deprecated 8.0
5054
	 *
5055
	 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5056
	 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5057
	 */
5058
	public static function fix_url_for_bad_hosts( $url ) {
5059
		_deprecated_function( __METHOD__, 'jetpack-8.0' );
5060
		return $url;
5061
	}
5062
5063
	public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5064
		// Default to a blog token.
5065
		$token_type = 'blog';
5066
5067
		// Let's see if this is onboarding. In such case, use user token type and the provided user id.
5068
		if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5069
			if ( ! empty( $_GET['onboarding'] ) ) {
5070
				$jpo = $_GET;
5071
			} else {
5072
				$jpo = json_decode( $request_data, true );
5073
			}
5074
5075
			$jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5076
			$jpo_user  = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5077
5078
			if (
5079
				isset( $jpo_user )
5080
				&& isset( $jpo_token )
5081
				&& is_email( $jpo_user )
5082
				&& ctype_alnum( $jpo_token )
5083
				&& isset( $_GET['rest_route'] )
5084
				&& self::validate_onboarding_token_action(
5085
					$jpo_token,
5086
					$_GET['rest_route']
5087
				)
5088
			) {
5089
				$jp_user = get_user_by( 'email', $jpo_user );
5090
				if ( is_a( $jp_user, 'WP_User' ) ) {
5091
					wp_set_current_user( $jp_user->ID );
5092
					$user_can = is_multisite()
5093
						? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5094
						: current_user_can( 'manage_options' );
5095
					if ( $user_can ) {
5096
						$token_type              = 'user';
5097
						$token->external_user_id = $jp_user->ID;
5098
					}
5099
				}
5100
			}
5101
5102
			$token_data['type']    = $token_type;
5103
			$token_data['user_id'] = $token->external_user_id;
5104
		}
5105
5106
		return $token_data;
5107
	}
5108
5109
	/**
5110
	 * Create a random secret for validating onboarding payload
5111
	 *
5112
	 * @return string Secret token
5113
	 */
5114
	public static function create_onboarding_token() {
5115
		if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5116
			$token = wp_generate_password( 32, false );
5117
			Jetpack_Options::update_option( 'onboarding', $token );
5118
		}
5119
5120
		return $token;
5121
	}
5122
5123
	/**
5124
	 * Remove the onboarding token
5125
	 *
5126
	 * @return bool True on success, false on failure
5127
	 */
5128
	public static function invalidate_onboarding_token() {
5129
		return Jetpack_Options::delete_option( 'onboarding' );
5130
	}
5131
5132
	/**
5133
	 * Validate an onboarding token for a specific action
5134
	 *
5135
	 * @return boolean True if token/action pair is accepted, false if not
5136
	 */
5137
	public static function validate_onboarding_token_action( $token, $action ) {
5138
		// Compare tokens, bail if tokens do not match
5139
		if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5140
			return false;
5141
		}
5142
5143
		// List of valid actions we can take
5144
		$valid_actions = array(
5145
			'/jetpack/v4/settings',
5146
		);
5147
5148
		// Only allow valid actions.
5149
		if ( ! in_array( $action, $valid_actions ) ) {
5150
			return false;
5151
		}
5152
5153
		return true;
5154
	}
5155
5156
	/**
5157
	 * Checks to see if the URL is using SSL to connect with Jetpack
5158
	 *
5159
	 * @since 2.3.3
5160
	 * @return boolean
5161
	 */
5162
	public static function permit_ssl( $force_recheck = false ) {
5163
		// Do some fancy tests to see if ssl is being supported
5164
		if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5165
			$message = '';
5166
			if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5167
				$ssl = 0;
5168
			} else {
5169
				$ssl = 1;
5170
5171
				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5172
					$ssl     = 0;
5173
					$message = __( 'WordPress reports no SSL support', 'jetpack' );
5174
				} else {
5175
					$response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5176
					if ( is_wp_error( $response ) ) {
5177
						$ssl     = 0;
5178
						$message = __( 'WordPress reports no SSL support', 'jetpack' );
5179
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5180
						$ssl     = 0;
5181
						$message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5182
					}
5183
				}
5184
			}
5185
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5186
			set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5187
		}
5188
5189
		return (bool) $ssl;
5190
	}
5191
5192
	/*
5193
	 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5194
	 */
5195
	public function alert_auto_ssl_fail() {
5196
		if ( ! current_user_can( 'manage_options' ) ) {
5197
			return;
5198
		}
5199
5200
		$ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5201
		?>
5202
5203
		<div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5204
			<div class="jp-banner__content">
5205
				<h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5206
				<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>
5207
				<p>
5208
					<?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5209
					<a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5210
					<span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5211
				</p>
5212
				<p>
5213
					<?php
5214
					printf(
5215
						__( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5216
						esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5217
						esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5218
					);
5219
					?>
5220
				</p>
5221
			</div>
5222
		</div>
5223
		<style>
5224
			#jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5225
		</style>
5226
		<script type="text/javascript">
5227
			jQuery( document ).ready( function( $ ) {
5228
				$( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5229
					var $this = $( this );
5230
					$this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5231
					$( '#jetpack-recheck-ssl-output' ).html( '' );
5232
					e.preventDefault();
5233
					var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5234
					$.post( ajaxurl, data )
5235
					  .done( function( response ) {
5236
						  if ( response.enabled ) {
5237
							  $( '#jetpack-ssl-warning' ).hide();
5238
						  } else {
5239
							  this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5240
							  $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5241
						  }
5242
					  }.bind( $this ) );
5243
				} );
5244
			} );
5245
		</script>
5246
5247
		<?php
5248
	}
5249
5250
	/**
5251
	 * Returns the Jetpack XML-RPC API
5252
	 *
5253
	 * @deprecated 8.0 Use Connection_Manager instead.
5254
	 * @return string
5255
	 */
5256
	public static function xmlrpc_api_url() {
5257
		_deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5258
		return self::connection()->xmlrpc_api_url();
5259
	}
5260
5261
	/**
5262
	 * Returns the connection manager object.
5263
	 *
5264
	 * @return Automattic\Jetpack\Connection\Manager
5265
	 */
5266
	public static function connection() {
5267
		$jetpack = static::init();
5268
5269
		// If the connection manager hasn't been instantiated, do that now.
5270
		if ( ! $jetpack->connection_manager ) {
5271
			$jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5272
		}
5273
5274
		return $jetpack->connection_manager;
5275
	}
5276
5277
	/**
5278
	 * Creates two secret tokens and the end of life timestamp for them.
5279
	 *
5280
	 * Note these tokens are unique per call, NOT static per site for connecting.
5281
	 *
5282
	 * @since 2.6
5283
	 * @param String  $action  The action name.
5284
	 * @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...
5285
	 * @param Integer $exp     Expiration time in seconds.
5286
	 * @return array
5287
	 */
5288
	public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5289
		return self::connection()->generate_secrets( $action, $user_id, $exp );
5290
	}
5291
5292
	public static function get_secrets( $action, $user_id ) {
5293
		$secrets = self::connection()->get_secrets( $action, $user_id );
5294
5295
		if ( Connection_Manager::SECRETS_MISSING === $secrets ) {
5296
			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...
5297
		}
5298
5299
		if ( Connection_Manager::SECRETS_EXPIRED === $secrets ) {
5300
			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...
5301
		}
5302
5303
		return $secrets;
5304
	}
5305
5306
	/**
5307
	 * @deprecated 7.5 Use Connection_Manager instead.
5308
	 *
5309
	 * @param $action
5310
	 * @param $user_id
5311
	 */
5312
	public static function delete_secrets( $action, $user_id ) {
5313
		return self::connection()->delete_secrets( $action, $user_id );
5314
	}
5315
5316
	/**
5317
	 * Builds the timeout limit for queries talking with the wpcom servers.
5318
	 *
5319
	 * Based on local php max_execution_time in php.ini
5320
	 *
5321
	 * @since 2.6
5322
	 * @return int
5323
	 * @deprecated
5324
	 **/
5325
	public function get_remote_query_timeout_limit() {
5326
		_deprecated_function( __METHOD__, 'jetpack-5.4' );
5327
		return self::get_max_execution_time();
5328
	}
5329
5330
	/**
5331
	 * Builds the timeout limit for queries talking with the wpcom servers.
5332
	 *
5333
	 * Based on local php max_execution_time in php.ini
5334
	 *
5335
	 * @since 5.4
5336
	 * @return int
5337
	 **/
5338
	public static function get_max_execution_time() {
5339
		$timeout = (int) ini_get( 'max_execution_time' );
5340
5341
		// Ensure exec time set in php.ini
5342
		if ( ! $timeout ) {
5343
			$timeout = 30;
5344
		}
5345
		return $timeout;
5346
	}
5347
5348
	/**
5349
	 * Sets a minimum request timeout, and returns the current timeout
5350
	 *
5351
	 * @since 5.4
5352
	 **/
5353 View Code Duplication
	public static function set_min_time_limit( $min_timeout ) {
5354
		$timeout = self::get_max_execution_time();
5355
		if ( $timeout < $min_timeout ) {
5356
			$timeout = $min_timeout;
5357
			set_time_limit( $timeout );
5358
		}
5359
		return $timeout;
5360
	}
5361
5362
	/**
5363
	 * Takes the response from the Jetpack register new site endpoint and
5364
	 * verifies it worked properly.
5365
	 *
5366
	 * @since 2.6
5367
	 * @deprecated since 7.7.0
5368
	 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5369
	 **/
5370
	public function validate_remote_register_response() {
5371
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5372
	}
5373
5374
	/**
5375
	 * @return bool|WP_Error
5376
	 */
5377
	public static function register() {
5378
		$tracking = new Tracking();
5379
		$tracking->record_user_event( 'jpc_register_begin' );
5380
5381
		add_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5382
5383
		$connection   = self::connection();
5384
		$registration = $connection->register();
5385
5386
		remove_filter( 'jetpack_register_request_body', array( __CLASS__, 'filter_register_request_body' ) );
5387
5388
		if ( ! $registration || is_wp_error( $registration ) ) {
5389
			return $registration;
5390
		}
5391
5392
		return true;
5393
	}
5394
5395
	/**
5396
	 * Filters the registration request body to include tracking properties.
5397
	 *
5398
	 * @param array $properties
5399
	 * @return array amended properties.
5400
	 */
5401 View Code Duplication
	public static function filter_register_request_body( $properties ) {
5402
		$tracking        = new Tracking();
5403
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5404
5405
		return array_merge(
5406
			$properties,
5407
			array(
5408
				'_ui' => $tracks_identity['_ui'],
5409
				'_ut' => $tracks_identity['_ut'],
5410
			)
5411
		);
5412
	}
5413
5414
	/**
5415
	 * Filters the token request body to include tracking properties.
5416
	 *
5417
	 * @param array $properties
5418
	 * @return array amended properties.
5419
	 */
5420 View Code Duplication
	public static function filter_token_request_body( $properties ) {
5421
		$tracking        = new Tracking();
5422
		$tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5423
5424
		return array_merge(
5425
			$properties,
5426
			array(
5427
				'_ui' => $tracks_identity['_ui'],
5428
				'_ut' => $tracks_identity['_ut'],
5429
			)
5430
		);
5431
	}
5432
5433
	/**
5434
	 * If the db version is showing something other that what we've got now, bump it to current.
5435
	 *
5436
	 * @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...
5437
	 */
5438
	public static function maybe_set_version_option() {
5439
		list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5440
		if ( JETPACK__VERSION != $version ) {
5441
			Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5442
5443
			if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5444
				/** This action is documented in class.jetpack.php */
5445
				do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5446
			}
5447
5448
			return true;
5449
		}
5450
		return false;
5451
	}
5452
5453
	/* Client Server API */
5454
5455
	/**
5456
	 * Loads the Jetpack XML-RPC client.
5457
	 * No longer necessary, as the XML-RPC client will be automagically loaded.
5458
	 *
5459
	 * @deprecated since 7.7.0
5460
	 */
5461
	public static function load_xml_rpc_client() {
5462
		_deprecated_function( __METHOD__, 'jetpack-7.7' );
5463
	}
5464
5465
	/**
5466
	 * Resets the saved authentication state in between testing requests.
5467
	 *
5468
	 * @deprecated since 8.9.0
5469
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5470
	 */
5471
	public function reset_saved_auth_state() {
5472
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5473
		Connection_Rest_Authentication::init()->reset_saved_auth_state();
5474
	}
5475
5476
	/**
5477
	 * Verifies the signature of the current request.
5478
	 *
5479
	 * @deprecated since 7.7.0
5480
	 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5481
	 *
5482
	 * @return false|array
5483
	 */
5484
	public function verify_xml_rpc_signature() {
5485
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5486
		return self::connection()->verify_xml_rpc_signature();
5487
	}
5488
5489
	/**
5490
	 * Verifies the signature of the current request.
5491
	 *
5492
	 * This function has side effects and should not be used. Instead,
5493
	 * use the memoized version `->verify_xml_rpc_signature()`.
5494
	 *
5495
	 * @deprecated since 7.7.0
5496
	 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5497
	 * @internal
5498
	 */
5499
	private function internal_verify_xml_rpc_signature() {
5500
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5501
	}
5502
5503
	/**
5504
	 * Authenticates XML-RPC and other requests from the Jetpack Server.
5505
	 *
5506
	 * @deprecated since 7.7.0
5507
	 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5508
	 *
5509
	 * @param \WP_User|mixed $user     User object if authenticated.
5510
	 * @param string         $username Username.
5511
	 * @param string         $password Password string.
5512
	 * @return \WP_User|mixed Authenticated user or error.
5513
	 */
5514 View Code Duplication
	public function authenticate_jetpack( $user, $username, $password ) {
5515
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5516
5517
		if ( ! $this->connection_manager ) {
5518
			$this->connection_manager = new Connection_Manager();
5519
		}
5520
5521
		return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5522
	}
5523
5524
	/**
5525
	 * Authenticates requests from Jetpack server to WP REST API endpoints.
5526
	 * Uses the existing XMLRPC request signing implementation.
5527
	 *
5528
	 * @deprecated since 8.9.0
5529
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5530
	 */
5531
	function wp_rest_authenticate( $user ) {
5532
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5533
		return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5534
	}
5535
5536
	/**
5537
	 * Report authentication status to the WP REST API.
5538
	 *
5539
	 * @deprecated since 8.9.0
5540
	 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5541
	 *
5542
	 * @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...
5543
	 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5544
	 */
5545
	public function wp_rest_authentication_errors( $value ) {
5546
		_deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5547
		return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5548
	}
5549
5550
	/**
5551
	 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5552
	 * Capture it here so we can verify the signature later.
5553
	 *
5554
	 * @deprecated since 7.7.0
5555
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5556
	 *
5557
	 * @param array $methods XMLRPC methods.
5558
	 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5559
	 */
5560 View Code Duplication
	public function xmlrpc_methods( $methods ) {
5561
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5562
5563
		if ( ! $this->connection_manager ) {
5564
			$this->connection_manager = new Connection_Manager();
5565
		}
5566
5567
		return $this->connection_manager->xmlrpc_methods( $methods );
5568
	}
5569
5570
	/**
5571
	 * Register additional public XMLRPC methods.
5572
	 *
5573
	 * @deprecated since 7.7.0
5574
	 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5575
	 *
5576
	 * @param array $methods Public XMLRPC methods.
5577
	 * @return array Public XMLRPC methods, with the getOptions one.
5578
	 */
5579 View Code Duplication
	public function public_xmlrpc_methods( $methods ) {
5580
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5581
5582
		if ( ! $this->connection_manager ) {
5583
			$this->connection_manager = new Connection_Manager();
5584
		}
5585
5586
		return $this->connection_manager->public_xmlrpc_methods( $methods );
5587
	}
5588
5589
	/**
5590
	 * Handles a getOptions XMLRPC method call.
5591
	 *
5592
	 * @deprecated since 7.7.0
5593
	 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5594
	 *
5595
	 * @param array $args method call arguments.
5596
	 * @return array an amended XMLRPC server options array.
5597
	 */
5598 View Code Duplication
	public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5599
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5600
5601
		if ( ! $this->connection_manager ) {
5602
			$this->connection_manager = new Connection_Manager();
5603
		}
5604
5605
		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...
5606
	}
5607
5608
	/**
5609
	 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5610
	 *
5611
	 * @deprecated since 7.7.0
5612
	 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5613
	 *
5614
	 * @param array $options Standard Core options.
5615
	 * @return array Amended options.
5616
	 */
5617 View Code Duplication
	public function xmlrpc_options( $options ) {
5618
		_deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5619
5620
		if ( ! $this->connection_manager ) {
5621
			$this->connection_manager = new Connection_Manager();
5622
		}
5623
5624
		return $this->connection_manager->xmlrpc_options( $options );
5625
	}
5626
5627
	/**
5628
	 * State is passed via cookies from one request to the next, but never to subsequent requests.
5629
	 * SET: state( $key, $value );
5630
	 * GET: $value = state( $key );
5631
	 *
5632
	 * @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...
5633
	 * @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...
5634
	 * @param bool   $restate private
5635
	 */
5636
	public static function state( $key = null, $value = null, $restate = false ) {
5637
		static $state = array();
5638
		static $path, $domain;
5639
		if ( ! isset( $path ) ) {
5640
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
5641
			$admin_url = self::admin_url();
5642
			$bits      = wp_parse_url( $admin_url );
5643
5644
			if ( is_array( $bits ) ) {
5645
				$path   = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5646
				$domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5647
			} else {
5648
				$path = $domain = null;
5649
			}
5650
		}
5651
5652
		// Extract state from cookies and delete cookies
5653
		if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5654
			$yum = wp_unslash( $_COOKIE['jetpackState'] );
5655
			unset( $_COOKIE['jetpackState'] );
5656
			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...
5657
				if ( strlen( $v ) ) {
5658
					$state[ $k ] = $v;
5659
				}
5660
				setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5661
			}
5662
		}
5663
5664
		if ( $restate ) {
5665
			foreach ( $state as $k => $v ) {
5666
				setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5667
			}
5668
			return;
5669
		}
5670
5671
		// Get a state variable.
5672
		if ( isset( $key ) && ! isset( $value ) ) {
5673
			if ( array_key_exists( $key, $state ) ) {
5674
				return $state[ $key ];
5675
			}
5676
			return null;
5677
		}
5678
5679
		// Set a state variable.
5680
		if ( isset( $key ) && isset( $value ) ) {
5681
			if ( is_array( $value ) && isset( $value[0] ) ) {
5682
				$value = $value[0];
5683
			}
5684
			$state[ $key ] = $value;
5685
			if ( ! headers_sent() ) {
5686
				if ( self::should_set_cookie( $key ) ) {
5687
					setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5688
				}
5689
			}
5690
		}
5691
	}
5692
5693
	public static function restate() {
5694
		self::state( null, null, true );
5695
	}
5696
5697
	/**
5698
	 * Determines whether the jetpackState[$key] value should be added to the
5699
	 * cookie.
5700
	 *
5701
	 * @param string $key The state key.
5702
	 *
5703
	 * @return boolean Whether the value should be added to the cookie.
5704
	 */
5705
	public static function should_set_cookie( $key ) {
5706
		global $current_screen;
5707
		$page = isset( $current_screen->base ) ? $current_screen->base : null;
5708
5709
		if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5710
			return false;
5711
		}
5712
5713
		return true;
5714
	}
5715
5716
	public static function check_privacy( $file ) {
5717
		static $is_site_publicly_accessible = null;
5718
5719
		if ( is_null( $is_site_publicly_accessible ) ) {
5720
			$is_site_publicly_accessible = false;
5721
5722
			$rpc = new Jetpack_IXR_Client();
5723
5724
			$success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5725
			if ( $success ) {
5726
				$response = $rpc->getResponse();
5727
				if ( $response ) {
5728
					$is_site_publicly_accessible = true;
5729
				}
5730
			}
5731
5732
			Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5733
		}
5734
5735
		if ( $is_site_publicly_accessible ) {
5736
			return;
5737
		}
5738
5739
		$module_slug = self::get_module_slug( $file );
5740
5741
		$privacy_checks = self::state( 'privacy_checks' );
5742
		if ( ! $privacy_checks ) {
5743
			$privacy_checks = $module_slug;
5744
		} else {
5745
			$privacy_checks .= ",$module_slug";
5746
		}
5747
5748
		self::state( 'privacy_checks', $privacy_checks );
5749
	}
5750
5751
	/**
5752
	 * Helper method for multicall XMLRPC.
5753
	 *
5754
	 * @deprecated since 8.9.0
5755
	 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5756
	 *
5757
	 * @param ...$args Args for the async_call.
5758
	 */
5759
	public static function xmlrpc_async_call( ...$args ) {
5760
5761
		_deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5762
5763
		global $blog_id;
5764
		static $clients = array();
5765
5766
		$client_blog_id = is_multisite() ? $blog_id : 0;
5767
5768
		if ( ! isset( $clients[ $client_blog_id ] ) ) {
5769
			$clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => Connection_Manager::CONNECTION_OWNER ) );
5770
			if ( function_exists( 'ignore_user_abort' ) ) {
5771
				ignore_user_abort( true );
5772
			}
5773
			add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5774
		}
5775
5776
		if ( ! empty( $args[0] ) ) {
5777
			call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5778
		} elseif ( is_multisite() ) {
5779
			foreach ( $clients as $client_blog_id => $client ) {
5780
				if ( ! $client_blog_id || empty( $client->calls ) ) {
5781
					continue;
5782
				}
5783
5784
				$switch_success = switch_to_blog( $client_blog_id, true );
5785
				if ( ! $switch_success ) {
5786
					continue;
5787
				}
5788
5789
				flush();
5790
				$client->query();
5791
5792
				restore_current_blog();
5793
			}
5794
		} else {
5795
			if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5796
				flush();
5797
				$clients[0]->query();
5798
			}
5799
		}
5800
	}
5801
5802
	/**
5803
	 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5804
	 *
5805
	 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5806
	 *
5807
	 * @param string $url WordPress.com static resource URL.
5808
	 */
5809
	public static function staticize_subdomain( $url ) {
5810
		_deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5811
		return Assets::staticize_subdomain( $url );
5812
	}
5813
5814
	/* JSON API Authorization */
5815
5816
	/**
5817
	 * Handles the login action for Authorizing the JSON API
5818
	 */
5819
	function login_form_json_api_authorization() {
5820
		$this->verify_json_api_authorization_request();
5821
5822
		add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5823
5824
		add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5825
		add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5826
		add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5827
	}
5828
5829
	// Make sure the login form is POSTed to the signed URL so we can reverify the request
5830
	function post_login_form_to_signed_url( $url, $path, $scheme ) {
5831
		if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5832
			return $url;
5833
		}
5834
5835
		$parsed_url = wp_parse_url( $url );
5836
		$url        = strtok( $url, '?' );
5837
		$url        = "$url?{$_SERVER['QUERY_STRING']}";
5838
		if ( ! empty( $parsed_url['query'] ) ) {
5839
			$url .= "&{$parsed_url['query']}";
5840
		}
5841
5842
		return $url;
5843
	}
5844
5845
	// Make sure the POSTed request is handled by the same action
5846
	function preserve_action_in_login_form_for_json_api_authorization() {
5847
		echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5848
		echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
5849
	}
5850
5851
	// If someone logs in to approve API access, store the Access Code in usermeta
5852
	function store_json_api_authorization_token( $user_login, $user ) {
5853
		add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
5854
		add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
5855
		$token = wp_generate_password( 32, false );
5856
		update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
5857
	}
5858
5859
	// Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5860
	function allow_wpcom_public_api_domain( $domains ) {
5861
		$domains[] = 'public-api.wordpress.com';
5862
		return $domains;
5863
	}
5864
5865
	static function is_redirect_encoded( $redirect_url ) {
5866
		return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5867
	}
5868
5869
	// Add all wordpress.com environments to the safe redirect allowed list.
5870
	function allow_wpcom_environments( $domains ) {
5871
		$domains[] = 'wordpress.com';
5872
		$domains[] = 'wpcalypso.wordpress.com';
5873
		$domains[] = 'horizon.wordpress.com';
5874
		$domains[] = 'calypso.localhost';
5875
		return $domains;
5876
	}
5877
5878
	// Add the Access Code details to the public-api.wordpress.com redirect
5879
	function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5880
		return add_query_arg(
5881
			urlencode_deep(
5882
				array(
5883
					'jetpack-code'    => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
5884
					'jetpack-user-id' => (int) $user->ID,
5885
					'jetpack-state'   => $this->json_api_authorization_request['state'],
5886
				)
5887
			),
5888
			$redirect_to
5889
		);
5890
	}
5891
5892
	/**
5893
	 * Verifies the request by checking the signature
5894
	 *
5895
	 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5896
	 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5897
	 *
5898
	 * @param null|array $environment
5899
	 */
5900
	function verify_json_api_authorization_request( $environment = null ) {
5901
		$environment = is_null( $environment )
5902
			? $_REQUEST
5903
			: $environment;
5904
5905
		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...
5906
		$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...
5907
		if ( ! $token || empty( $token->secret ) ) {
5908
			wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
5909
		}
5910
5911
		$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' );
5912
5913
		// Host has encoded the request URL, probably as a result of a bad http => https redirect
5914
		if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
5915
			/**
5916
			 * Jetpack authorisation request Error.
5917
			 *
5918
			 * @since 7.5.0
5919
			 */
5920
			do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
5921
			$die_error = sprintf(
5922
				/* translators: %s is a URL */
5923
				__( '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' ),
5924
				Redirect::get_url( 'jetpack-support-double-encoding' )
5925
			);
5926
		}
5927
5928
		$jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
5929
5930
		if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
5931
			$signature = $jetpack_signature->sign_request(
5932
				$environment['token'],
5933
				$environment['timestamp'],
5934
				$environment['nonce'],
5935
				'',
5936
				'GET',
5937
				$environment['jetpack_json_api_original_query'],
5938
				null,
5939
				true
5940
			);
5941
		} else {
5942
			$signature = $jetpack_signature->sign_current_request(
5943
				array(
5944
					'body'   => null,
5945
					'method' => 'GET',
5946
				)
5947
			);
5948
		}
5949
5950
		if ( ! $signature ) {
5951
			wp_die( $die_error );
5952
		} elseif ( is_wp_error( $signature ) ) {
5953
			wp_die( $die_error );
5954
		} elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
5955
			if ( is_ssl() ) {
5956
				// 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
5957
				$signature = $jetpack_signature->sign_current_request(
5958
					array(
5959
						'scheme' => 'http',
5960
						'body'   => null,
5961
						'method' => 'GET',
5962
					)
5963
				);
5964
				if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
5965
					wp_die( $die_error );
5966
				}
5967
			} else {
5968
				wp_die( $die_error );
5969
			}
5970
		}
5971
5972
		$timestamp = (int) $environment['timestamp'];
5973
		$nonce     = stripslashes( (string) $environment['nonce'] );
5974
5975
		if ( ! $this->connection_manager ) {
5976
			$this->connection_manager = new Connection_Manager();
5977
		}
5978
5979
		if ( ! $this->connection_manager->add_nonce( $timestamp, $nonce ) ) {
5980
			// De-nonce the nonce, at least for 5 minutes.
5981
			// 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)
5982
			$old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
5983
			if ( $old_nonce_time < time() - 300 ) {
5984
				wp_die( __( 'The authorization process expired.  Please go back and try again.', 'jetpack' ) );
5985
			}
5986
		}
5987
5988
		$data         = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
5989
		$data_filters = array(
5990
			'state'        => 'opaque',
5991
			'client_id'    => 'int',
5992
			'client_title' => 'string',
5993
			'client_image' => 'url',
5994
		);
5995
5996
		foreach ( $data_filters as $key => $sanitation ) {
5997
			if ( ! isset( $data->$key ) ) {
5998
				wp_die( $die_error );
5999
			}
6000
6001
			switch ( $sanitation ) {
6002
				case 'int':
6003
					$this->json_api_authorization_request[ $key ] = (int) $data->$key;
6004
					break;
6005
				case 'opaque':
6006
					$this->json_api_authorization_request[ $key ] = (string) $data->$key;
6007
					break;
6008
				case 'string':
6009
					$this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6010
					break;
6011
				case 'url':
6012
					$this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6013
					break;
6014
			}
6015
		}
6016
6017
		if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6018
			wp_die( $die_error );
6019
		}
6020
	}
6021
6022
	function login_message_json_api_authorization( $message ) {
6023
		return '<p class="message">' . sprintf(
6024
			esc_html__( '%s wants to access your site&#8217;s data.  Log in to authorize that access.', 'jetpack' ),
6025
			'<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6026
		) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6027
	}
6028
6029
	/**
6030
	 * Get $content_width, but with a <s>twist</s> filter.
6031
	 */
6032
	public static function get_content_width() {
6033
		$content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6034
			? $GLOBALS['content_width']
6035
			: false;
6036
		/**
6037
		 * Filter the Content Width value.
6038
		 *
6039
		 * @since 2.2.3
6040
		 *
6041
		 * @param string $content_width Content Width value.
6042
		 */
6043
		return apply_filters( 'jetpack_content_width', $content_width );
6044
	}
6045
6046
	/**
6047
	 * Pings the WordPress.com Mirror Site for the specified options.
6048
	 *
6049
	 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6050
	 *
6051
	 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6052
	 */
6053
	public function get_cloud_site_options( $option_names ) {
6054
		$option_names = array_filter( (array) $option_names, 'is_string' );
6055
6056
		$xml = new Jetpack_IXR_Client();
6057
		$xml->query( 'jetpack.fetchSiteOptions', $option_names );
6058
		if ( $xml->isError() ) {
6059
			return array(
6060
				'error_code' => $xml->getErrorCode(),
6061
				'error_msg'  => $xml->getErrorMessage(),
6062
			);
6063
		}
6064
		$cloud_site_options = $xml->getResponse();
6065
6066
		return $cloud_site_options;
6067
	}
6068
6069
	/**
6070
	 * Checks if the site is currently in an identity crisis.
6071
	 *
6072
	 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6073
	 */
6074
	public static function check_identity_crisis() {
6075
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() || ! self::validate_sync_error_idc_option() ) {
6076
			return false;
6077
		}
6078
6079
		return Jetpack_Options::get_option( 'sync_error_idc' );
6080
	}
6081
6082
	/**
6083
	 * Checks whether the home and siteurl specifically are allowed.
6084
	 * Written so that we don't have re-check $key and $value params every time
6085
	 * we want to check if this site is allowed, for example in footer.php
6086
	 *
6087
	 * @since  3.8.0
6088
	 * @return bool True = already allowed False = not on the allowed list.
6089
	 */
6090
	public static function is_staging_site() {
6091
		_deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6092
		return ( new Status() )->is_staging_site();
6093
	}
6094
6095
	/**
6096
	 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6097
	 *
6098
	 * @since 4.4.0
6099
	 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6100
	 *
6101
	 * @return bool
6102
	 */
6103
	public static function validate_sync_error_idc_option() {
6104
		$is_valid = false;
6105
6106
		// Is the site opted in and does the stored sync_error_idc option match what we now generate?
6107
		$sync_error = Jetpack_Options::get_option( 'sync_error_idc' );
6108
		if ( $sync_error && self::sync_idc_optin() ) {
6109
			$local_options = self::get_sync_error_idc_option();
6110
			// Ensure all values are set.
6111
			if ( isset( $sync_error['home'] ) && isset( $local_options['home'] ) && isset( $sync_error['siteurl'] ) && isset( $local_options['siteurl'] ) ) {
6112
6113
				// If the WP.com expected home and siteurl match local home and siteurl it is not valid IDC.
6114
				if (
6115
						isset( $sync_error['wpcom_home'] ) &&
6116
						isset( $sync_error['wpcom_siteurl'] ) &&
6117
						$sync_error['wpcom_home'] === $local_options['home'] &&
6118
						$sync_error['wpcom_siteurl'] === $local_options['siteurl']
6119
				) {
6120
					$is_valid = false;
6121
					// Enable migrate_for_idc so that sync actions are accepted.
6122
					Jetpack_Options::update_option( 'migrate_for_idc', true );
6123
				} elseif ( $sync_error['home'] === $local_options['home'] && $sync_error['siteurl'] === $local_options['siteurl'] ) {
6124
					$is_valid = true;
6125
				}
6126
			}
6127
		}
6128
6129
		/**
6130
		 * Filters whether the sync_error_idc option is valid.
6131
		 *
6132
		 * @since 4.4.0
6133
		 *
6134
		 * @param bool $is_valid If the sync_error_idc is valid or not.
6135
		 */
6136
		$is_valid = (bool) apply_filters( 'jetpack_sync_error_idc_validation', $is_valid );
6137
6138
		if ( ! $is_valid && $sync_error ) {
6139
			// Since the option exists, and did not validate, delete it
6140
			Jetpack_Options::delete_option( 'sync_error_idc' );
6141
		}
6142
6143
		return $is_valid;
6144
	}
6145
6146
	/**
6147
	 * Normalizes a url by doing three things:
6148
	 *  - Strips protocol
6149
	 *  - Strips www
6150
	 *  - Adds a trailing slash
6151
	 *
6152
	 * @since 4.4.0
6153
	 * @param string $url
6154
	 * @return WP_Error|string
6155
	 */
6156
	public static function normalize_url_protocol_agnostic( $url ) {
6157
		$parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6158 View Code Duplication
		if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parsed_url of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false 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...
6159
			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...
6160
		}
6161
6162
		// Strip www and protocols
6163
		$url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6164
		return $url;
6165
	}
6166
6167
	/**
6168
	 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6169
	 *
6170
	 * @since 4.4.0
6171
	 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6172
	 *
6173
	 * @param array $response
6174
	 * @return array Array of the local urls, wpcom urls, and error code
6175
	 */
6176
	public static function get_sync_error_idc_option( $response = array() ) {
6177
		// Since the local options will hit the database directly, store the values
6178
		// in a transient to allow for autoloading and caching on subsequent views.
6179
		$local_options = get_transient( 'jetpack_idc_local' );
6180
		if ( false === $local_options ) {
6181
			$local_options = array(
6182
				'home'    => Functions::home_url(),
6183
				'siteurl' => Functions::site_url(),
6184
			);
6185
			set_transient( 'jetpack_idc_local', $local_options, MINUTE_IN_SECONDS );
6186
		}
6187
6188
		$options = array_merge( $local_options, $response );
6189
6190
		$returned_values = array();
6191
		foreach ( $options as $key => $option ) {
6192
			if ( 'error_code' === $key ) {
6193
				$returned_values[ $key ] = $option;
6194
				continue;
6195
			}
6196
6197
			if ( is_wp_error( $normalized_url = self::normalize_url_protocol_agnostic( $option ) ) ) {
6198
				continue;
6199
			}
6200
6201
			$returned_values[ $key ] = $normalized_url;
6202
		}
6203
6204
		set_transient( 'jetpack_idc_option', $returned_values, MINUTE_IN_SECONDS );
6205
6206
		return $returned_values;
6207
	}
6208
6209
	/**
6210
	 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6211
	 * If set to true, the site will be put into staging mode.
6212
	 *
6213
	 * @since 4.3.2
6214
	 * @return bool
6215
	 */
6216
	public static function sync_idc_optin() {
6217
		if ( Constants::is_defined( 'JETPACK_SYNC_IDC_OPTIN' ) ) {
6218
			$default = Constants::get_constant( 'JETPACK_SYNC_IDC_OPTIN' );
6219
		} else {
6220
			$default = ! Constants::is_defined( 'SUNRISE' ) && ! is_multisite();
6221
		}
6222
6223
		/**
6224
		 * Allows sites to opt in for IDC mitigation which blocks the site from syncing to WordPress.com when the home
6225
		 * URL or site URL do not match what WordPress.com expects. The default value is either true, or the value of
6226
		 * JETPACK_SYNC_IDC_OPTIN constant if set.
6227
		 *
6228
		 * @since 4.3.2
6229
		 *
6230
		 * @param bool $default Whether the site is opted in to IDC mitigation.
6231
		 */
6232
		return (bool) apply_filters( 'jetpack_sync_idc_optin', $default );
6233
	}
6234
6235
	/**
6236
	 * Maybe Use a .min.css stylesheet, maybe not.
6237
	 *
6238
	 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6239
	 */
6240
	public static function maybe_min_asset( $url, $path, $plugin ) {
6241
		// Short out on things trying to find actual paths.
6242
		if ( ! $path || empty( $plugin ) ) {
6243
			return $url;
6244
		}
6245
6246
		$path = ltrim( $path, '/' );
6247
6248
		// Strip out the abspath.
6249
		$base = dirname( plugin_basename( $plugin ) );
6250
6251
		// Short out on non-Jetpack assets.
6252
		if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6253
			return $url;
6254
		}
6255
6256
		// File name parsing.
6257
		$file              = "{$base}/{$path}";
6258
		$full_path         = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6259
		$file_name         = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6260
		$file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6261
		$extension         = array_shift( $file_name_parts_r );
6262
6263
		if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6264
			// Already pointing at the minified version.
6265
			if ( 'min' === $file_name_parts_r[0] ) {
6266
				return $url;
6267
			}
6268
6269
			$min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6270
			if ( file_exists( $min_full_path ) ) {
6271
				$url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6272
				// If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6273
				if ( 'css' === $extension ) {
6274
					$key                      = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6275
					self::$min_assets[ $key ] = $path;
6276
				}
6277
			}
6278
		}
6279
6280
		return $url;
6281
	}
6282
6283
	/**
6284
	 * If the asset is minified, let's flag .min as the suffix.
6285
	 *
6286
	 * Attached to `style_loader_src` filter.
6287
	 *
6288
	 * @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...
6289
	 * @param string $handle The registered handle of the script in question.
6290
	 * @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...
6291
	 */
6292
	public static function set_suffix_on_min( $src, $handle ) {
6293
		if ( false === strpos( $src, '.min.css' ) ) {
6294
			return $src;
6295
		}
6296
6297
		if ( ! empty( self::$min_assets ) ) {
6298
			foreach ( self::$min_assets as $file => $path ) {
6299
				if ( false !== strpos( $src, $file ) ) {
6300
					wp_style_add_data( $handle, 'suffix', '.min' );
6301
					return $src;
6302
				}
6303
			}
6304
		}
6305
6306
		return $src;
6307
	}
6308
6309
	/**
6310
	 * Maybe inlines a stylesheet.
6311
	 *
6312
	 * If you'd like to inline a stylesheet instead of printing a link to it,
6313
	 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6314
	 *
6315
	 * Attached to `style_loader_tag` filter.
6316
	 *
6317
	 * @param string $tag The tag that would link to the external asset.
6318
	 * @param string $handle The registered handle of the script in question.
6319
	 *
6320
	 * @return string
6321
	 */
6322
	public static function maybe_inline_style( $tag, $handle ) {
6323
		global $wp_styles;
6324
		$item = $wp_styles->registered[ $handle ];
6325
6326
		if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6327
			return $tag;
6328
		}
6329
6330
		if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6331
			$href = $matches[1];
6332
			// Strip off query string
6333
			if ( $pos = strpos( $href, '?' ) ) {
6334
				$href = substr( $href, 0, $pos );
6335
			}
6336
			// Strip off fragment
6337
			if ( $pos = strpos( $href, '#' ) ) {
6338
				$href = substr( $href, 0, $pos );
6339
			}
6340
		} else {
6341
			return $tag;
6342
		}
6343
6344
		$plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6345
		if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6346
			return $tag;
6347
		}
6348
6349
		// If this stylesheet has a RTL version, and the RTL version replaces normal...
6350
		if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6351
			// And this isn't the pass that actually deals with the RTL version...
6352
			if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6353
				// Short out, as the RTL version will deal with it in a moment.
6354
				return $tag;
6355
			}
6356
		}
6357
6358
		$file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6359
		$css  = self::absolutize_css_urls( file_get_contents( $file ), $href );
6360
		if ( $css ) {
6361
			$tag = "<!-- Inline {$item->handle} -->\r\n";
6362
			if ( empty( $item->extra['after'] ) ) {
6363
				wp_add_inline_style( $handle, $css );
6364
			} else {
6365
				array_unshift( $item->extra['after'], $css );
6366
				wp_style_add_data( $handle, 'after', $item->extra['after'] );
6367
			}
6368
		}
6369
6370
		return $tag;
6371
	}
6372
6373
	/**
6374
	 * Loads a view file from the views
6375
	 *
6376
	 * Data passed in with the $data parameter will be available in the
6377
	 * template file as $data['value']
6378
	 *
6379
	 * @param string $template - Template file to load
6380
	 * @param array  $data - Any data to pass along to the template
6381
	 * @return boolean - If template file was found
6382
	 **/
6383
	public function load_view( $template, $data = array() ) {
6384
		$views_dir = JETPACK__PLUGIN_DIR . 'views/';
6385
6386
		if ( file_exists( $views_dir . $template ) ) {
6387
			require_once $views_dir . $template;
6388
			return true;
6389
		}
6390
6391
		error_log( "Jetpack: Unable to find view file $views_dir$template" );
6392
		return false;
6393
	}
6394
6395
	/**
6396
	 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6397
	 */
6398
	public function deprecated_hooks() {
6399
		$filter_deprecated_list = array(
6400
			'jetpack_bail_on_shortcode'                    => array(
6401
				'replacement' => 'jetpack_shortcodes_to_include',
6402
				'version'     => 'jetpack-3.1.0',
6403
			),
6404
			'wpl_sharing_2014_1'                           => array(
6405
				'replacement' => null,
6406
				'version'     => 'jetpack-3.6.0',
6407
			),
6408
			'jetpack-tools-to-include'                     => array(
6409
				'replacement' => 'jetpack_tools_to_include',
6410
				'version'     => 'jetpack-3.9.0',
6411
			),
6412
			'jetpack_identity_crisis_options_to_check'     => array(
6413
				'replacement' => null,
6414
				'version'     => 'jetpack-4.0.0',
6415
			),
6416
			'update_option_jetpack_single_user_site'       => array(
6417
				'replacement' => null,
6418
				'version'     => 'jetpack-4.3.0',
6419
			),
6420
			'audio_player_default_colors'                  => array(
6421
				'replacement' => null,
6422
				'version'     => 'jetpack-4.3.0',
6423
			),
6424
			'add_option_jetpack_featured_images_enabled'   => array(
6425
				'replacement' => null,
6426
				'version'     => 'jetpack-4.3.0',
6427
			),
6428
			'add_option_jetpack_update_details'            => array(
6429
				'replacement' => null,
6430
				'version'     => 'jetpack-4.3.0',
6431
			),
6432
			'add_option_jetpack_updates'                   => array(
6433
				'replacement' => null,
6434
				'version'     => 'jetpack-4.3.0',
6435
			),
6436
			'add_option_jetpack_network_name'              => array(
6437
				'replacement' => null,
6438
				'version'     => 'jetpack-4.3.0',
6439
			),
6440
			'add_option_jetpack_network_allow_new_registrations' => array(
6441
				'replacement' => null,
6442
				'version'     => 'jetpack-4.3.0',
6443
			),
6444
			'add_option_jetpack_network_add_new_users'     => array(
6445
				'replacement' => null,
6446
				'version'     => 'jetpack-4.3.0',
6447
			),
6448
			'add_option_jetpack_network_site_upload_space' => array(
6449
				'replacement' => null,
6450
				'version'     => 'jetpack-4.3.0',
6451
			),
6452
			'add_option_jetpack_network_upload_file_types' => array(
6453
				'replacement' => null,
6454
				'version'     => 'jetpack-4.3.0',
6455
			),
6456
			'add_option_jetpack_network_enable_administration_menus' => array(
6457
				'replacement' => null,
6458
				'version'     => 'jetpack-4.3.0',
6459
			),
6460
			'add_option_jetpack_is_multi_site'             => array(
6461
				'replacement' => null,
6462
				'version'     => 'jetpack-4.3.0',
6463
			),
6464
			'add_option_jetpack_is_main_network'           => array(
6465
				'replacement' => null,
6466
				'version'     => 'jetpack-4.3.0',
6467
			),
6468
			'add_option_jetpack_main_network_site'         => array(
6469
				'replacement' => null,
6470
				'version'     => 'jetpack-4.3.0',
6471
			),
6472
			'jetpack_sync_all_registered_options'          => array(
6473
				'replacement' => null,
6474
				'version'     => 'jetpack-4.3.0',
6475
			),
6476
			'jetpack_has_identity_crisis'                  => array(
6477
				'replacement' => 'jetpack_sync_error_idc_validation',
6478
				'version'     => 'jetpack-4.4.0',
6479
			),
6480
			'jetpack_is_post_mailable'                     => array(
6481
				'replacement' => null,
6482
				'version'     => 'jetpack-4.4.0',
6483
			),
6484
			'jetpack_seo_site_host'                        => array(
6485
				'replacement' => null,
6486
				'version'     => 'jetpack-5.1.0',
6487
			),
6488
			'jetpack_installed_plugin'                     => array(
6489
				'replacement' => 'jetpack_plugin_installed',
6490
				'version'     => 'jetpack-6.0.0',
6491
			),
6492
			'jetpack_holiday_snow_option_name'             => array(
6493
				'replacement' => null,
6494
				'version'     => 'jetpack-6.0.0',
6495
			),
6496
			'jetpack_holiday_chance_of_snow'               => array(
6497
				'replacement' => null,
6498
				'version'     => 'jetpack-6.0.0',
6499
			),
6500
			'jetpack_holiday_snow_js_url'                  => array(
6501
				'replacement' => null,
6502
				'version'     => 'jetpack-6.0.0',
6503
			),
6504
			'jetpack_is_holiday_snow_season'               => array(
6505
				'replacement' => null,
6506
				'version'     => 'jetpack-6.0.0',
6507
			),
6508
			'jetpack_holiday_snow_option_updated'          => array(
6509
				'replacement' => null,
6510
				'version'     => 'jetpack-6.0.0',
6511
			),
6512
			'jetpack_holiday_snowing'                      => array(
6513
				'replacement' => null,
6514
				'version'     => 'jetpack-6.0.0',
6515
			),
6516
			'jetpack_sso_auth_cookie_expirtation'          => array(
6517
				'replacement' => 'jetpack_sso_auth_cookie_expiration',
6518
				'version'     => 'jetpack-6.1.0',
6519
			),
6520
			'jetpack_cache_plans'                          => array(
6521
				'replacement' => null,
6522
				'version'     => 'jetpack-6.1.0',
6523
			),
6524
6525
			'jetpack_lazy_images_skip_image_with_atttributes' => array(
6526
				'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6527
				'version'     => 'jetpack-6.5.0',
6528
			),
6529
			'jetpack_enable_site_verification'             => array(
6530
				'replacement' => null,
6531
				'version'     => 'jetpack-6.5.0',
6532
			),
6533
			'can_display_jetpack_manage_notice'            => array(
6534
				'replacement' => null,
6535
				'version'     => 'jetpack-7.3.0',
6536
			),
6537
			'atd_http_post_timeout'                        => array(
6538
				'replacement' => null,
6539
				'version'     => 'jetpack-7.3.0',
6540
			),
6541
			'atd_service_domain'                           => array(
6542
				'replacement' => null,
6543
				'version'     => 'jetpack-7.3.0',
6544
			),
6545
			'atd_load_scripts'                             => array(
6546
				'replacement' => null,
6547
				'version'     => 'jetpack-7.3.0',
6548
			),
6549
			'jetpack_widget_authors_exclude'               => array(
6550
				'replacement' => 'jetpack_widget_authors_params',
6551
				'version'     => 'jetpack-7.7.0',
6552
			),
6553
			// Removed in Jetpack 7.9.0
6554
			'jetpack_pwa_manifest'                         => array(
6555
				'replacement' => null,
6556
				'version'     => 'jetpack-7.9.0',
6557
			),
6558
			'jetpack_pwa_background_color'                 => array(
6559
				'replacement' => null,
6560
				'version'     => 'jetpack-7.9.0',
6561
			),
6562
			'jetpack_check_mobile'                         => array(
6563
				'replacement' => null,
6564
				'version'     => 'jetpack-8.3.0',
6565
			),
6566
			'jetpack_mobile_stylesheet'                    => array(
6567
				'replacement' => null,
6568
				'version'     => 'jetpack-8.3.0',
6569
			),
6570
			'jetpack_mobile_template'                      => array(
6571
				'replacement' => null,
6572
				'version'     => 'jetpack-8.3.0',
6573
			),
6574
			'jetpack_mobile_theme_menu'                    => array(
6575
				'replacement' => null,
6576
				'version'     => 'jetpack-8.3.0',
6577
			),
6578
			'minileven_show_featured_images'               => array(
6579
				'replacement' => null,
6580
				'version'     => 'jetpack-8.3.0',
6581
			),
6582
			'minileven_attachment_size'                    => array(
6583
				'replacement' => null,
6584
				'version'     => 'jetpack-8.3.0',
6585
			),
6586
			'instagram_cache_oembed_api_response_body'     => array(
6587
				'replacement' => null,
6588
				'version'     => 'jetpack-9.1.0',
6589
			),
6590
			'jetpack_can_make_outbound_https'              => array(
6591
				'replacement' => null,
6592
				'version'     => 'jetpack-9.1.0',
6593
			),
6594
		);
6595
6596
		foreach ( $filter_deprecated_list as $tag => $args ) {
6597
			if ( has_filter( $tag ) ) {
6598
				apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6599
			}
6600
		}
6601
6602
		$action_deprecated_list = array(
6603
			'jetpack_updated_theme'        => array(
6604
				'replacement' => 'jetpack_updated_themes',
6605
				'version'     => 'jetpack-6.2.0',
6606
			),
6607
			'atd_http_post_error'          => array(
6608
				'replacement' => null,
6609
				'version'     => 'jetpack-7.3.0',
6610
			),
6611
			'mobile_reject_mobile'         => array(
6612
				'replacement' => null,
6613
				'version'     => 'jetpack-8.3.0',
6614
			),
6615
			'mobile_force_mobile'          => array(
6616
				'replacement' => null,
6617
				'version'     => 'jetpack-8.3.0',
6618
			),
6619
			'mobile_app_promo_download'    => array(
6620
				'replacement' => null,
6621
				'version'     => 'jetpack-8.3.0',
6622
			),
6623
			'mobile_setup'                 => array(
6624
				'replacement' => null,
6625
				'version'     => 'jetpack-8.3.0',
6626
			),
6627
			'jetpack_mobile_footer_before' => array(
6628
				'replacement' => null,
6629
				'version'     => 'jetpack-8.3.0',
6630
			),
6631
			'wp_mobile_theme_footer'       => array(
6632
				'replacement' => null,
6633
				'version'     => 'jetpack-8.3.0',
6634
			),
6635
			'minileven_credits'            => array(
6636
				'replacement' => null,
6637
				'version'     => 'jetpack-8.3.0',
6638
			),
6639
			'jetpack_mobile_header_before' => array(
6640
				'replacement' => null,
6641
				'version'     => 'jetpack-8.3.0',
6642
			),
6643
			'jetpack_mobile_header_after'  => array(
6644
				'replacement' => null,
6645
				'version'     => 'jetpack-8.3.0',
6646
			),
6647
		);
6648
6649
		foreach ( $action_deprecated_list as $tag => $args ) {
6650
			if ( has_action( $tag ) ) {
6651
				do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6652
			}
6653
		}
6654
	}
6655
6656
	/**
6657
	 * Converts any url in a stylesheet, to the correct absolute url.
6658
	 *
6659
	 * Considerations:
6660
	 *  - Normal, relative URLs     `feh.png`
6661
	 *  - Data URLs                 `data:image/gif;base64,eh129ehiuehjdhsa==`
6662
	 *  - Schema-agnostic URLs      `//domain.com/feh.png`
6663
	 *  - Absolute URLs             `http://domain.com/feh.png`
6664
	 *  - Domain root relative URLs `/feh.png`
6665
	 *
6666
	 * @param $css string: The raw CSS -- should be read in directly from the file.
6667
	 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6668
	 *
6669
	 * @return mixed|string
6670
	 */
6671
	public static function absolutize_css_urls( $css, $css_file_url ) {
6672
		$pattern = '#url\((?P<path>[^)]*)\)#i';
6673
		$css_dir = dirname( $css_file_url );
6674
		$p       = wp_parse_url( $css_dir );
6675
		$domain  = sprintf(
6676
			'%1$s//%2$s%3$s%4$s',
6677
			isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6678
			isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6679
			$p['host'],
6680
			isset( $p['port'] ) ? ":{$p['port']}" : ''
6681
		);
6682
6683
		if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6684
			$find = $replace = array();
6685
			foreach ( $matches as $match ) {
6686
				$url = trim( $match['path'], "'\" \t" );
6687
6688
				// If this is a data url, we don't want to mess with it.
6689
				if ( 'data:' === substr( $url, 0, 5 ) ) {
6690
					continue;
6691
				}
6692
6693
				// If this is an absolute or protocol-agnostic url,
6694
				// we don't want to mess with it.
6695
				if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6696
					continue;
6697
				}
6698
6699
				switch ( substr( $url, 0, 1 ) ) {
6700
					case '/':
6701
						$absolute = $domain . $url;
6702
						break;
6703
					default:
6704
						$absolute = $css_dir . '/' . $url;
6705
				}
6706
6707
				$find[]    = $match[0];
6708
				$replace[] = sprintf( 'url("%s")', $absolute );
6709
			}
6710
			$css = str_replace( $find, $replace, $css );
6711
		}
6712
6713
		return $css;
6714
	}
6715
6716
	/**
6717
	 * This methods removes all of the registered css files on the front end
6718
	 * from Jetpack in favor of using a single file. In effect "imploding"
6719
	 * all the files into one file.
6720
	 *
6721
	 * Pros:
6722
	 * - Uses only ONE css asset connection instead of 15
6723
	 * - Saves a minimum of 56k
6724
	 * - Reduces server load
6725
	 * - Reduces time to first painted byte
6726
	 *
6727
	 * Cons:
6728
	 * - Loads css for ALL modules. However all selectors are prefixed so it
6729
	 *      should not cause any issues with themes.
6730
	 * - Plugins/themes dequeuing styles no longer do anything. See
6731
	 *      jetpack_implode_frontend_css filter for a workaround
6732
	 *
6733
	 * For some situations developers may wish to disable css imploding and
6734
	 * instead operate in legacy mode where each file loads seperately and
6735
	 * can be edited individually or dequeued. This can be accomplished with
6736
	 * the following line:
6737
	 *
6738
	 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6739
	 *
6740
	 * @since 3.2
6741
	 **/
6742
	public function implode_frontend_css( $travis_test = false ) {
6743
		$do_implode = true;
6744
		if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6745
			$do_implode = false;
6746
		}
6747
6748
		// Do not implode CSS when the page loads via the AMP plugin.
6749
		if ( Jetpack_AMP_Support::is_amp_request() ) {
6750
			$do_implode = false;
6751
		}
6752
6753
		/**
6754
		 * Allow CSS to be concatenated into a single jetpack.css file.
6755
		 *
6756
		 * @since 3.2.0
6757
		 *
6758
		 * @param bool $do_implode Should CSS be concatenated? Default to true.
6759
		 */
6760
		$do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6761
6762
		// Do not use the imploded file when default behavior was altered through the filter
6763
		if ( ! $do_implode ) {
6764
			return;
6765
		}
6766
6767
		// We do not want to use the imploded file in dev mode, or if not connected
6768
		if ( ( new Status() )->is_offline_mode() || ! self::is_active() ) {
6769
			if ( ! $travis_test ) {
6770
				return;
6771
			}
6772
		}
6773
6774
		// Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6775
		if ( get_option( 'sharedaddy_disable_resources' ) ) {
6776
			return;
6777
		}
6778
6779
		/*
6780
		 * Now we assume Jetpack is connected and able to serve the single
6781
		 * file.
6782
		 *
6783
		 * In the future there will be a check here to serve the file locally
6784
		 * or potentially from the Jetpack CDN
6785
		 *
6786
		 * For now:
6787
		 * - Enqueue a single imploded css file
6788
		 * - Zero out the style_loader_tag for the bundled ones
6789
		 * - Be happy, drink scotch
6790
		 */
6791
6792
		add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6793
6794
		$version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6795
6796
		wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6797
		wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6798
	}
6799
6800
	function concat_remove_style_loader_tag( $tag, $handle ) {
6801
		if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6802
			$tag = '';
6803
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6804
				$tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6805
			}
6806
		}
6807
6808
		return $tag;
6809
	}
6810
6811
	/**
6812
	 * @deprecated
6813
	 * @see Automattic\Jetpack\Assets\add_aync_script
6814
	 */
6815
	public function script_add_async( $tag, $handle, $src ) {
6816
		_deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6817
	}
6818
6819
	/*
6820
	 * Check the heartbeat data
6821
	 *
6822
	 * Organizes the heartbeat data by severity.  For example, if the site
6823
	 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6824
	 *
6825
	 * Data will be added to "caution" array, if it either:
6826
	 *  - Out of date Jetpack version
6827
	 *  - Out of date WP version
6828
	 *  - Out of date PHP version
6829
	 *
6830
	 * $return array $filtered_data
6831
	 */
6832
	public static function jetpack_check_heartbeat_data() {
6833
		$raw_data = Jetpack_Heartbeat::generate_stats_array();
6834
6835
		$good    = array();
6836
		$caution = array();
6837
		$bad     = array();
6838
6839
		foreach ( $raw_data as $stat => $value ) {
6840
6841
			// Check jetpack version
6842
			if ( 'version' == $stat ) {
6843
				if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6844
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6845
					continue;
6846
				}
6847
			}
6848
6849
			// Check WP version
6850
			if ( 'wp-version' == $stat ) {
6851
				if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6852
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6853
					continue;
6854
				}
6855
			}
6856
6857
			// Check PHP version
6858
			if ( 'php-version' == $stat ) {
6859
				if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6860
					$caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6861
					continue;
6862
				}
6863
			}
6864
6865
			// Check ID crisis
6866
			if ( 'identitycrisis' == $stat ) {
6867
				if ( 'yes' == $value ) {
6868
					$bad[ $stat ] = $value;
6869
					continue;
6870
				}
6871
			}
6872
6873
			// The rest are good :)
6874
			$good[ $stat ] = $value;
6875
		}
6876
6877
		$filtered_data = array(
6878
			'good'    => $good,
6879
			'caution' => $caution,
6880
			'bad'     => $bad,
6881
		);
6882
6883
		return $filtered_data;
6884
	}
6885
6886
	/*
6887
	 * This method is used to organize all options that can be reset
6888
	 * without disconnecting Jetpack.
6889
	 *
6890
	 * It is used in class.jetpack-cli.php to reset options
6891
	 *
6892
	 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6893
	 *
6894
	 * @return array of options to delete.
6895
	 */
6896
	public static function get_jetpack_options_for_reset() {
6897
		return Jetpack_Options::get_options_for_reset();
6898
	}
6899
6900
	/*
6901
	 * Strip http:// or https:// from a url, replaces forward slash with ::,
6902
	 * so we can bring them directly to their site in calypso.
6903
	 *
6904
	 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6905
	 *
6906
	 * @param string | url
6907
	 * @return string | url without the guff
6908
	 */
6909
	public static function build_raw_urls( $url ) {
6910
		_deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
6911
6912
		return ( new Status() )->get_site_suffix( $url );
6913
	}
6914
6915
	/**
6916
	 * Stores and prints out domains to prefetch for page speed optimization.
6917
	 *
6918
	 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
6919
	 *
6920
	 * @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...
6921
	 */
6922
	public static function dns_prefetch( $urls = null ) {
6923
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
6924
		if ( $urls ) {
6925
			Assets::add_resource_hint( $urls );
6926
		}
6927
	}
6928
6929
	public function wp_dashboard_setup() {
6930
		if ( self::is_active() ) {
6931
			add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
6932
		}
6933
6934
		if ( has_action( 'jetpack_dashboard_widget' ) ) {
6935
			$jetpack_logo = new Jetpack_Logo();
6936
			$widget_title = sprintf(
6937
				/* translators: Placeholder is a Jetpack logo. */
6938
				__( 'Stats by %s', 'jetpack' ),
6939
				$jetpack_logo->get_jp_emblem( true )
6940
			);
6941
6942
			// Wrap title in span so Logo can be properly styled.
6943
			$widget_title = sprintf(
6944
				'<span>%s</span>',
6945
				$widget_title
6946
			);
6947
6948
			wp_add_dashboard_widget(
6949
				'jetpack_summary_widget',
6950
				$widget_title,
6951
				array( __CLASS__, 'dashboard_widget' )
6952
			);
6953
			wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
6954
			wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
6955
6956
			// If we're inactive and not in offline mode, sort our box to the top.
6957
			if ( ! self::is_active() && ! ( new Status() )->is_offline_mode() ) {
6958
				global $wp_meta_boxes;
6959
6960
				$dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
6961
				$ours      = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
6962
6963
				$wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
6964
			}
6965
		}
6966
	}
6967
6968
	/**
6969
	 * @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...
6970
	 * @return mixed
6971
	 */
6972
	function get_user_option_meta_box_order_dashboard( $sorted ) {
6973
		if ( ! is_array( $sorted ) ) {
6974
			return $sorted;
6975
		}
6976
6977
		foreach ( $sorted as $box_context => $ids ) {
6978
			if ( false === strpos( $ids, 'dashboard_stats' ) ) {
6979
				// If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6980
				continue;
6981
			}
6982
6983
			$ids_array = explode( ',', $ids );
6984
			$key       = array_search( 'dashboard_stats', $ids_array );
6985
6986
			if ( false !== $key ) {
6987
				// If we've found that exact value in the option (and not `google_dashboard_stats` for example)
6988
				$ids_array[ $key ]      = 'jetpack_summary_widget';
6989
				$sorted[ $box_context ] = implode( ',', $ids_array );
6990
				// We've found it, stop searching, and just return.
6991
				break;
6992
			}
6993
		}
6994
6995
		return $sorted;
6996
	}
6997
6998
	public static function dashboard_widget() {
6999
		/**
7000
		 * Fires when the dashboard is loaded.
7001
		 *
7002
		 * @since 3.4.0
7003
		 */
7004
		do_action( 'jetpack_dashboard_widget' );
7005
	}
7006
7007
	public static function dashboard_widget_footer() {
7008
		?>
7009
		<footer>
7010
7011
		<div class="protect">
7012
			<h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7013
			<?php if ( self::is_module_active( 'protect' ) ) : ?>
7014
				<p class="blocked-count">
7015
					<?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7016
				</p>
7017
				<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>
7018
			<?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7019
				<a href="
7020
				<?php
7021
				echo esc_url(
7022
					wp_nonce_url(
7023
						self::admin_url(
7024
							array(
7025
								'action' => 'activate',
7026
								'module' => 'protect',
7027
							)
7028
						),
7029
						'jetpack_activate-protect'
7030
					)
7031
				);
7032
				?>
7033
							" class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7034
					<?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7035
				</a>
7036
			<?php else : ?>
7037
				<?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7038
			<?php endif; ?>
7039
		</div>
7040
7041
		<div class="akismet">
7042
			<h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7043
			<?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7044
				<p class="blocked-count">
7045
					<?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7046
				</p>
7047
				<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>
7048
			<?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7049
				<a href="
7050
				<?php
7051
				echo esc_url(
7052
					wp_nonce_url(
7053
						add_query_arg(
7054
							array(
7055
								'action' => 'activate',
7056
								'plugin' => 'akismet/akismet.php',
7057
							),
7058
							admin_url( 'plugins.php' )
7059
						),
7060
						'activate-plugin_akismet/akismet.php'
7061
					)
7062
				);
7063
				?>
7064
							" class="button button-jetpack">
7065
					<?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7066
				</a>
7067
			<?php else : ?>
7068
				<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>
7069
			<?php endif; ?>
7070
		</div>
7071
7072
		</footer>
7073
		<?php
7074
	}
7075
7076
	/*
7077
	 * Adds a "blank" column in the user admin table to display indication of user connection.
7078
	 */
7079
	function jetpack_icon_user_connected( $columns ) {
7080
		$columns['user_jetpack'] = '';
7081
		return $columns;
7082
	}
7083
7084
	/*
7085
	 * Show Jetpack icon if the user is linked.
7086
	 */
7087
	function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7088
		if ( 'user_jetpack' == $col && self::is_user_connected( $user_id ) ) {
7089
			$jetpack_logo = new Jetpack_Logo();
7090
			$emblem_html  = sprintf(
7091
				'<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7092
				esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7093
				$jetpack_logo->get_jp_emblem()
7094
			);
7095
			return $emblem_html;
7096
		}
7097
7098
		return $val;
7099
	}
7100
7101
	/*
7102
	 * Style the Jetpack user column
7103
	 */
7104
	function jetpack_user_col_style() {
7105
		global $current_screen;
7106
		if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7107
			?>
7108
			<style>
7109
				.fixed .column-user_jetpack {
7110
					width: 21px;
7111
				}
7112
				.jp-emblem-user-admin svg {
7113
					width: 20px;
7114
					height: 20px;
7115
				}
7116
				.jp-emblem-user-admin path {
7117
					fill: #00BE28;
7118
				}
7119
			</style>
7120
			<?php
7121
		}
7122
	}
7123
7124
	/**
7125
	 * Checks if Akismet is active and working.
7126
	 *
7127
	 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7128
	 * that implied usage of methods present since more recent version.
7129
	 * See https://github.com/Automattic/jetpack/pull/9585
7130
	 *
7131
	 * @since  5.1.0
7132
	 *
7133
	 * @return bool True = Akismet available. False = Aksimet not available.
7134
	 */
7135
	public static function is_akismet_active() {
7136
		static $status = null;
7137
7138
		if ( ! is_null( $status ) ) {
7139
			return $status;
7140
		}
7141
7142
		// Check if a modern version of Akismet is active.
7143
		if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7144
			$status = false;
7145
			return $status;
7146
		}
7147
7148
		// Make sure there is a key known to Akismet at all before verifying key.
7149
		$akismet_key = Akismet::get_api_key();
7150
		if ( ! $akismet_key ) {
7151
			$status = false;
7152
			return $status;
7153
		}
7154
7155
		// Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7156
		$akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7157
7158
		// 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.
7159
		$recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7160
		// We cache the result of the Akismet key verification for ten minutes.
7161
		if ( ! $akismet_key_state || $recheck ) {
7162
			$akismet_key_state = Akismet::verify_key( $akismet_key );
7163
			set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7164
		}
7165
7166
		$status = 'valid' === $akismet_key_state;
7167
7168
		return $status;
7169
	}
7170
7171
	/**
7172
	 * @deprecated
7173
	 *
7174
	 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7175
	 */
7176
	public static function is_function_in_backtrace() {
7177
		_deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7178
	}
7179
7180
	/**
7181
	 * Given a minified path, and a non-minified path, will return
7182
	 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7183
	 *
7184
	 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7185
	 * root Jetpack directory.
7186
	 *
7187
	 * @since 5.6.0
7188
	 *
7189
	 * @param string $min_path
7190
	 * @param string $non_min_path
7191
	 * @return string The URL to the file
7192
	 */
7193
	public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7194
		return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7195
	}
7196
7197
	/**
7198
	 * Checks for whether Jetpack Backup is enabled.
7199
	 * Will return true if the state of Backup is anything except "unavailable".
7200
	 *
7201
	 * @return bool|int|mixed
7202
	 */
7203
	public static function is_rewind_enabled() {
7204
		if ( ! self::is_active() ) {
7205
			return false;
7206
		}
7207
7208
		$rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7209
		if ( false === $rewind_enabled ) {
7210
			jetpack_require_lib( 'class.core-rest-api-endpoints' );
7211
			$rewind_data    = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7212
			$rewind_enabled = ( ! is_wp_error( $rewind_data )
7213
				&& ! empty( $rewind_data['state'] )
7214
				&& 'active' === $rewind_data['state'] )
7215
				? 1
7216
				: 0;
7217
7218
			set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7219
		}
7220
		return $rewind_enabled;
7221
	}
7222
7223
	/**
7224
	 * Return Calypso environment value; used for developing Jetpack and pairing
7225
	 * it with different Calypso enrionments, such as localhost.
7226
	 *
7227
	 * @since 7.4.0
7228
	 *
7229
	 * @return string Calypso environment
7230
	 */
7231
	public static function get_calypso_env() {
7232
		if ( isset( $_GET['calypso_env'] ) ) {
7233
			return sanitize_key( $_GET['calypso_env'] );
7234
		}
7235
7236
		if ( getenv( 'CALYPSO_ENV' ) ) {
7237
			return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7238
		}
7239
7240
		if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7241
			return sanitize_key( CALYPSO_ENV );
7242
		}
7243
7244
		return '';
7245
	}
7246
7247
	/**
7248
	 * Returns the hostname with protocol for Calypso.
7249
	 * Used for developing Jetpack with Calypso.
7250
	 *
7251
	 * @since 8.4.0
7252
	 *
7253
	 * @return string Calypso host.
7254
	 */
7255
	public static function get_calypso_host() {
7256
		$calypso_env = self::get_calypso_env();
7257
		switch ( $calypso_env ) {
7258
			case 'development':
7259
				return 'http://calypso.localhost:3000/';
7260
			case 'wpcalypso':
7261
				return 'https://wpcalypso.wordpress.com/';
7262
			case 'horizon':
7263
				return 'https://horizon.wordpress.com/';
7264
			default:
7265
				return 'https://wordpress.com/';
7266
		}
7267
	}
7268
7269
	/**
7270
	 * Handles activating default modules as well general cleanup for the new connection.
7271
	 *
7272
	 * @param boolean $activate_sso                 Whether to activate the SSO module when activating default modules.
7273
	 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7274
	 * @param boolean $send_state_messages          Whether to send state messages.
7275
	 * @return void
7276
	 */
7277
	public static function handle_post_authorization_actions(
7278
		$activate_sso = false,
7279
		$redirect_on_activation_error = false,
7280
		$send_state_messages = true
7281
	) {
7282
		$other_modules = $activate_sso
7283
			? array( 'sso' )
7284
			: array();
7285
7286
		if ( $active_modules = Jetpack_Options::get_option( 'active_modules' ) ) {
7287
			self::delete_active_modules();
7288
7289
			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...
7290
		} else {
7291
			self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages );
7292
		}
7293
7294
		// Since this is a fresh connection, be sure to clear out IDC options
7295
		Jetpack_IDC::clear_all_idc_options();
7296
7297
		if ( $send_state_messages ) {
7298
			self::state( 'message', 'authorized' );
7299
		}
7300
	}
7301
7302
	/**
7303
	 * Returns a boolean for whether backups UI should be displayed or not.
7304
	 *
7305
	 * @return bool Should backups UI be displayed?
7306
	 */
7307
	public static function show_backups_ui() {
7308
		/**
7309
		 * Whether UI for backups should be displayed.
7310
		 *
7311
		 * @since 6.5.0
7312
		 *
7313
		 * @param bool $show_backups Should UI for backups be displayed? True by default.
7314
		 */
7315
		return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7316
	}
7317
7318
	/*
7319
	 * Deprecated manage functions
7320
	 */
7321
	function prepare_manage_jetpack_notice() {
7322
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7323
	}
7324
	function manage_activate_screen() {
7325
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7326
	}
7327
	function admin_jetpack_manage_notice() {
7328
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7329
	}
7330
	function opt_out_jetpack_manage_url() {
7331
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7332
	}
7333
	function opt_in_jetpack_manage_url() {
7334
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7335
	}
7336
	function opt_in_jetpack_manage_notice() {
7337
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7338
	}
7339
	function can_display_jetpack_manage_notice() {
7340
		_deprecated_function( __METHOD__, 'jetpack-7.3' );
7341
	}
7342
7343
	/**
7344
	 * Clean leftoveruser meta.
7345
	 *
7346
	 * Delete Jetpack-related user meta when it is no longer needed.
7347
	 *
7348
	 * @since 7.3.0
7349
	 *
7350
	 * @param int $user_id User ID being updated.
7351
	 */
7352
	public static function user_meta_cleanup( $user_id ) {
7353
		$meta_keys = array(
7354
			// AtD removed from Jetpack 7.3
7355
			'AtD_options',
7356
			'AtD_check_when',
7357
			'AtD_guess_lang',
7358
			'AtD_ignored_phrases',
7359
		);
7360
7361
		foreach ( $meta_keys as $meta_key ) {
7362
			if ( get_user_meta( $user_id, $meta_key ) ) {
7363
				delete_user_meta( $user_id, $meta_key );
7364
			}
7365
		}
7366
	}
7367
7368
	/**
7369
	 * Checks if a Jetpack site is both active and not in offline mode.
7370
	 *
7371
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7372
	 *
7373
	 * @deprecated 8.8.0
7374
	 *
7375
	 * @return bool True if Jetpack is active and not in offline mode.
7376
	 */
7377
	public static function is_active_and_not_development_mode() {
7378
		_deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7379
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7380
			return false;
7381
		}
7382
		return true;
7383
	}
7384
7385
	/**
7386
	 * Checks if a Jetpack site is both active and not in offline mode.
7387
	 *
7388
	 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7389
	 *
7390
	 * @since 8.8.0
7391
	 *
7392
	 * @return bool True if Jetpack is active and not in offline mode.
7393
	 */
7394
	public static function is_active_and_not_offline_mode() {
7395
		if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7396
			return false;
7397
		}
7398
		return true;
7399
	}
7400
7401
	/**
7402
	 * Returns the list of products that we have available for purchase.
7403
	 */
7404
	public static function get_products_for_purchase() {
7405
		$products = array();
7406
		if ( ! is_multisite() ) {
7407
			$products[] = array(
7408
				'key'               => 'backup',
7409
				'title'             => __( 'Jetpack Backup', 'jetpack' ),
7410
				'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7411
				'learn_more'        => __( 'Which backup option is best for me?', 'jetpack' ),
7412
				'description'       => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7413
				'options_label'     => __( 'Select a backup option:', 'jetpack' ),
7414
				'options'           => array(
7415
					array(
7416
						'type'        => 'daily',
7417
						'slug'        => 'jetpack-backup-daily',
7418
						'key'         => 'jetpack_backup_daily',
7419
						'name'        => __( 'Daily Backups', 'jetpack' ),
7420
						'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7421
					),
7422
					array(
7423
						'type'        => 'realtime',
7424
						'slug'        => 'jetpack-backup-realtime',
7425
						'key'         => 'jetpack_backup_realtime',
7426
						'name'        => __( 'Real-Time Backups', 'jetpack' ),
7427
						'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7428
					),
7429
				),
7430
				'default_option'    => 'realtime',
7431
				'show_promotion'    => true,
7432
				'discount_percent'  => 70,
7433
				'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7434
			);
7435
7436
			$products[] = array(
7437
				'key'               => 'scan',
7438
				'title'             => __( 'Jetpack Scan', 'jetpack' ),
7439
				'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7440
				'learn_more'        => __( 'Learn More', 'jetpack' ),
7441
				'description'       => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7442
				'show_promotion'    => true,
7443
				'discount_percent'  => 30,
7444
				'options'           => array(
7445
					array(
7446
						'type' => 'scan',
7447
						'slug' => 'jetpack-scan',
7448
						'key'  => 'jetpack_scan',
7449
						'name' => __( 'Daily Scan', 'jetpack' ),
7450
					),
7451
				),
7452
				'default_option'    => 'scan',
7453
				'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7454
			);
7455
		}
7456
7457
		$products[] = array(
7458
			'key'               => 'search',
7459
			'title'             => __( 'Jetpack Search', 'jetpack' ),
7460
			'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7461
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7462
			'description'       => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7463
			'label_popup'       => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7464
			'options'           => array(
7465
				array(
7466
					'type' => 'search',
7467
					'slug' => 'jetpack-search',
7468
					'key'  => 'jetpack_search',
7469
					'name' => __( 'Search', 'jetpack' ),
7470
				),
7471
			),
7472
			'tears'             => array(),
7473
			'default_option'    => 'search',
7474
			'show_promotion'    => false,
7475
			'included_in_plans' => array( 'search-plan' ),
7476
		);
7477
7478
		$products[] = array(
7479
			'key'               => 'anti-spam',
7480
			'title'             => __( 'Jetpack Anti-Spam', 'jetpack' ),
7481
			'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' ),
7482
			'learn_more'        => __( 'Learn More', 'jetpack' ),
7483
			'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' ),
7484
			'options'           => array(
7485
				array(
7486
					'type' => 'anti-spam',
7487
					'slug' => 'jetpack-anti-spam',
7488
					'key'  => 'jetpack_anti_spam',
7489
					'name' => __( 'Anti-Spam', 'jetpack' ),
7490
				),
7491
			),
7492
			'default_option'    => 'anti-spam',
7493
			'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7494
		);
7495
7496
		return $products;
7497
	}
7498
}
7499